springmvc配置filter

本文主要介绍了如何在Spring MVC中配置Filter来解决乱码问题。通过创建Filter实现类并进行web.xml配置,确保/*路径下的请求能正确处理中文字符,避免乱码的出现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

有时候我们会遇到乱码问题,比如:
接收前端的字符串如果是中文字符时会出现乱码。

这里,我们先写一个test.jsp

<%--
  Created by IntelliJ IDEA.
  User: daodai
  Date: 2020/7/31
  Time: 19:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>test</title>
</head>
<body>
    <form action="/hello" method="post">
        <input type="text" name="username">111
        <input type="submit" value="提交">
    </form>

</body>
</html>

访问/test时,跳转到test页面

@GetMapping("/test")
    public String test(Model model){
        return "test";
    }

在test页面上输入中文字符并进行提交,跳到hello页面,并显示输入的中文字符

    @PostMapping("/hello")
    public String hello1(String username,Model model){
        model.addAttribute("msg", username);
        return "hello";
    }
<%--
  Created by IntelliJ IDEA.
  User: daodai
  Date: 2020/7/30
  Time: 22:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello</title>
</head>
<body>
${msg}
</body>
</html>

然而这样显示的内容是乱码。
在这里插入图片描述
要解决这个问题就要使用filter

  • 先创建Filter的实现类
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中如果使用/,.jsp文件不做处理。所以这边要用/*。
<filter>
        <filter-name>encoding-filter</filter-name>
        <filter-class>com.kuang.filter.EncodingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>encoding-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</filter>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值