This article describes how to configure a controller to handle URL paths, request parameters, and so on in Springmvc.
requestmapping annotation Function:
Spring MVC uses @RequestMapping annotations to specify which URL requests can be processed by the controller.
@requestmapping can be annotated at the controller's class definition and method definition
- At the class definition: Provides preliminary request mapping information. The root directory relative to the WEB app
- Method: Provides further subdivision mapping information. Relative to the URL at the class definition. If @RequestMapping is not marked at the class definition, the URL marked at the method
The root directory relative to the web App
@RequestMapping Common Properties:
- Value: Represents the request URL
- Path: Represents the request URL
- Method: means the request
- Params: Indicates request parameters
- Heads: Represents the mapping criteria for a request header
There is a relationship between them, and using multiple conditions together can make the request mapping more precise.
Dispatcherservlet intercepts the request, it determines the processing method corresponding to the request through the mapping information provided by @RequestMapping on the controller.
Example
@Controller @requestmapping ( "/user" ) public class Usercontroller {@RequestMapping ( "/login" ) public String login (@requestparam (value =" username ", required= True ) String username, @RequestParam (value = " Password ", Required=true ) String password) {system.out . println (" login Username: " +username+ +password); return "login" ; }}
Test Request URL
Http://localhost:8080/webapp/user/login?username=ricky&password=123
Requestparam annotation Function:
You can pass the request parameter to the request method by using @RequestParam at the processing method entry.
@RequestParam contains 3 properties:
- Value: Name of parameter
- Required: Whether it is necessary. The default is true, which indicates that the request parameter must contain a corresponding-parameter, which, if not present, throws an exception
- DefaultValue: Default value
Example:
@RequestMapping("/login") publiclogin(@RequestParam(value="username", required=true) String username, @RequestParam(value="password", required=true)String password) { System.out.println("login username:"+username+",password:"+password); return"login"; }
Test Request URL
Http://localhost:8080/webapp/user/login?username=ricky&password=123
Attention
The value of the @RequestParam Value property can be inconsistent with the parameter name of the controller processing method, for example:
@RequestMapping("/logout") publiclogout(@RequestParam(value="username", required=true) String name){ System.out.println("logout username:"+name); return"logout"; }
Test Request URL:
Http://localhost:8080/webapp/user/logout?username=demo
pathvariable annotation Function:
By @PathVariable You can bind a placeholder parameter in a URL to an entry in the Controller processing method: the {XXX} placeholder in the URL can be bound to the entry of an action method by @pathvariable ("xxx").
Example:
@RequestMapping("/login/{username}") publiclogin(@PathVariable("username") String username) { System.out.println("login username:"+username); return"login"; }
Test Request URL
Http://localhost:8080/webapp/restuser/login/ricky
Requestheader annotation function
The request header contains several header properties that the server can learn about the client and bind the property values in the request header to the parameters of the processing method by @RequestHeader
Example
@RequestMapping("/header") public String header(@RequestHeader("Accept-Encoding"@RequestParam("name") String name){ System.out.println("header encoding:"+encoding); return"header"; }
Test Request URL
Http://localhost:8080/webapp/param/header?name=abc
cookievalue annotation function
@CookieValue can? Bind a Cookie value to the processing method entry parameter.
Example
@RequestMapping("/cookie") public String cookie(@CookieValue("JSESSIONID"@RequestParam("age"int age){ System.out.println("cookie sessionId:"+sessionId); return"login"; }
Test Request URL
Http://localhost:8080/webapp/param/cookie?age=21
Using the Pojo object to pass the parameter action
Spring MVC automatically populates the property values with the request parameter name and the POJO property name for automatic matching. Cascading properties are supported.
When the controller's processing method requires multiple parameters, the use of @requestparam is very bloated, we can map the request parameters to a Pojo object.
Example
1. User registration request (Post form submission )
The registration page register_form.jsp as follows:
<! DOCTYPE html><html><head> <title>Getting started:serving Web Content</title> <meta http-equiv="Content-type" Content="text/html; Charset=utf-8 " /></head><body> <form Action="Param/pojo" method="POST">Username<input type="text" name="username"/> <br>Password<input type="password" name="password"/> <br>Email<input type="text" name="email"/> <br>Age<input type="text" name="Age"/> <br>Province:<input type="text" name="address.province"/> <br>City<input type="text" name="address.city"/> <br> <input type="Submit" value="Submit"/> </form></body></html>
We map the request parameters in the form to a user object, and then pass the user object to the processor's processing method.
The user is defined as follows:
PackageCom.ricky.codelab.webapp.ch2.model; Public class User { PrivateString username;PrivateString password;PrivateString email;Private intAgePrivateAddress address; PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; } PublicStringGetemail() {returnEmail } Public void Setemail(String email) { This. email = email; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } PublicAddressgetaddress() {returnAddress } Public void setaddress(Address address) { This. address = Address; }@Override PublicStringtoString() {return "User [username=]+ Username +", password="+ Password +", email="+ Email +", age="+ Age +", address="+ Address +"]"; }}
The address is defined as follows:
PackageCom.ricky.codelab.webapp.ch2.model; Public class Address { PrivateString Province;PrivateString City; PublicStringgetprovince() {returnProvince; } Public void setprovince(String Province) { This. province = Province; } PublicStringgetcity() {returnCity } Public void setcity(String city) { This. City = City; }@Override PublicStringtoString() {return "Address [province="+ Province +", city="+ City +"]"; }}
Register Request Processor Pojocontroller
@RequestMapping(value="/pojo", method=RequestMethod.POST) publicregister(User user){ System.out.println("pojo user:"+user); return"login"; }
2, get the way to submit
@RequestMapping(value="/pojo_get", method=RequestMethod.GET) publicregisterByGet(User user){ System.out.println("get pojo user:"+user); return"login"; }
Test Request URL
post:http://localhost:8080/webapp/register_form.jsp
get:http://localhost:8080/webapp/param/pojo_get?username=ricky&password=123&[email protected] &age=27&address.province=hubei&&address.city=wuhan
Using the Servlet API as an entry description
The SPRINGMVC supports the process of passing the servlet API as an incoming parameter to the controller.
The types that can be received are as follows:
- HttpServletRequest
- HttpServletResponse
- HttpSession
- Java.security.Principal
- Locale
- InputStream
- OutputStream
- Reader
- Writer
Example
Packagecom. Ricky. Codelab. WebApp. Ch2;Import Javax. servlet. HTTP. HttpServletRequest;Import Javax. servlet. HTTP. HttpServletResponse;import org. Springframework. Stereotype. Controller;import org. Springframework. Web. Bind. Annotation. Requestmapping;@Controller @requestmapping ("/servlet") public class Servletapicontroller {@RequestMapping ("Api_test") Public String Register (httpservletrequest request, httpservletresponse response) {System. out. println("Request:"+request);Return"Login";}}
Springmvc Combat (iii)-controller configuration detailed