日期:2014-05-17  浏览次数:20802 次

请高手帮我看一下为什么这个filter没有起到作用?
在练习写servlet和filter, 但是下面写的filter 为什么没有起到做作, 请专家们帮忙看一下!
开发环境: Eclipse Javaee + Tomcat 6

我在filter中的doFilter() 方法中加放了System.out.println("do Filter"), 
在提交表单的时候,要终端里可以打印出这行代码,
但是filter的就是没有起来作用。

filter的作用:
当用输入"hello"的时候,把它替换为"world",


第一个message.jsp 代码如下:
HTML code

<body>
    <h1>留言薄</h1>
    <form action="messageServlet" method="post">
        姓名:<br />
        <input type="text" name="username" /><br />
        留言:<br />
        <textarea rows="10" cols="20" name="message" ></textarea><br />
        <input type="submit" value="Submit" />    
    </form>    
</body>




messageFilter.java 代码如下:
Java code

package com.shy.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.HttpServletResponse;

public class messageFilter implements Filter
{

    @Override
    public void destroy()
    {
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException
    {        
        //HttpServletRequest req = (HttpServletRequest)request;
        //HttpServletResponse resp = (HttpServletResponse)response;
        
        String username = request.getParameter("username");
        String message = request.getParameter("message");
        
        if(username.equals("hello"))
        {
            username = "world";
        }
        
        System.out.println("Do Filter");
        chain.doFilter(request,response);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException
    {
        System.out.println("Filter start");
    }    
}




messageServlet代码如下:
Java code

package com.shy.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class messageServlet extends HttpServlet 
{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        
        String username = req.getParameter("username");
        String message = req.getParameter("message");        
                
        req.setAttribute("username", username);
        req.setAttribute("message", message);
        
        Re