您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
/**
*
*/
package cn.itcast.test;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* @author 国真
* 继承HttpServletRequestWrapper类是采用了装饰者模式
*/
public class CharSetRequest extends HttpServletRequestWrapper {
public CharSetRequest(HttpServletRequest request) {
super(request); //调用父类的构造器,给父类传递底层对象
}
//增强getParameter()方法
@Override
public String getParameter(String name) {
String value = super.getParameter(name);
//判断当前请求是否为get请求,若是则回退,重解
if (getMethod().equalsIgnoreCase("GET")) {
try {
value = new String(value.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//返回
return value;
}
}
package cn.itcast.test;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
/**
* 处理全站编码问题
* @author 国真
*
*/
public class CharSetFilter implements Filter {
public CharSetFilter() {
// TODO Auto-generated constructor stub
}
//释放
public void destroy() {
// TODO Auto-generated method stub
}
//执行过滤功能
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8"); //只处理post请求
response.setContentType("text/html;charset=utf-8"); //处理响 应的编码
//创建山寨版的request
CharSetRequest req = new CharSetRequest((HttpServletRequest)request);
//放行市把request掉包
chain.doFilter(req, response);
}
//初始化
public void init(FilterConfig fConfig) throws ServletException {
}
}
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>tools</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CharSetFilter</filter-name>
<filter-class>cn.itcast.test.CharSetFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharSetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>VerifyCodeServlet</servlet-name>
<servlet-class>cn.itcast.vcode.servlet.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VerifyCodeServlet</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>
</web-app>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。