写个 login.jsp 页面
提交的 method 一般为 post(写 get 不安全,地址栏上会显示)
action 表示提交后跳转的地址
(不直接写控制器里的路径是因为配置 Tomcat 时设置了前缀路径,默认走 http://localhost:8080)
html
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<form action="/annotation/demo" method="post">
<input type="text" name="name"/>
<input type="submit"/>
</form>
</body>
</html>
写个控制器
因为提交是 post,所以控制器里也要用 @PostMapping
获取表单提交的值,需要在方法括号里也加上
java
package com.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class Demo {
@PostMapping("/demo")
public String demo(Model model,String name){
model.addAttribute("msg",name); //获取表单提交的值
return "test"; //跳转到 /WEB-INF/jsp/test.jsp显示输入的值
}
}
运行,地址栏后缀输入 login.jsp 回车,输入中文,提交后进入 test.jsp,出现乱码
在审查元素里可以看到,响应是乱码,说明在 Java 层面已经是乱码了
使用过滤器解决乱码
写个类实现 Filter 接口(注意是 servlet 下的 Filter)
重写方法,主要代码写在 doFilter
请求和响应都设置 utf-8
**filterChain.doFilter(servletRequest,servletResponse);**固定写法,必须要加,不然卡死
java
package com.demo.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("utf-8");
//让链继续往下走,不然卡死
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
方法1:web.xml 文件注册
XML
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.demo.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
方法2:配置 SpringMVC 的乱码过滤
XML
<!-- 配置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>
<url-pattern> 路径必须是 /*,如果写 / 还是乱码