Summary of Spring MVC value-Transfer method

Source: Internet
Author: User

Front end upload to controller:

Method 1

Through HttpServletRequest. The wording is as follows:

@Controllerpublic class Mytestcontroller {@RequestMapping ("/print") public String Printinfo (httpservletrequest Request) {System.out.println ("Name:" +request.getparameter ("name")); System.out.println ("Age:" + request.getparameter ("age")); return "Testpage";}}

The HttpServletRequest class is a type in the servlet and represents a servlet request. Both post and get requests can be obtained in this way.

such as the above code, through the Get method, the following address

Http://127.0.0.1:8080/WebApp/print?name=zhangsan&age=30

You can also use the Post method to simulate a POST request using the Postman tool, and you can upload the value to the controller.

This gives you access to cookies and session data.

It is also possible to inject httpservletrequest automatically with annotations @autowired, without worrying about concurrency problems under multithreading, where HttpServletRequest injects an AOP proxy instead of a generic bean. Each time the request comes in, the thread local property is checked to get the real request object. These are the default scenarios that spring automatically configures. You can refer to https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html# Beans-factory-scopes-other-injection

However, this method is not recommended because it destroys the general understanding of an injected object and causes confusion.

The code is as follows:

@Controllerpublic class Mytestcontroller {@Autowiredprivate httpservletrequest request; @RequestMapping (value= "/ print ") public String Printinfo () {System.out.println (" Name: "+request.getparameter (" name ")); System.out.println ("Age:" + request.getparameter ("age")); return "Testpage";}}

Method 2

Use a PATH variable. The wording is as follows:

@Controllerpublic class Mytestcontroller {@RequestMapping ("/print/{name}/{age}") Public String Printinfo (@ Pathvariable String name, @PathVariable int age) {System.out.println ("name:" + name); System.out.println ("Age:" + age); return "Testpage";}}

The {} In the @RequestMapping is the path variable, which also needs to appear in the parameter values of the method, and Mark @pathvariable.

The method of URL matching can be used to achieve both values, which is a method of the rest style.

For the above example, just enter the URL:

Http://127.0.0.1:8080/WebApp/print/ZhangSan/30

The controller receives the value and outputs:

Name:zhangsan

Age:30

@RequestMapping ("/print/{name}/{age}") is an abbreviated form of @requestmapping (value= "/print/{name}/{age}"), essentially the same.

Method 3

How to match the parameter names:

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public string Printinfo (string name, Int. age) {System.out.println ("name:" +name); System.out.println ("Age:" + age); return "Testpage";}}

Or:

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public String Printinfo (@RequestParam (" Name ") String name, @RequestParam (" age ") int age) {System.out.println (" name: "+name); System.out.println ("Age:" + age); return "Testpage";}}

When requesting the incoming parameter name and controller

The name of the code in the same time, both ways can be, the difference is that using the annotation @requestparam, you can set a default value to handle to the null value.

@RequestParam (value= "name", defaultvalue= "John")

However, if the name of the parameter in the request is different from the variable name, only the @requestparam annotation can be used. For example, the requested parameter is as follows:

Http://localhost:8080/WebApp/print?user_name=somename&user_age=30

The controller code can only be written as follows

@RequestMapping (value= "/print") public string Printinfo (@RequestParam ("user_name") string name, @RequestParam ("User_ Age ") int (age) {...}

Use @requestparam annotations as much as possible, because it is clear that the parameter is from request and is readable.

Method 4

Passing parameters in the request header requires the use of the @requestheader annotation, which binds the values in the header to the parameters and can get one, many, or all of the arguments. For example

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public String printinfo (@RequestHeader Map <string, string> Headers) {for (String Elem:headers.keySet ()) {System.out.println (Elem + ":" + headers.get (elem)) ;} return "Testpage";}}

Or

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public String Printinfo (@RequestHeader (" User-agent ") String useragent) {System.out.println (" 12 "); System.out.println ("Name:" +useragent);//system.out.println ("Age:" + age); return "Testpage";}}

Method 5

Use the @requestbody annotation to get the entire requestbody information

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public string Printinfo (@RequestBody string Body) {System.out.println ("body:" +body); return "Testpage";}}

@RequestBody can map JSON data directly to the Java object. For example:

Method 6

With @modelattribute annotations, named matches, the value of the parameter in the post is automatically bound to the parameter value in the model.

@Controllerpublic class Mytestcontroller {@RequestMapping (value= "/print") public String Printinfo (@ModelAttribute User user) {System.out.println ("6"); System.out.println ("Name:" +user.getname ()); System.out.println ("Age:" +user.getage ()); return "Testpage";}} public class User {private string name;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}

Then, when the value of the post has name and age, the user object in the controller automatically attaches a value.

Controller passed to JSP

Method 1

Using the Modelandview class, the code is as follows:

@RequestMapping ("/hello") public Modelandview ShowMessage () {Modelandview mv = new Modelandview ("HelloWorld"); Mv.addobject ("UserList", Getuserlist ()); return MV;} Public list<user> getuserlist () {list<user> lst=new arraylist<user> (); User User1=new User (); User1.setname ("Zhangsan"); user1.setage; Lst.add (user1); User User2=new User (); User2.setname ("Lisi"); User2.setage (+); Lst.add (user2); return lst;}

In the JSP page:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding=" iso-8859-1 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core " %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

When the Modelandview is initialized, the name of the view is set, and the object is stored and passed directly to the view. Simple and practical.


Method 2

Use model or Modelmap

(model is an interface, MODELMAP implements the model interface)

The method is similar to the Modelandview method, except that the model and view are separated by returning a string to find that the View,model is a parameter injected into the controller by adding a property to it and reading the value on the JSP side. The code is as follows:

@Controllerpublic class Helloworldcontroller {String message = "Welcome to Spring mvc!"; @RequestMapping ("/hello") public String ShowMessage (model model) {Model.addattribute ("userlist", Getuserlist ()); return "HelloWorld";} Public list<user> getuserlist () {list<user> lst=new arraylist<user> (); User User1=new User (), User1.setname ("Zhangsan"), User1.setage (Lst.add); User User2=new User (); User2.setname ("Lisi"); user2.setage; Lst.add (user2); return lst;}}

In the JSP page:

<%@ page language= "java" contenttype= "text/html; Charset=iso-8859-1 "pageencoding=" iso-8859-1 "%><%@ taglib prefix=" C "uri=" Http://java.sun.com/jsp/jstl/core " %><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >


This article is from "a blog" blog, make sure to keep this source http://cnn237111.blog.51cto.com/2359144/1894506

Summary of Spring MVC value-Transfer method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.