Spring MVC data processing and jump

Posted by chrisprse on Wed, 06 Oct 2021 14:27:25 +0200

1. Result jump method

  • ModelAndView

Set the ModelAndView object, and jump to the specified page according to the name of the view and the view parser

Page: {view parser prefix} + viewName + {view parser suffix}

<!-- view resolver  -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
     id="internalResourceViewResolver">
   <!-- prefix -->
   <property name="prefix" value="/WEB-INF/jsp/" />
   <!-- suffix -->
   <property name="suffix" value=".jsp" />
</bean>

Corresponding controller class

public class ControllerTest1 implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       //Returns a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest");
       mv.setViewName("test");
       return mv;
  }
}
  • ServletAPI

By setting up the servlet API, no view parser is required

1. Output through HttpServletResponse

2. Redirection via HttpServletResponse

3. Forwarding through HttpServletResponse

@Controller
public class ResultGo {

   @RequestMapping("/result/t1")
   public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       rsp.getWriter().println("Hello,Spring BY servlet API");
  }

   @RequestMapping("/result/t2")
   public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
       rsp.sendRedirect("/index.jsp");
  }

   @RequestMapping("/result/t3")
   public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
       //forward
       req.setAttribute("msg","/result/t3");
       req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
  }

}
  • SpringMVC

Forward and redirect through spring MVC - no view parser is required;

Before testing, you need to comment out the view parser

@Controller
public class ResultSpringMVC {
   @RequestMapping("/rsm/t1")
   public String test1(){
       //forward
       return "/index.jsp";
  }

   @RequestMapping("/rsm/t2")
   public String test2(){
       //Forward two
       return "forward:/index.jsp";
  }

   @RequestMapping("/rsm/t3")
   public String test3(){
       //redirect
       return "redirect:/index.jsp";
  }
}

Forward and redirect through spring MVC - view parser;

Redirection does not require a view parser. Its essence is to re request a new place. You need to pay attention to the path problem

You can redirect to another request implementation

@Controller
public class ResultSpringMVC2 {
   @RequestMapping("/rsm2/t1")
   public String test1(){
       //forward
       return "test";
  }

   @RequestMapping("/rsm2/t2")
   public String test2(){
       //redirect
       return "redirect:/index.jsp";
       //return "redirect:hello.do"; //hello.do is another request/
  }
}

2. Data processing

  • Process submitted data

1. The submitted domain name is consistent with the parameter name of the processing method

Submit data: http://localhost:8080/hello?name=zhangsan

Treatment method:

@RequestMapping("/hello")
public String hello(String name){
   System.out.println(name);
   return "hello";
}

Background output: zhangsan

2. The submitted domain name is inconsistent with the parameter name of the processing method

Submit data: http://localhost:8080/hello?username=zhangsan

Treatment method:

//@Requestparam ("username"): the name of the domain submitted by username
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
   System.out.println(name);
   return "hello";
}

Background output: zhangsan

3. Submitted is an object

It is required that the submitted form field and the attribute name of the object are consistent, and the parameter can use the object

1. Entity class

public class User {
   private int id;
   private String name;
   private int age;
   //structure
   //get/set
   //tostring()
}

2. Submit data: http://localhost:8080/mvc/user?name=zhangsan&id=1&age=15

3. Treatment method:

@RequestMapping("/user")
public String user(User user){
   System.out.println(user);
   return "hello";
}

Background output: user {id = 1, name = 'zhangsan', age=15}

Note: if an object is used, the parameter name passed by the front end must be consistent with the object name, otherwise it is null

3. Data display to front end

First: through ModelAndView

public class ControllerTest implements Controller {

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
       //Returns a model view object
       ModelAndView mv = new ModelAndView();
       mv.addObject("msg","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

The second is through ModelMap

@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
   //Encapsulates the data to be displayed in the view
   //Equivalent to req.setAttribute("name",name);
   model.addAttribute("name",name);
   System.out.println(name);
   return "hello";
}

Third: through Model

@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
   //Encapsulates the data to be displayed in the view
   //Equivalent to req.setAttribute("name",name);
   model.addAttribute("msg",name);
   System.out.println(name);
   return "test";
}
  • contrast

For novices, the simple difference is:

  1. Model has only a few methods, which are only suitable for storing data, simplifying novices' operation and understanding of model objects

  2. ModelMap inherits LinkedMap. In addition to implementing some of its own methods, it also inherits the methods and features of LinkedMap

  3. ModelAndView can store data, set the returned logical view, and control the jump of the display layer

  • Garbled code problem

Test steps:

1. We can write a submission form on the home page

<form action="/e/t" method="post">
 <input type="text" name="name">
 <input type="submit">
</form>

2. Write the corresponding processing class in the background

@Controller
public class Encoding {
   @RequestMapping("/e/t")
   public String test(Model model,String name){
       model.addAttribute("msg",name); //Gets the value of the form submission
       return "test"; //Jump to the test page and display the entered value
  }
}

3. Input Chinese test, found garbled code

In the past, the problem of garbled code was solved through filters, and spring MVC provided us with a filter that can be configured in web.xml. After modifying the XML file, we need to restart the server

<filter>
   <filter-name>encoding</filter-name>
   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
   <init-param>
       <param-name>encoding</param-name>
       <param-value>utf-8</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>encoding</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

In some extreme cases, this filter does not support get well

Treatment method:

1. Modify tomcat configuration file: set encoding

<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
          connectionTimeout="20000"
          redirectPort="8443" />

2. Custom filter

package com.kuang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
* Filter to solve all the garbled codes of get and post requests
*/
public class GenericEncodingFilter implements Filter {

   @Override
   public void destroy() {
  }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //Handle the character encoding of the response
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");

       // Transformation into agreement related objects
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // Enhanced request packaging
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
  }

}

//Custom request object, wrapper class of HttpServletRequest
class MyRequest extends HttpServletRequestWrapper {

   private HttpServletRequest request;
   //Coded flag
   private boolean hasEncode;
   //Define a constructor that can be passed into the HttpServletRequest object to decorate it
   public MyRequest(HttpServletRequest request) {
       super(request);// super must write
       this.request = request;
  }

   // Override methods that need to be enhanced
   @Override
   public Map getParameterMap() {
       // Get request method first
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
           // post request
           try {
               // Handle post garbled code
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
           // get request
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) { // Ensure that the get manual encoding logic runs only once
               for (String parameterName : parameterMap.keySet()) {
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
                       for (int i = 0; i < values.length; i++) {
                           try {
                               // Handle get garbled code
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }

   //Take a value
   @Override
   public String getParameter(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // Retrieve the first value of the parameter
  }

   //Take all values
   @Override
   public String[] getParameterValues(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

Then configure this filter in web.xml!

Topics: Java Spring Spring MVC SSM mvc