过滤器复用代码【中文乱码、HTML转义】

中文乱码


public class CharacterEncodingFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp; request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8"); chain.doFilter(new MyRequest(request), response); } public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub } public void destroy() {
// TODO Auto-generated method stub }
} class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request; }
@Override
public String getParameter(String name) { String value = this.request.getParameter(name);
if(value==null){
return null;
}
if(!this.request.getMethod().equalsIgnoreCase("get")){
return value;
}
try {
value = new String(value.getBytes("iso8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return value;
}
}

过滤HTML

public class HtmlFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp; chain.doFilter(new MyRequest2(request), response); } public void destroy() {
// TODO Auto-generated method stub
} public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
} }
class MyRequest2 extends HttpServletRequestWrapper{ private HttpServletRequest request;
public MyRequest2(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) { String value = this.request.getParameter(name);
if(value==null){
return null;
}
return filter(value);
} public String filter(String message) { if (message == null)
return (null); char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("&lt;");
break;
case '>':
result.append("&gt;");
break;
case '&':
result.append("&amp;");
break;
case '"':
result.append("&quot;");
break;
default:
result.append(content[i]);
}
}
return (result.toString()); } }
上一篇:.NET 清理非托管资源


下一篇:Pyqt 屏幕截图工具