敏感词替换的留言板 试试加filter和不加filter两种做法

本文通过实例展示了两种在留言板中实现敏感词过滤的方法:一种是直接在servlet中处理,另一种是使用filter进行过滤。详细步骤包括表单创建、servlet操作以及filter的配置和使用。强调了在使用filter时,需将修改后的字符串重新传给request对象以确保效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一 不加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

简单的转向就可以完事了。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值