springMVC第二天前端乱码问题解决

项目结构:在这里插入图片描述springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.kuang.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">

        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--BeanNameUrlHandlerMapping : bean-->
</beans>

ControllerDemo02

@Controller
//代表这个类会被Spring接管,被这个注解的类,中的所有方法,如果返回值是String,
//并且有具体可以跳转的页面,那么就会被视图解析器解析
public class ControllerDemo02 {
    @RequestMapping("t2")
    public String test(Model model){
        model.addAttribute("msg","ControllerDemo02");
        return "test";

    }


    @RequestMapping("t3")
    public String test2(Model model){
        model.addAttribute("msg","ControllerDemo02");
        return "test";

    }
}

在这里插入图片描述

@Controller
@RequestMapping("/c3")
public class ControllerDemo03 {
    @RequestMapping("/t1")
    public String test1(Model model){
        model.addAttribute("msg","ControllerDemo03");
        return "test";
    }
}

这个test.jsp是在WEB-INF下面的jsp文件下面body里面写${msg}
在这里插入图片描述//原来的:http://localhost:8080/add?a=1&b=2

@Controller
public class RestFulController {
//原来的:http://localhost:8080/add?a=1&b=2
    //RestFul: http://localhost:8080/add/a/b
   @RequestMapping("/add")
    public String test1(int a,int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为"+res);
        return "test";
    }
}

在这里插入图片描述//RestFul: http://localhost:8080/add/a/b

@Controller
public class RestFulController {
//原来的:http://localhost:8080/add?a=1&b=2
    //RestFul: http://localhost:8080/add/a/b
   @RequestMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable int b, Model model){
        int res=a+b;
        model.addAttribute("msg","结果为"+res);
        return "test";
    }
}

在这里插入图片描述


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/add/1/3" method="post">
    <input type="submit">
</form>
</body>
</html>

http://localhost:8080/a.jsp
提交
在这里插入图片描述
在这里插入图片描述// //RestFul:简洁、高效、 安全

我们把视图解析器注释掉:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.kuang.controller"/>
    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

    <!--视图解析器-->
   <!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">

        &lt;!&ndash;前缀&ndash;&gt;
        <property name="prefix" value="/WEB-INF/jsp/"/>
        &lt;!&ndash;后缀&ndash;&gt;
        <property name="suffix" value=".jsp"/>
    </bean>
    &lt;!&ndash;BeanNameUrlHandlerMapping : bean&ndash;&gt;
    <bean name="/hello" class="com.kuang.controller.ControllerDemo01"/>-->
</beans>
@Controller
public class ModuleTest {
    @RequestMapping("/m1/t1")
    public  String test1(Model model){
        model.addAttribute("msg","ModuleTest");
        //转发
        return "forward:/WEB-INF/jsp/test.jsp";

    }
//    public String test1(Model model){
//        model.addAttribute("msg","ModuleTest");
//        return "redirect:/index.jsp";
//    }
}

在这里插入图片描述

@Controller
public class ModuleTest {
    @RequestMapping("/m1/t1")
    public  String test1(){
        //转发
        return "redirect:/index.jsp";


    }

}

在这里插入图片描述

@GetMapping("/t2")
    public String test2(User user){
    System.out.println(user);
        return "test";
}

前端传递的参数和对象的名称一致
User(id=1, name=李白, age=18)
在这里插入图片描述前端传递的参数和对象的名称不一致
User(id=1, name=null, age=18)
在这里插入图片描述解决乱码问题1

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/e/t1" method="get">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

注意,此方法用post方式提交请求不行,只能用get

@Controller
public class EncodingController {
    @GetMapping ("/e/t1")
    public String test1(String name, Model model, HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        System.out.println(name);
        model.addAttribute("msg" ,name);
        return "test";
    }
}

过滤器实现:

public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        chain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }
}

方式二:
用springmvc 写好的
在web.xml配置文件中配置

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

网上大神写的通用的方法,包括post请求方式也可以
GenericEncodingFilter

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>com.kuang.fileter.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>

提交方式post和get有什么区别?
(1)post是向服务器传送数据;get是从服务器上获取数据。

(2)在客户端,get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。

post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。

(3)对于get方式,服务器端用Request.QueryString获取变量的值,对于post方式,服务器端用Request.Form获取提交的数据。

例如:get 提交Request.QueryString[“aa”].ToString();

post 提交用 Request.Form[“aa”].ToString();

(4)get可以传送的数据量则非常小,只能有1024字节,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。

(5)安全性问题。正如在(1)中提到,使用 get 的时候,参数会显示在浏览器地址栏上,而 post 不会。

建议:

1、get方式的安全性较post方式要差些,但是执行效率却比post方法好。

如果这些数据是中文数据而且是非敏感数据,那么使用 get;如果用户输入的数据不是中文字符而且包含敏感数据,包含机密信息的话,建议用post数据提交方式为好;

2、在做数据查询时,建议用get方式;而在做数据添加、修改或删除时,建议用post方式;

总结:(简答)

(1)get的参数会显示在浏览器地址栏中,而post的参数不会显示在浏览器地址栏中;

(2)使用post提交的页面在点击【刷新】按钮的时候浏览器一般会提示“是否重新提交”,而get则不会;

(3)用get的页面可以被搜索引擎抓取,而用post的则不可以;

(4)用post可以提交的数据量非常大,而用get可以提交的数据量则非常小(2k),受限于网页地址的长度。

(5)用post可以进行文件的提交,而用get则不可以。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值