欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

cookie、session和java过滤器结合实现登陆程序

程序员文章站 2024-03-11 16:28:07
cookie、session和过滤器通常都是用在web应用中,cookie和session用来保存一定的数据,过滤器filter则是在浏览器发出请求之后,而后台执行特定的请...

cookie、session和过滤器通常都是用在web应用中,cookie和session用来保存一定的数据,过滤器filter则是在浏览器发出请求之后,而后台执行特定的请求之前发生一定的作用。之所以把这三个放一起,是因为有很多时候都会是把他们结合在一起使用,例如有些登陆程序

cookie是浏览器的机制,session是服务器的机制,但是实际上cookie也是由服务器生成的,之后返回给浏览器的,并不是浏览器本身生成。当浏览器发送某个请求时,如果拥有有效的cookie则会把这个cookie带在一起。

之所有会有cookie的使用,是因为http协议原本是无状态协议,也就是说通过http协议本身,服务器不能判断浏览器是否之前访问过。

filter和servlet的写法相似,编写相关代码的时候需要实现filter接口并重写相关的方法,通常更改较多的是dofilter方法。filter代码写好以后如果需要发生效用,需要像配置servlet一样在web.xml中 进行一定的配置。

以下是一个简单的结合cookie、session、servlet和filter的登陆示例代码:

定义一个用户实体类,充当数据库数据,这里使用单例模式,保证只存在一个实例对象:

package models; 
 
/** 
 * 用户信息实体类 
 * 
 * @author tuzongxun123 
 * 
 */ 
public class usermodel { 
  private string username; 
  private string password; 
 
  // 单例模式,保证只有一个用户对象实例 
  public static usermodel getinstance() { 
    usermodel user = new usermodel("zhangsan", "123456"); 
    return user; 
 
  } 
 
  private usermodel(string username, string pasword) { 
    this.username = username; 
    this.password = pasword; 
  } 
 
  public string getusername() { 
    return username; 
  } 
 
  public string getpassword() { 
    return password; 
  } 
 
} 



用户登陆输入信息index.jsp界面,在form表单的action中使用jsp的特性获得项目路径:

<%@ page language="java" import="java.util.*" contenttype="text/html; charset=utf-8" 
  pageencoding="utf-8"%> 
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=utf-8"> 
<title>cookieandfiltertest</title> 
</head> 
<body> 
   <form action="<%=request.getcontextpath() %>/loginservlet" method="post"> 
    username:<input type="text" name="username" /></br> 
    password:<input type="password" name="password" /></br> 
    <input type="submit" value="login"/> 
   </form> 
</body> 
</html> 

对应的后台servlet:

package servlettest; 
 
import java.io.ioexception; 
import javax.servlet.servletexception; 
import javax.servlet.http.cookie; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import javax.servlet.http.httpsession; 
import models.usermodel; 
 
public class loginservlet extends httpservlet { 
 
  @override 
  protected void doget(httpservletrequest req, httpservletresponse resp) 
      throws servletexception, ioexception { 
    this.dopost(req, resp); 
  } 
 
  @override 
  protected void dopost(httpservletrequest req, httpservletresponse resp) 
      throws servletexception, ioexception { 
    string username = req.getparameter("username"); 
    string password = req.getparameter("password"); 
    // 模拟数据库数据 
    usermodel user = usermodel.getinstance(); 
    string dbusername = user.getusername(); 
    string dbpassword = user.getpassword(); 
    if (dbusername.equals(username) && dbpassword.equals(password)) { 
      // 用户名和密码都匹配,证明登陆成功,设置session和cookie 
      httpsession session = req.getsession(); 
      session.setattribute("username", username); 
      session.setattribute("password", password); 
      cookie cookie = new cookie("username", username); 
      cookie cookie2 = new cookie("password", password); 
      // 设置cookie的存储时长 
      cookie.setmaxage(60); 
      cookie2.setmaxage(60); 
      // 把cookie发送给浏览器 
      resp.addcookie(cookie); 
      resp.addcookie(cookie2); 
      // 转发请求到用户列表 
      req.getrequestdispatcher("/userlist").forward(req, resp); 
    } else { 
      // 转发请求到登陆页面 
      req.getrequestdispatcher("index.jsp").forward(req, resp); 
    } 
    ; 
 
  } 
 
} 

