html轉義文字---HttpServletRequest物件增強
阿新 • • 發佈:2019-01-09
在表單提交文字時,文字內容本身可能就是一段html格式內容,因此要是不做轉義直接顯示在網頁上時,將會被當做一段html文字進行顯示,這就和本身提交的內容不符,因此可以對request物件進行增強,是提交的資料按其原格式進行顯示。下面是個MyHtmlRequest包裝類,其中filter方法是tomcat中HtmlFilter.java裡的一段原始碼。
Filter:public class MyHtmlRequest extends HttpServletRequestWrapper { private HttpServletRequest request; public MyHtmlRequest(HttpServletRequest request) { super(request); // TODO Auto-generated constructor stub this.request = request; } /* (non-Javadoc) * @see javax.servlet.ServletRequestWrapper#getParameter(java.lang.String) */ @Override public String getParameter(String name) { // TODO Auto-generated method stub String value = 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); StringBuilder result = new StringBuilder(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 doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; MyHtmlRequest myReq = new MyHtmlRequest(request); chain.doFilter(myReq, response); }