一 不加filter写成的留言板控制敏感词
1.写表单
<body>
<form action = "commentServlet" method = "post">
username:<input type = "text" name = "username"><br>
comment:<textarea name = "comment">
</textarea><br>
<input type = "submit">
</form>
</body>
2.完成action转向的servlet内容
public class commentServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String username = req.getParameter("username");
String comment = req.getParameter("comment");
username = username.replace("zhang", "li");
comment = comment.replace("wjl", "gcd");
req.setAttribute("username", username);
req.setAttribute("comment", comment);
req.getRequestDispatcher("MyJsp.jsp").forward(req, resp);
}
}
3.完成转发的页面
<body>
username: <%=request.getAttribute("username") %><br>
comment:<%= request.getAttribute("comment")%>
</body>
总结:修改过的字符串如果不重新传给request对象,那就白瞎了。
二、加filter写成的留言板控制敏感词
1.写表单 不变
2.写filter
public class commentFilter implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)arg0;
HttpServletResponse resp = (HttpServletResponse)arg1;
String username = arg0.getParameter("username");
String comment = arg0.getParameter("comment");
username = username.replace("zhang", "li");
comment = comment.replace("wjl", "gcd");
arg0.setAttribute("username", username);
arg0.setAttribute("comment", comment);
arg2.doFilter(arg0, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
}
}
3.在web.xml配置filter 可以在servlet之前配置。
<filter-name>commentf</filter-name>
<filter-class>com.my.filter.commentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>commentf</filter-name>
<url-pattern>/commentServlet</url-pattern>
</filter-mapping>
4.写servlet
简单的转向就可以完事了。