spirngMVC (4)-result jump method, data processing, data display to the front end, garbled problem

1 Result jump method

1ModelAndView

Set the ModelAndView object, and jump to the specified page according to the name of the view and the view resolver .
Page: {view resolver prefix} + viewName + {view resolver suffix}

    @GetMapping("/add/{a}/{b}")
    public String add(@PathVariable String a , @PathVariable int b, Model model) {
    
    
        String res = a + b;
        model.addAttribute("msg","结果为:" + res);
        return "hello"; // 视图名称
    }
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

2ServletAPI [not meaningful]

By setting ServletAPI, no view resolver is required.
1 Output
through HttpServletResponse 2 Redirect
through HttpServletResponse 3 Redirect through HttpServletRequest

3SpringMVC [Key Points]

Realize forwarding and redirection through SpringMVC, no view resolver is required,
provided that the view resolver is commented out
Insert picture description here
Insert picture description here

2 data processing

1 processing submitted data

1 The submitted domain name is consistent with the parameter name of the processing method
Insert picture description here
2 The submitted domain name is inconsistent with the parameter name of the processing method
Insert picture description here
3 Submitted is an object
Insert picture description here

3 data display to the front end

1 through ModelAndView

2 through ModelMap

Insert picture description here

3 through Model

Compared

Model has only a few methods that are only suitable for storing data, which simplifies the operation and understanding of Model objects by novices;
ModelMap inherits LinkedMap, in addition to implementing some of its own methods, it also inherits the methods and characteristics of LinkedMap;
ModelAndView can be stored in At the same time of data, you can set the return logic view and control the jump of the display layer.

4 Garbled problem

index.jps

<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2021/1/24
  Time: 14:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <form action="/e/t" method="post">
    <input type="text" name="name">
    <input type="submit">
  </form>
  </body>
</html>

Encoding.java

package com.zs.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class Encoding {
    
    
    @PostMapping("/e/t")
    public String test(@RequestParam("name") String name , Model model) {
    
    
        model.addAttribute("msg",name);
        return "hello";
    }
}

In the test, the
Insert picture description here
garbled problem was solved by a filter, but SpringMVC provides us with a filter, which can be configured in web.xml
to solve the garbled code. Generally this kind of spring can solve it.

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

Insert picture description here
Final solution

<!--    配置过滤器-->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.zs.controller.GenericEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
package com.zs.controller;

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;

/**
 * 解决get和post请求 全部乱码的过滤器
 */
public class GenericEncodingFilter implements Filter {
    
    

    @Override
    public void destroy() {
    
    
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    
    
        //处理response的字符编码
        HttpServletResponse myResponse=(HttpServletResponse) response;
        myResponse.setContentType("text/html;charset=UTF-8");

        // 转型为与协议相关对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 对request包装增强
        HttpServletRequest myrequest = new MyRequest(httpServletRequest);
        chain.doFilter(myrequest, response);
    }

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

}

//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
    
    

    private HttpServletRequest request;
    //是否编码的标记
    private boolean hasEncode;
    //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
    public MyRequest(HttpServletRequest request) {
    
    
        super(request);// super必须写
        this.request = request;
    }

    // 对需要增强方法 进行覆盖
    @Override
    public Map getParameterMap() {
    
    
        // 先获得请求方式
        String method = request.getMethod();
        if (method.equalsIgnoreCase("post")) {
    
    
            // post请求
            try {
    
    
                // 处理post乱码
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
    
    
                e.printStackTrace();
            }
        } else if (method.equalsIgnoreCase("get")) {
    
    
            // get请求
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (!hasEncode) {
    
     // 确保get手动编码逻辑只运行一次
                for (String parameterName : parameterMap.keySet()) {
    
    
                    String[] values = parameterMap.get(parameterName);
                    if (values != null) {
    
    
                        for (int i = 0; i < values.length; i++) {
    
    
                            try {
    
    
                                // 处理get乱码
                                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<String, String[]> parameterMap = getParameterMap();
        String[] values = parameterMap.get(name);
        if (values == null) {
    
    
            return null;
        }
        return values[0]; // 取回参数的第一个值
    }

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

Guess you like

Origin blog.csdn.net/zs18753479279/article/details/113094374