5.SpringMVC数据处理

转载:https://blog.kuangstudy.com/index.php/archives/476/

一.SpringMVC数据处理

1.数据处理的场景

  1. 前端数据传递给后端

    1. 提交的域名称和处理方法的参数名一致

    2. 提交的域名称和处理方法的参数名不一致

    3. 提交一个对象

  2. 后端数据传递给前端

    1. 通过ModelAndView

    2. 通过ModelMap

    3. 通过Model

  3. 数据出现乱码问题

    1. 自己写过滤器设置编码格式

    2. SpringMVC自带的过滤器(常用)

    3. 终极版本的过滤器

2.前端数据传递给后端

(1)提交的域名称和处理方法的参数名一致

提交数据 : http://localhost:8080/user/t1?name=你好  , 与处理方法参数name一致

处理方法 :

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {

    @GetMapping("/t1")
    public String test1(String name, Model model) {

        //1.接收前端传递来的参数
        System.out.println("前端传递来的参数为:" + name);
        
        //2.返回结果传递给前端,使用Model
        model.addAttribute("msg",name);

        //3.视图跳转
        return "test";
    }
}

(2)提交的域名称和处理方法的参数名不一致

提交数据 : http://localhost:8080/user/t2?username=你好 , 与处理方法参数不一致添加注解@RequestParam("username")

注:推荐使用注解@RequestParam,当出错时可以显示错误信息为参数错误

处理方法 :

@GetMapping("/t2")
public String test2(@RequestParam("username") String name, Model model) {

    //1.接收前端传递来的参数
    System.out.println("前端传递来的参数为:" + name);

    //2.返回结果传递给前端,使用Model
    model.addAttribute("msg",name);

    //3.视图跳转
    return "test";
}

(3)前端提交一个对象

实体类:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private int id;
    private String name;
    private int age;
}

提交数据 : http://localhost:8080/user/t3?name=王&id=1&age=24

注:参数名必须和对象的属性一致,否则属性值为null

处理方法:

@GetMapping("/t3")
public String test3(User user) {

    System.out.println("前端传递来的参数为:" + user);
    return "test";
}

3.后端数据传递给前端

(1)通过ModelAndView(基本不用)

还要配置 <bean name="/t1" class="ustc.wzh.controller.ControllerTest1"/> 

public class ControllerTest1 implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //返回一个模型视图对象
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","ControllerTest1");
        mv.setViewName("test");
        return mv;
    }
}

(2)通过ModelMap

@GetMapping("/t4")
public String test4(@RequestParam("username") String name, ModelMap model){
    //封装要显示到视图中的数据
    //相当于req.setAttribute("name",name);
    model.addAttribute("msg",name);

    return "test";
}

(3)通过Model(重点)

@GetMapping("/t5")
public String test5(@RequestParam("username") String name, Model model){
    //封装要显示到视图中的数据
    //相当于req.setAttribute("name",name);
    model.addAttribute("msg",name);

    return "test";
}

(4)对比

Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;

ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;

ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。

4.数据出现乱码问题

搭建:

  1. 前端页面

  2. 控制器

在index.jsp同一级的目录下创建form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>测试乱码问题</title>
</head>
<body>
<form action="/e/t1" method="post">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

EncodingController.java

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

@Controller
@RequestMapping("/e")
public class EncodingController {

    @PostMapping("/t1")
    public String test1(String name, Model model){

        model.addAttribute("msg",name);

        return "test";
    }
}

测试发现汉字乱码

(1)自己写过滤器设置编码格式

步骤:

  1. 在controller目录同一级建立filter目录并创建EncodingFilter.java

  2. 在web.xml中注册过滤器

EncodingFilter.java

import javax.servlet.*;
import java.io.IOException;

public class EncodingFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    public void destroy() {

    }
}

在web.xml注册

注意路径 <url-pattern>/*</url-pattern> 

<!--1.自定义过滤器解决乱码问题(可行)-->
<filter>
    <filter-name>encoding</filter-name>
    <filter-class>ustc.wzh.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

测试自定义过滤器可行

(2)SpringMVC自带的过滤器(常用)

直接在web.xml中注册即可

注意: <url-pattern>/*</url-pattern> ,有些极端情况下.这个过滤器对get的支持不好 .

<!--2.使用SpringMVC自带的过滤器处理乱码问题(可行)-->
<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>

测试自定义过滤器可行

(3)终极版本的过滤器

GenericEncodingFilter.java

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

注册web.xml

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>ustc.wzh.filter.GenericEncodingFilter</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>

测试自定义过滤器可行

 

posted @ 2020-02-20 17:28  All_just_for_fun  阅读(376)  评论(0编辑  收藏  举报