Spring MVC from Controller How to pass a value to a page
In the actual development, the controller obtains the data (can be processed in the controller, of course, can also originate from the business Logic layer), to the page, the Common way is:
1. Using Modelandview page to transmit value
The background program is as follows:
@RequestMapping (value= "/recivedata", method=requestmethod.get) public Modelandview StartPage () { modelmap map=new modelmap (); User User=new User (); User.setpassword ("123456"); User.setusername ("Zhangsan"); Map.put ("user", user); return New Modelandview ("Recivecontrollerdata", map);}
The page program is as follows:
<Body> <H1>Recive Data from Controller</H1> <BR>user name: ${user.username}<BR>Password: ${user.password}</Body></HTML>
Attention:
Modelandview has a total of seven constructors, in which the parameter model of the constructor can pass parameters. See Modelandview's documentation, model is a map object in which the key and value values are set, which can then be removed from the view.
From the parameter definition map<string,?> model, it is known that any map object, can be used as Modeandview parameters.
2, Modelmap as function parameter call mode
@RequestMapping (value= "/recivedata2", method=requestmethod.get) public Modelandview StartPage2 (Modelmap map) { user user=new User (); User.setpassword ("123456"); User.setusername ("Zhangsan"); Map.put ("user", user); return New Modelandview ("Recivecontrollerdata");}
3. Using @modelattribute annotations
Method 1: @modelAttribute used on function parameters, can be uploaded to the page by httpservletrequest on the page side
@RequestMapping (value= "/recivedata3", method=requestmethod.get) public Modelandview StartPage3 (@ModelAttribute ("user") user user) { user.setpassword ("123456"); User.setusername ("Zhangsan"); return New Modelandview ("Recivecontrollerdata"); }
View Code
Method 2: Use the @ModelAttribute on the property
@RequestMapping (value= "/recivedata4", method=requestmethod.get) PublicModelandview StartPage4 () {sthname= "LiSi"; return NewModelandview ("Recivecontrollerdata");} /*Be sure to have the Sthname property and take the @modelattribute property on the Get property*/ PrivateString Sthname; @ModelAttribute ("Name") PublicString GetName () {returnSthname; }
View Code
4. Using @modelattribute annotations
/* Save the value directly with the HttpServletRequest session.
* */
@RequestMapping (value= "/recivedata5", method=requestmethod.get) public Modelandview StartPage5 (HttpServletRequest request) { user user=new User (); User.setpassword ("123456"); User.setusername ("Zhangsan"); HttpSession session=request.getsession (); Session.setattribute ("user", user); return New Modelandview ("Recivecontrollerdata");}
View Code
How Spring MVC passes values from a controller to a page