过滤器处理Struts2中文乱码的问题(struts2.1.3以后版本)

1、创建过滤器Java类

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class SetCharacterEncodingFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		
		//传递控制到下一个过滤器
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

}
2 、web.xml配置

不适用StrutsPrepareAndExecuteFilter,将所用过滤器放置在StrutsPrepareFilter和StrutsExecuteFilter之间,编码设置为UTF-8。2.1.3版本后不用ActionContextCleanUp

<?xml version="1.0" encoding="UTF-8"?><!--必要-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<filter>
		<filter-name>StrutsPrepareFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>StrutsPrepareFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>SetCharacterEncoding</filter-name>
		<filter-class>com.flowers.with.utils.SetCharacterEncodingFilter</filter-class><!--根据创建过滤器所在的位置填写-->
	</filter>
	<filter-mapping>
		<filter-name>SetCharacterEncoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<filter>
		<filter-name>StrutsExecuteFilter</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>StrutsExecuteFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
3、struts.xml配置编码设置为UTF-8

<?xml version="1.0" encoding="UTF-8"?>

4、JSP配置,JSP页面编码设置为UTF-8,form提交的方法设置成post,默认为get

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%> <!--必要-->
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
	String path = request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!--必要-->
<title>Register</title>
</head>
<body style="background-image: url(../IMAGE/repeat1.jpg)">
	<form action="register" id="registerForm" method="post"><!--方法设置为post-->
	</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值