上边登陆后跳转的请求:

package servlettest; 
 
import java.io.ioexception; 
import javax.servlet.servletexception; 
import javax.servlet.http.httpservlet; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import models.usermodel; 
 
public class userlistservlet extends httpservlet { 
 
  @override 
  protected void doget(httpservletrequest req, httpservletresponse resp) 
      throws servletexception, ioexception { 
    this.dopost(req, resp); 
  } 
 
  @override 
  protected void dopost(httpservletrequest req, httpservletresponse resp) 
      throws servletexception, ioexception { 
    usermodel user = usermodel.getinstance(); 
    //在浏览器中打印出用户列表书数据 
    resp.getwriter().write( 
        "username:" + user.getusername() + "," + "password:" 
            + user.getpassword()); 
 
  } 
 
} 

项目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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
  id="webapp_id" version="2.5">   
 
 <!-- 访问时的项目名称 --> 
 <display-name>cookieandfiltertest</display-name> 
 <!-- servlet配置 --> 
 <servlet> 
   <servlet-name>login</servlet-name> 
   <servlet-class>servlettest.loginservlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>login</servlet-name> 
   <url-pattern>/loginservlet</url-pattern> 
 </servlet-mapping> 
 
 <servlet> 
   <servlet-name>userlist</servlet-name> 
   <servlet-class>servlettest.userlistservlet</servlet-class> 
 </servlet> 
 <servlet-mapping> 
   <servlet-name>userlist</servlet-name> 
   <url-pattern>/userlist</url-pattern> 
 </servlet-mapping> 
 
 <!-- 过滤器设置,浏览其发送请求后首先会走这里 --> 
 <filter> 
   <filter-name>loginfilter</filter-name> 
   <filter-class>filtertest.filtertest</filter-class> 
 </filter> 
 <filter-mapping> 
   <filter-name>loginfilter</filter-name> 
   <url-pattern>/*</url-pattern> 
 </filter-mapping> 
 
 <!-- 输入项目名访问的默认页面 --> 
 <welcome-file-list> 
  <welcome-file>index.jsp</welcome-file> 
 </welcome-file-list> 
</web-app> 

java过滤器代码:

package filtertest; 
 
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.cookie; 
import javax.servlet.http.httpservletrequest; 
import javax.servlet.http.httpservletresponse; 
import models.usermodel; 
 
public class filtertest 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 uri = req.getrequesturi(); 
    if ("/cookieandfiltertest/loginservlet".equals(uri) 
        || "/cookieandfiltertest/".equals(uri)) { 
      // 放行 
      chain.dofilter(request, response); 
      return; 
    } 
 
    // 不是登陆请求的话,判断是否有cookie 
    cookie[] cookies = req.getcookies(); 
    if (cookies != null && cookies.length > 0) { 
      string username = null; 
      string password = null; 
      // 判断cookie中的用户名和密码是否和数据库中的一致,如果一致则放行,否则转发请求到登陆页面 
      for (cookie cookie : cookies) { 
        if ("username".equals(cookie.getname())) { 
          username = cookie.getvalue(); 
        } 
        if ("password".equals(cookie.getname())) { 
          password = cookie.getvalue(); 
        } 
      } 
      usermodel user = usermodel.getinstance(); 
      if (user.getusername().equals(username) 
          && user.getpassword().equals(password)) { 
        chain.dofilter(request, response); 
        return; 
      } else { 
        // 重定向到登陆界面 
        req.getrequestdispatcher("/index.jsp").forward(req, resp); 
        return; 
      } 
    } else { 
      req.getrequestdispatcher("/index.jsp").forward(req, resp); 
      return; 
    } 
  } 
 
  @override 
  public void init(filterconfig arg0) throws servletexception { 
 
  } 
 
} 

以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。