首页 > 代码库 > javaWeb 使用 filter 处理 html 标签问题
javaWeb 使用 filter 处理 html 标签问题
1.web.xml代码
<filter> <filter-name>HtmlFilter</filter-name> <filter-class>de.bvb.web.filter.HtmlFilter</filter-class> </filter> <filter-mapping> <filter-name>HtmlFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
2.de.bvb.web.filter.HtmlFilter.java 代码
package de.bvb.web.filter; 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.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; public class HtmlFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; chain.doFilter(new HtmlHttpServletRequestWrapper(request), response); } class HtmlHttpServletRequestWrapper extends HttpServletRequestWrapper { private HttpServletRequest request; public HtmlHttpServletRequestWrapper(HttpServletRequest request) { super(request); this.request = request; } @Override public String getParameter(String name) { return filter(request.getParameter(name)); } 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("<"); break; case ‘>‘: result.append(">"); break; case ‘&‘: result.append("&"); break; case ‘"‘: result.append("""); break; default: result.append(content[i]); } } return (result.toString()); } } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
javaWeb 使用 filter 处理 html 标签问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。