实验五、过滤器与监听器

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验五:过滤器与监听器

一、实验目的

1.掌握过滤器的创建与配置方法;

2.掌握监听器的创建与配置方法;

二、实验内容

2.1 创建Web项目

1. 打开MyEclipse,创建一个Web Project,命名为ServletTest。

2.1 SecurityFilter

详细过程见securityFilter.rmvb

1.过滤器SecurityFilter的代码如下:

package filters;

import java.io.IOException;

import java.io.PrintWriter;

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;

public class SecurityFilter implements Filter {

private FilterConfig filterConfig;

public void destroy() {

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request;

// 获得用户输入的密码

String pwdInput = httpRequest.getParameter("password");

// 获得filter配置参数中的rightpass的值

String rightPwd = filterConfig.getInitParameter("rightpass");

if (!rightPwd.equals(pwdInput)) {

PrintWriter out = response.getWriter();

out.println("

Wrong password! Please try again.

");

out.flush();

return;

}

filterChain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig;

}

}

2.LoginServlet的主要代码如下:

package servlets;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

/**

* Constructor of the object.

*/

public LoginServlet() {

super();

}

/**

* Destruction of the servlet.

*/

public void destroy() {

super.destroy(); // Just puts "destroy" string in log

// Put your code here

}

/**

* The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

* @param request the request send by the client to the server

* @param response the response send by the server to the client

* @throws ServletException if an error occurred

* @throws IOException if an error occurred

*/

相关文档
最新文档