1. Jump mode of results

1.1 ModelAndView

Set the ModelAndView object to jump to the specified page based on the name of the view and the view parser (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/" />
    <! - the suffix - >
    <property name="suffix" value=".jsp" />
</bean>
Copy the code

Controller Indicates the Controller

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");
        returnmv; }}Copy the code

1.2 ServletAPI

By setting up the ServletAPI, no view parser is required

  1. Output via HttpServletResponse

  2. Redirect via HttpServletResponse

  3. Forwarding is implemented via HttpServletResponse

    @Controller
    public class ResultGo {
     
        @RequestMapping("/result/t1")
        public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
            rsp.getWriter().println("Hello");
        }
     
        @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 {
            / / forwarding
            req.setAttribute("msg"."/result/t3");
            req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp); }}Copy the code

1.3 for SpringMVC

SpringMVC implements forwarding and redirection, which the view parser may or may not use

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

    @RequestMapping("/rsm2/t2")
    public String test2(a){
        / / redirection
        return "redirect:/index.jsp";
        //hello.do for another request /
        //return "redirect:hello.do";}}Copy the code

2. Data processing

2.1 Processing submitted data

  1. If the parameter name is the same as the parameter name of the processing method, it will be matched automatically

    @RequestMapping("/hello")
    public String hello(String name){
        System.out.println(name);
        return "hello";
    }
    Copy the code
  2. The name of the submitted parameter does not match the name of the processing method and requires manual binding using the @requestParam annotation in the method’s parameter list

    // @requestParam ("username") : specifies the name of the field submitted by username.
    @RequestMapping("/hello")
    public String hello(@RequestParam("username") String name){
        System.out.println(name);
        return "hello";
    }
    Copy the code
  3. You’re submitting an object

    • If an object is submitted, the argument simply uses the object
    @RequestMapping("/user")
    public String user(User user){
        System.out.println(user);
        return "hello";
    }
    Copy the code

3. Data is displayed in the front end

3.1 through the ModelAndView

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");
        returnmv; }}Copy the code

3.2 through the ModelMap

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

3.3 through the Model

@RequestMapping("/ct2/hello")public String hello(@RequestParam("username") String name, Model model){    // Encapsulate the data to be displayed in the view // equivalent to req.setattribute ("name",name); model.addAttribute("msg",name); System.out.println(name); return "test"; }
Copy the code

3.4 Comparison of the three methods

  • Model has only a few methods suitable for storing data, simplifying the operation and understanding of Model objects
  • ModelMap inherits LinkedMap, in addition to implementing some of its own methods, as well as the methods and features of LinkedMap
  • ModelAndView can store data at the same time, can set the returned logical view, control the jump of the display layer

4. Garbled characters

You can modify the filter in the web.xml configuration file. Spring comes with the CharacterEncodingFilter filter

<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>
Copy the code

Custom filters can also be used

package top.linzeliang.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 resolve all garbled get and POST requests */public class GenericEncodingFilter implements Filter {    @Override    public void destroy(a) {}@Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html; charset=UTF-8"); HttpServletRequest = (HttpServletRequest) request; HttpServletRequest = (HttpServletRequest) request; Myrequest = new myRequest (HttpServletRequest); chain.doFilter(myrequest, response); } @override public void init(FilterConfig FilterConfig) throws ServletException {}} It's a wrapper class class MyRequest extends HttpServletRequestWrapper {private it request; Private Boolean hasEncode; Public MyRequest(HttpServletRequest Request) {super(request); public MyRequest(HttpServletRequest Request) {super(request); // super must write this.request = request; } @override public Map getParameterMap() {String method = request.getMethod(); If (method equalsIgnoreCase (" post ")) {/ / post request try {/ / processing post gibberish request. SetCharacterEncoding (" utf-8 "); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }} else if (method.equalSignorecase ("get")) {// Get request Map
      
        parameterMap = request.getParameterMap(); if (! HasEncode) {// Ensure that the get manual encoding logic is run only once for (String parameterName: parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values ! = null) { for (int i = 0; i < values.length; Values [I] = new String(values[I].getBytes(" ISo-8859-1 "), "utF-8 "); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } @override public String getParameter(String name) {Map
       
         parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; @override public String[] getParameterValues(String name) {Map
        
          parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; }}
        ,>
       ,>
      ,>
Copy the code