SpringMVC-part04 data processing and jump

Keywords: Java Back-end RESTful

4. Data processing and jump

In the previous section, we learned about controllers and Restful style operations

Mad God says spring mvc03: RestFul and controller

Now let's take a look at spring MVC parameter receiving processing and result jump processing!

4.1 result jump method

4.1.1ModelAndView

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","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

4.1.2ServletAPI

By setting 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);
  }

}

4.1.3SpringMVC

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, so 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/
  }

}

4.2 data processing

4.2.1 processing submitted data

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

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

Treatment method:

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

Background output: kuangshen

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

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

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: kuangshen

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/mvc04/user?name=kuangshen&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 = 'kuangshen', 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.

4.2.2 data display to front end

First: through ModelAndView

We've always been like this before. There's no more explanation

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","ControllerTest1");
       mv.setViewName("test");
       return mv;
  }
}

The second is through ModelMap

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

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";
}

4.2.3 comparison

For novices, the simple difference is:

Model There are only a few methods that are only suitable for storing data, which simplifies novices' understanding of data Model Operation and understanding of objects;

ModelMap Inherited LinkedMap ´╝îIn addition to implementing some of its own methods, the same inheritance LinkedMap Methods and characteristics of;

ModelAndView While storing data, you can set the returned logical view to control the jump of the display layer.

Of course, more future development is more about performance and optimization, so it can't be limited to this understanding.

Please use 80% of your time to lay a solid foundation, the remaining 18% to study the framework and 2% to learn some English. The official document of the framework is always the best tutorial.

4.2.4 garbled code

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

It has to be said that the problem of garbled code is very common in our development, and it is also a big problem for our program ape!

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

The xml file has been modified. You 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>

However, we found that in some extreme cases, this filter does not support get well

Treatment method:

1. Modify tomcat configuration file: set code!

<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;
  }
}

This is also written by some great gods I found on the Internet. Generally, the default garbled code processing of spring MVC can be well solved!

Then configure this filter in web.xml!

The problem of garbled code needs more attention at ordinary times. The unified coding UTF-8 should be set wherever possible!

With this knowledge, we can integrate SSM immediately!
This article comes from Bili Bili Madness theory Study notes

Posted by Christoph09 on Sun, 05 Dec 2021 21:04:34 -0800