Spring MVC request mapping and parameters

1 Parameters of the controller method

(1) Acquisition of request parameters

 Coding The first problem in handling HTTP requests is to obtain the parameters submitted by the user. Native HTTP parameters are all of string type, and in traditional Servlets, we need to obtain them through the request object.

String variable = request.getParameter("parameter name");

 If the ID value or date is obtained, non-null judgment and type conversion must be performed. If many form fields are obtained at one time, the code will be lengthy. Almost all MVC frameworks will definitely optimize this simple redundant code. In Spring MVC, we can directly obtain the request parameters submitted by the user in the controller method, as long as the name of the method parameter is the same as the name of the request parameter, and Sprig MVC will automatically perform corresponding type conversion on the parameters. For example, if we want to write a controller method for login verification, we can directly accept the user name submitted by the form.

(username) and password (password).

       Form code:

<form action="check-login" method="post">  	 	
    <input type="text" name="username" />  	 	
    <input type="password" name="password" />  	 	
    <button>登录</button>  	
</form> 

Controller method code:

@RequestMapping(value="/check-login")  	
public String login(String username, String password){ 
} 

(2) Model pushed to View 

 In addition to obtaining request parameters, another most common operation in request processing is to push the data Model in the Controller to the View for display. As mentioned earlier, we can put the data to be pushed to the View into

Map<String, Object>, and then it can be obtained and displayed in the forwarded View.

       Controller method:

@RequestMapping(value="/check-login") 
 public String login(String username, String password, Map<String,Object> model){   
    User loginUser = userBiz.checkLogin(username, password);   
    if(loginUser!=null){    
        return "redirect:/index"; //重定向 
    }else{    
        model.put("message", "用户名或密码有误。");    
        return "login";   //转发 
 	 	} 
 	} 

Also note here is the return value of the controller method.

 If return is followed by a string starting with "redirect: ", it means redirection behavior (equivalent to response.sendRedirect(…)); if not, it means forwarding behavior (equivalent to request.getRequestDispacther(…).forward( ...)).

      In addition to using Map, Spring MVC can also use Model type objects to load Model data.

@RequestMapping(value="/check-login")  	
public String login(String username, String password, Model model){ 
 	 … model.addAttribute("message", "用户名或密码有误。"); … 
} 

 

(3) Using the Servlet API

 The MVC framework optimizes the acquisition of parameters or the push of models. These operations do not require request and response objects, which is the so-called Servlet API. The tediousness of traditional Servlet programming is here, if the code hardly appears

Servlet API, Web programming becomes intuitive and concise.

 Of course, it is impossible for us to completely abandon the Servlet API. This is server programming. For example, what should we do if we want to use Session? So the controller method in Spring MVC also has a third function, which is to pass in the Servlet API we need, whether it is request, response, session, application, etc., as long as you want, directly in the controller method Just declare a parameter.

      The following is the complete login processing method. After the login is successful, store the user information in the session for future use

@RequestMapping(value="/check-login") 
 public String login(HttpSession session, String username, String password, Model model){ 
     User loginUser = userBiz.checkLogin(username, password); 
     if(loginUser!=null){ 
         session.setAttribute("loginUser", loginUser); //session 中保存登录状态 
         return "redirect:/index"; 
     }else{ 
         model.addAttribute("message", "用户名或密码有误。"); 
     return "login"; 
     } 
 } 

2 RequestMapping annotations and REST request style

The @RequestMapping annotation can not only realize the simple mapping from URL to Controller method, but also supports more advanced HTTP request concept, which is the so-called REST style.

REST (Representational State Transfer) is translated into Chinese as "Representational State Transfer". Simply put, it is to use various features of the HTTP protocol to treat a request differently, including the URL, the method of the request, the request header information, etc.; instead of only relying on the URL to distinguish the request. For a server written in strict accordance with the REST style, a URL is equivalent to a business object. The get, post, put, and delete in the request method correspond to the query, addition, modification, and deletion of the object, respectively, and the server can also return according to the needs of the request header. html, json or xml, such a server is not only a website for people to browse, but also an SOA system that can obtain information from different systems such as mobile phones, desktop software, and another server, called REST Web Service.

    In order to support the REST style, @RequestMapping provides the following properties for us to set.

