SPRINGMVC (II) - forwarding and redirection, the front end of a data processing request (normal string / object)

1. Forwarding and Redirection

Forwarding: url change (front-end data query fixed template) will not happen

@RequestMapping("/hello1")
    public String hello1(Model model){
        model.addAttribute("msg","Spring01");
        return "hello";  //普通返回
    }

Redirect: url will change (when logging business, jump page)

@RequestMapping("/hello2")
    public String hello2(Model model){
        model.addAttribute("msg","Spring02");
        return "redirect:/index.jsp";
    }

2. The front end of the data processing request

2.1 ordinary strings

@Controller 
@RequestMapping("/user")
public class HelloController {
 //处理前端请求的数据:普通字符串
    @RequestMapping("receive1")
    public String receive(String name,String password,Model model){
        System.out.println("接收到了name=>"+name+" pwd:"+password);
        String str="name:"+name+"pwd:"+password;
        model.addAttribute("msg",str);
        return "hello";
    }
}

Click Start Test: front-end output user name and password
Here Insert Picture Description
if you enter Chinese garbled, garbled can add a filter in web.xml

Such as creating a form in index.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>

  <form action="/login" method="post">
    <p>用户名:
      <input type="text" name="username">
    </p>

    <p>密码:
      <input type="password" name="password">
    </p>
    <input type="submit">

  </form>
  </body>
</html>

Creating LoginController class under control layer controller directory

package com.zz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {

    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        System.out.println("接收到了name=>"+username+" pwd:"+password);
        model.addAttribute("msg",username);
        return "hello";
    }
}

Click Start Test: Enter the Chinese name, the form is submitted
Here Insert Picture Description

Garbled phenomenon:
Here Insert Picture Description
solution: add a garbled filter in web.xml

 <!--SpringMVC 给我们提供了一个乱码过滤器-->
    <filter>
        <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

After restarting the test and found that the phenomenon is not garbled
Here Insert Picture Description
in some extreme cases, garbled filter SpringMVC provides us unable to solve the garbage problem, then you can customize a filter

package com.zz.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;

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

 
    public void destroy() {
    }


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


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

Then, just in web.xml, here replaced by self-defined directory location of the filter can be!
Here Insert Picture Description
If the property name and the control layer in the form front end is inconsistent, as the user name in the form user, and the control layer is a username, the test results are as follows:
Here Insert Picture Description
find the name is null, in order to solve this problem, in the method of parameter control layer before adding annotations @RequestParam ( "user")

 @RequestMapping("/login")
    public String login(@RequestParam("user") String username, String password, Model model){
        System.out.println("接收到了name=>"+username+" pwd:"+password);
        model.addAttribute("msg",username);
        return "hello";
    }

Test results again:
Here Insert Picture Description

2.2 Object

If we receive an object, as long as the front end transmit parameter names and attributes of our objects can be the same!

Create a user class:

package com.zz.pojo;

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}
@RequestMapping("/login2")
    public String login(User user, Model model){
        model.addAttribute("msg",user.getId());
        System.out.println(user.getName());
        System.out.println(user.getPwd());
        return "hello";
    }

LoginController then write in the class under control layer controller directory

 @RequestMapping("/login2")
    public String login(User user, Model model){
        model.addAttribute("msg",user.getId());
        System.out.println(user.getName());
        System.out.println(user.getPwd());
        return "hello";
}

Start Test: id displayed in the page, the console display name and pwd
Here Insert Picture Description
Here Insert Picture Description

Published 54 original articles · won praise 1 · views 2030

Guess you like

Origin blog.csdn.net/nzzynl95_/article/details/104540428