初识过滤器

1,这里写的功能是 登录功能 。从login.jsp页面输入用户名,然后判断输入的用户名对不对,如果对了那么跳转到JSP包地下的 index.jsp页面。

   login.jsp页面代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  
     <form action="${pageContext.request.contextPath }/servlet/LoginServlet" method="post">
         <input type="text" name="uname"/>
         <input type="submit" value="登录"/>
     </form>
     
  </body>
</html>

  index.jsp页面代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <h2>index</h2>
  </body>
</html>

  1.1 这里我们定义  servlet  层的 LoginServlet 来接收请求和响应。

LoginServlet 代码如下:

ckage cn.happy.servlet;

import java.io.IOException;

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

public class LoginServlet extends HttpServlet {

	/**
	 *
	 *王志亭	 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * 王志亭	
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			
		String uname = request.getParameter("uname");
		if("admin".equals(uname)){
			//request.getSession().setAttribute("uname", uname);
			request.getRequestDispatcher("/JSP/index.jsp").forward(request, response);
		}else{
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}
		
		
	}

}

  1.2那么问题来了,如果有个人知道了访问页面   index.jsp的路径 那么不用登录也能反问。所以为了避免这个情况 有了  过滤Filter。

      在  myeclipse 这款软件里头没有 Filter 这个过滤器模版,所以使用  类实现Filter接口  类转换成过滤器的方法。

     过滤器的代码如下:

package cn.happy.filter;

import java.io.IOException;
import java.util.regex.Pattern;

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 SessionFilter implements Filter{
	Pattern pattern;
	@Override
	public void init(FilterConfig Config) throws ServletException {
		//我们配置了例外的过滤器不该走的servlet
		String url = Config.getInitParameter("unFilter");
		if(url!=null&&!"".equals(url)){
			pattern= Pattern.compile(url);
		}
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
//因为ServletRequest和ServletResponse里头没有Session,所以我们抢转成他的子接口HttpServletRequest 
    HttpServletRequest req=(HttpServletRequest) request; 
    HttpServletResponse res=(HttpServletResponse) response;
    String path = req.getServletPath();
      if(pattern.matcher(path).matches()){
        chain.doFilter(request, response); return;
      }
    Object obj = req.getSession().getAttribute("uname");
      if(obj!=null){ //已经登录过
         chain.doFilter(request, response);
      }else{
     res.sendRedirect(req.getContextPath()+"/login.jsp");
    }
      }
    @Override
  public void destroy() {
}
}

  因为没有  filter 的模版,所以我们在 web.xml文档中自己配置相关的 代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name></display-name>
  
  <filter>
  	<filter-name>SessionFilter</filter-name>
  	<filter-class>cn.happy.filter.SessionFilter</filter-class>
  		<init-param>
 			<param-name>unFilter</param-name>
 			<param-value>/servlet/(Login|Register)Servlet</param-value>
 		</init-param>
  </filter>
  
  
 
  <filter-mapping>
  		<filter-name>SessionFilter</filter-name>
  		<url-pattern>/JSP/*</url-pattern>
  
  </filter-mapping>
   <filter-mapping>
  		<filter-name>SessionFilter</filter-name>
  		<url-pattern>/servlet/*</url-pattern>
  
  </filter-mapping>
  
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>cn.happy.servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/servlet/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

  

 

posted on 2017-08-17 19:04  蒙古码农  阅读(135)  评论(0编辑  收藏  举报