Attributes

Function

value

Specify the actual address of the request, it is an array, you can specify multiple

method

Specify the method type of the request, GET, POST, PUT, DELETE, etc.

consumes

Specify the submitted content type (Content-Type) of the request, such as application/json, text/html;

produces

Specify the content type to return, and only return if the (Accept) type in the request header contains the specified type

params

Specifies that the request must contain certain parameter values ​​before the method can process it

headers

The specified request must contain certain specified header (request header) values ​​in order for the method to process the request

       

      In simple cases, we should at least set the value and method of @RequestMapping. For example, we want the same request address "/login", return a login form for the user to fill out under the get request, and process login verification under the post request, then we can write it as. 

@RequestMapping(value="/login",method=RequestMethod.GET) 
 public String login(){ 
     return "login"; 
 } 
 
 @RequestMapping(value="/login", method=RequestMethod.POST) 
 public String login(HttpSession session, String username, String password, Model model){ 
 }

3 Acquisition of value type parameters

      The following example is a multi-condition pagination controller method to realize the paging query function of movie information.

@RequestMapping("/movie-list") 
 public String movieList( int cid, String title, int page, Model model ){ 
     final int pageSize = 4; 
     List<Movie> movies = movieBiz.getMoviesPagings(cid, title, page, pageSize); 
     int rows = movieBiz.fetchMovieRows(cid, title); 
     int totalPages = rows%pageSize==0?rows/pageSize:rows/pageSize+1; 
     model.addAttribute("totalPages", totalPages); 
     model.addAttribute("page", page); 
     model.addAttribute("movies", movies); 
     model.addAttribute("categories", categoryBiz.getAll()); 
     return "admin/movie-list"; 
} 

         Works well when the request provides a cid parameter and a page parameter.

           But if the cid parameter and page parameter are not provided in the request, it will not work.

 

This is caused by the cid and page parameters of type int. Int is a native type parameter, and the native type cannot put a null value, so when the request parameter is empty, Spring MVC cannot set the method parameter of type int for us! and

The String type parameter title does not matter, because the String parameter can be set to null if it does not exist.

       To solve this problem, you can choose one of the following two options.

 

  1. Use wrapper class (Integer) instead of native type (int) to declare method parameters

The first method is: as long as the parameters of the original value type are not necessary, they should be replaced with wrapper classes.

@RequestMapping("/movie-list") 
 public String movieList( Integer cid, String title, Integer page, Model model){ 
     cid = cid==null? 0 : cid; 
     page = page==null? 1 : page; 
} 

However, you must pay attention to null value processing when using this method, such as "page = page==null? 1 : page;" in the above code, when the page number is null, set the page number to page 1, otherwise it will be in the When the query method executes, a NullPointerException will most likely occur!

 

  1. Use @RequestParam annotation to mark parameters The second method is: use @RequestParam to modify the parameters of the Controller method. @RequestParam This annotation can:
    1. Specify the parameter name of the request parameter through the name attribute, so that the method parameter and the request parameter name can be different;
    2. Use the required attribute to specify whether the request parameter must be provided (true) or optional (false)
    3. Specify the default value when the request parameter is not provided through the defaultValue attribute.
