零xml配置Spring MVC过滤器解决中文参数乱码

由于JSP默认的字符编码为ISO-8859-1,如果request中有中文的话会出现乱码,因此可以使用过滤器设置request的编码

Spring MVC中提供了一个CharacterEncodingFilter,顾名思义就是用来做字符编码的过滤器。因此可以自定义一个Filter来继承它。

方式一:

自定义的Filter(注意不要添加@WebFilter(filterName = "MyFilter",urlPatterns = "/*")注解:

public class MyFilter extends CharacterEncodingFilter{

    public MyFilter(String encoding, boolean forceRequestEncoding, boolean forceResponseEncoding) {
        super(encoding, forceRequestEncoding, forceResponseEncoding);
    }
}

自定义基于Java的初始化器(可定义任意数量)

public class MyInitializer implements WebApplicationInitializer{

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
    //注册Filter
        FilterRegistration.Dynamic dynamic=servletContext.addFilter("myFilter",
                new MyFilter("UTF-8",true,true));
        dynamic.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*"); //映射Filter
    }
}

Controller

@Controller
public class HomeController {

    @RequestMapping(value = "/viewAll")
    public ModelAndView viewAll(String name,String password) {
        ModelAndView mv=new ModelAndView();
        System.out.println("name: "+name);
        System.out.println("password: "+password);
        mv.setViewName("home"); //返回home.jsp
        return mv;
    }
}

登录JSP:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>logintitle>
head>
<body>
<h2>登录界面h2>
<%--不加/mvc的话默认是localhost:8080路径 --%>
<form name="form" action="/mvc/viewAll" method="post">
    <input type="text" name="name"> <br>
    <input type="password" name="password"><br>
    <input type="submit" name="login">
form>
body>
html>

其实不用自定义Filter直接用CharacterEncodingFilter就行了,只是顺便温故一下自定义Filter

方式二:

过滤器的配置一样,不过不是通过初始化器来注册Filter,但这种方式要求Servlet3.0以上

public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
    @Override
    protected Class[] getRootConfigClasses() {
        return new Class[]{RootConfig.class};
    }

    @Override
    protected Class[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //重写该方法注册Filter,该方法的所有Filter都会映射到DispatcherServlet上,因此没必要声明映射路径
    @Override
    protected Filter[] getServletFilters() {
        return new Filter[]{new MyFilter("UTF-8",true,true)};
    }
}

你可能感兴趣的:(web)