web 转义特殊字符

在web开发中用户的输入的<>"等特殊字符需要显示的时候会出问题,这样解决方法一般两种:1:验证不可以输入2:对特殊字符进行转义。
本文主要介绍第二种方法。
在那个地方转义呢!我的方法是在过滤器中进行转义。代码如下:

public class MyFilter implements Filter{
    ...
    public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain chain)      throws IOException, ServletException{
          chain.doFilter(new MyRequest(request), response);
}
    class MyRequest extends HttpServletRequestWrapper{

public MyRequest(HttpServletRequest request) {
super(request);
}

@Override
public Map getParameterMap() {//重写这个方法
Map map = super.getParameterMap();
Set<String> set = map.keySet();
if (set != null){
for (String key:set){
Object obj = map.get(key);
if (obj instanceof String[]){
String[] array = (String[])obj;
for (int i = 0; i < array.length; ++i){
array[i] = array[i].replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
}
}else if (obj instanceof String){
String str = (String)obj;
str = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
map.put(key, str);
}
}
}
return map;
}
}
}

猜你喜欢

转载自yeswoyaofei.iteye.com/blog/1513696