@RequestMapping("/movie-list") 
 public String movieList( 
     @RequestParam(name="cid",required=false,defaultValue="0") int cid, 
     String title, 
     @RequestParam(name="page",required=false,defaultValue="1") int page, 
     Model model) { 

 

This approach is more standard, but the method parameter list looks more complicated.

 

 

4Query String Parameters and Path Parameters

(1) Query String Parameters Continue to implement a modification function for movie information. We want to click the "edit" link in the query list to go to a single information edit page and pass the ID of the record to be modified.

Usually we can use hyperlinks such as "edit?id=2", that is, get request parameters. This method of passing parameters after the "?" in the URL is often called "query string".

 

 The corresponding controller method should be as follows:

@RequestMapping("/edit") 
 public String edit ( Integer id, Model model ) { 
     id = id==null?0:id; 
     if(id>0){ 
         Movie m = movieBiz.fetchById(id); 
         model.addAttribute("movie", m); 
     }     
     model.addAttribute("categories", categoryBiz.getAll()); 
     return "admin/movie-edit"; 
 } 

(2) Path parameters - @PathVariable

       In order to better implement the REST style and optimize the path, Spring MVC also supports path parameter passing using @PathVariable. When using path parameters, we can be on the URL path instead of the ? After passing the parameter value. The control method of the editing function above can be rewritten as:

   

  @RequestMapping( "/edit/{id}" )
  public String edit ( @PathVariable("id") int id, Model model ) {
  }

 In the path attribute of @RequestMapping, declare the position of the path parameter by means of "{parameter name}", and use @PathVariable("parameter name") in the method parameter to receive it. At this time, the request address is as follows: 

 

This parameter does not have to be at the end of the URL, it can be in the middle, but it is usually a mandatory parameter, not an optional parameter. ( When you are a beginner, it is not very recommended to use the "path parameter" method to pass parameters, because it may cause relative path confusion )

  1. object parameter

 When we finish editing a form and submit data, there are often many elements in the form, which correspond to many attributes of an object. It would be troublesome if our controller had to receive scattered parameters, as the following example shows.

@RequestMapping(value="/movie-save", method=RequestMethod.POST) 
public String save ( int id, String title, String movieCode, int categoryId, … ) { 
     //… 执行 movieBiz.add() 或者 movieBiz.update() 
}

 Spring MVC allows us to use objects to receive multiple parameters submitted by the form in one go. By default, as long as the "property name of the object" is consistent with the "name name of the form element". So the controller method that saves the movie modification can get the entire form submission value with just one parameter.

@RequestMapping(value="/movie-save", method=RequestMethod.POST) 
 public String save(Movie movie){ 
     if(movie.getId()>0){ 
         movieBiz.update(movie); 
     }else{ 
         movieBiz.add(movie); 
     } 
     return "redirect:/admin/movie-list"; 
 } 

 

It is worth noting here that the final redirection "redirect:/admin/movie-list", if you want to query the required data after redirection, you may wish to add some query parameters after redirection, such as the following wording.

 

 

  1. The solution to the garbled characters of the POST request

       After the above modification is saved, everyone may see the situation except Chinese garbled characters.

  We know that in JSP technology, GET request garbled characters can be solved by setting the server.xml configuration of the server, while POST request garbled characters should use the code "request.setCharactorEncoding="UTF8"" before obtaining the request data. In Spring MVC, we should not call the Servlet API frequently, so the framework provides us with an encoding filter. By setting the filter, we can specify the encoding settings of the request.

 

<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"  	
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  	
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   	
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> 
<!-- 编码过滤器,解决 Spring MVC 请求参数中文乱码 --> 
 	<filter> 
 	 	<filter-name>encodingFilter</filter-name> 
 	 	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
 	 	<async-supported>true</async-supported> 
 	 	<init-param> 
 	 	 	<param-name>encoding</param-name> 
 	 	 	<param-value>UTF-8</param-value> 
 	 	</init-param> 
 	</filter> 
 	<filter-mapping> 
 	 	<filter-name>encodingFilter</filter-name> 
 	 	<url-pattern>/*</url-pattern> 
 	</filter-mapping> 
     <!-- Spring 容器的启动监听器 --> 
     <listener> 
         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
     </listener> 
     <context-param> 
         <param-name>contextConfigLocation</param-name> 
         <param-value>classpath:spring-beans.xml</param-value> 
     </context-param> 
     <!-- 配置 MVC 框架的核心控制器 --> 
     <servlet> 
         <servlet-name>springmvc</servlet-name> 
         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
         <init-param> 
             <param-name>contextConfigLocation</param-name> 
             <param-value>classpath:spring-mvc.xml</param-value> 
         </init-param> 
         <load-on-startup>1</load-on-startup> 
     </servlet> 
     <servlet-mapping> 
     <servlet-name>springmvc</servlet-name> 
     <url-pattern>/</url-pattern> 
 </servlet-mapping> 
</web-app>

Guess you like

Origin blog.csdn.net/qq_55917018/article/details/127083532