动态web项目使用Filter过滤器实现网页自动登录

javabean

package bean;
//封装数据
public class User {
	private int id;
	private String userName;
	private String userPwd;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPwd() {
		return userPwd;
	}
	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}
	
}

数据库工具类

package utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
	private static DataSource ds=new ComboPooledDataSource();
	//获取连接池
	public static DataSource getDataSource() {
		return ds;
	}
	//获取连接
	public static Connection getConn() throws SQLException {
		return ds.getConnection();
	}
}

dao

package dao;
//数据库操作类

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import bean.User;
import utils.DataSourceUtils;

public class LoginDao {
	public User LoginUserNameAndPwd(String userName,String userPwd) throws SQLException {
		//创建QuerRunner对象
		QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
		//创建sql
		String sql="select * from user where username=? and password=?";
		User user = qr.query(sql,new BeanHandler<User>(User.class),userName,userPwd);
		//执行sql
		return user;
	}
}

service

package serice;

import java.sql.SQLException;

import bean.User;
import dao.LoginDao;

public class LoginSerice {
	public User getUserByUsernameAndPwd(String username, String password) throws SQLException {
		// TODO Auto-generated method stub
		//创建LoginDao
		LoginDao ld = new LoginDao();
		return ld.LoginUserNameAndPwd(username,password);
	}

}

验证码的servlet

package servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

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

public class CodeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		// 使用java图形界面技术绘制一张图片

		int charNum = 4;
		int width = 20 * 4;
		int height = 28;

		// 1. 创建一张内存图片
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		// 2.获得绘图对象
		Graphics graphics = bufferedImage.getGraphics();

		// 3、绘制背景颜色
		graphics.setColor(Color.YELLOW);
		graphics.fillRect(0, 0, width, height);

		// 4、绘制图片边框
		graphics.setColor(Color.GRAY);
		graphics.drawRect(0, 0, width - 1, height - 1);

		// 5、输出验证码内容
		graphics.setColor(Color.RED);
		graphics.setFont(new Font("宋体", Font.BOLD, 22));
		
		// 随机输出4个字符
		String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
		Random random = new Random();
		
		// session中要用到
		String msg = "";
		
		int x = 5;
		for (int i = 0; i < charNum; i++) {
			int index = random.nextInt(32);
			String content = String.valueOf(s.charAt(index));
			
			msg += content;
			graphics.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
			graphics.drawString(content, x, 22);
			x += 20;
		}
		
		request.getSession().setAttribute("sessionYzm", msg);

		// 6、绘制干扰线
		graphics.setColor(Color.GRAY);
		for (int i = 0; i < 5; i++) {
			int x1 = random.nextInt(width);
			int x2 = random.nextInt(width);

			int y1 = random.nextInt(height);
			int y2 = random.nextInt(height);
			graphics.drawLine(x1, y1, x2, y2);
		}

		// 释放资源
		graphics.dispose();

		// 图片输出 ImageIO
		ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}

用户登录的servlet

package servlet;

import java.io.IOException;
import java.sql.SQLException;

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 bean.User;
import serice.LoginSerice;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("content-type", "text/html;charset=utf-8");
		//获取请求的用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		//获取前台录入的验证码
		String yzm = request.getParameter("yzm");
		//从session中获取图片中的验证码
		String sessionYzm=(String)request.getSession().getAttribute("sessionYzm");
		//清空session   保证点击登录的时候  验证码是最新的
		request.getSession().removeAttribute("sessionYzm");
		//创建LoginService
		LoginSerice ls = new LoginSerice();
		try {
			//校验验证码
			if(yzm==""||yzm.trim().length()==0){
				//把错误信息放入request域中
				request.setAttribute("msg", "请输入验证码");
				//请求转发
				request.getRequestDispatcher("/login.jsp").forward(request, response);
				//如果程序中出现多个请求转发  那么需要在每一个请求转发后面加上return
				return;
			}else{
				//如果两个验证不一样  需要给出提示
				if(!yzm.equalsIgnoreCase(sessionYzm)){
					//把错误信息放入request域中
					request.setAttribute("msg", "请输入正确的验证码");
					//请求转发
					request.getRequestDispatcher("/login.jsp").forward(request, response);
					return;
				}
			}
			//调用service中的方法
			User user=ls.getUserByUsernameAndPwd(username,password);
			//根据返回的对象,判断提示信息的内容
			if(user==null){
				//response.getWriter().println("登录失败");
				//把错误信息放入request域对象中
				request.setAttribute("msg", "登录失败");
				//使用请求转发跳转到login.jsp
				request.getRequestDispatcher("/login.jsp").forward(request, response);
				return;
				//不能使用重定向,因为使用重定向后request失效
				//response.sendRedirect("/day1102/login.jsp");
			}else{
				//获取前台'自动登录'的value值
				String flag = request.getParameter("flag");
				//判断是否勾选'自动登录'
				if("ok".equals(flag)){
					//设置session时间
					HttpSession session = request.getSession();
					Cookie cookie = new Cookie("JSESSIONID", session.getId());
					cookie.setMaxAge(2 * 3600);  // 客户端的JSESSIONID也保存两小时
					response.addCookie(cookie);
					//创建cookie,把当前的用户名和密码放入cookie中(tom-123)
					Cookie cookie1 = new Cookie("usernameAndPwd", user.getUserName()+"-"+user.getUserPwd());
					//设置cookie的存活时间
					cookie1.setMaxAge(3600);
					//把cookie写回浏览器
					response.addCookie(cookie1);
				}
				request.getSession().setAttribute("username", user.getUserName());
				response.getWriter().println(user.getUserName()+":欢迎回来");
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Filter过滤器

package servlet;

import java.io.IOException;
import java.sql.SQLException;

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 bean.User;
import serice.LoginSerice;

public class LoginFilter implements Filter {

	private static final ServletRequest HttpServletRequest = null;
	private static final String String = null;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		//把servletReuqest强转为HttpServletRequest
				HttpServletRequest request = (HttpServletRequest)req;
				HttpServletResponse response = (HttpServletResponse)res;
				//判断session中是否有用户存在
				String username1=(String)request.getSession().getAttribute("username");
				if(username1!=null){
					//放行
					chain.doFilter(request, response);
					return;
				}
				//获取所有的cookie
				Cookie[] cookies = request.getCookies();
				Cookie co = null;
				//判断cookies是否为null
				if(cookies!=null){
					//从cookies中查找与usernameAndPwd相匹配的cookie
					for(Cookie cookie:cookies){
						if("usernameAndPwd".equals(cookie.getName())){
							co=cookie;
						}
					}
				}
				
				//判断是否是第一次登录
				if(co!=null){
					
					//获取cookie中的用户名和密码
					String up = co.getValue();
					String[] sp = up.split("-");
					String username = sp[0];
					String password = sp[1];
					//完成自动登录,调用LoginService
					LoginSerice ls = new LoginSerice();
					try {
						User user = ls.getUserByUsernameAndPwd(username, password);
						System.out.println("查询一次数据库");
						if(user!=null){
							//保证用户在线
							            
 request.getSession().setAttribute("username",user.getUserName());
						}
						//放行
						chain.doFilter(request, response);
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}else{
					chain.doFilter(request, response);
				}
				
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}

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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>LoginDemo2</display-name>
  <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>
  <servlet>
  	<display-name>LoginServlet</display-name>
  	<servlet-name>LoginServlet</servlet-name>
  	<servlet-class>servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>LoginServlet</servlet-name>
  	<url-pattern>/login</url-pattern>
  </servlet-mapping>
 <!--  配置验证码 -->
 	<servlet>
 		<servlet-name>CodeServlet</servlet-name>
 		<servlet-class>servlet.CodeServlet</servlet-class>
 	</servlet>
 	<servlet-mapping>
 		<servlet-name>CodeServlet</servlet-name>
 		<url-pattern>/code</url-pattern>
 	</servlet-mapping>
 	<!-- 配置Filter过滤器 -->
 	<filter>
 		<filter-name>LoginFilter</filter-name>
 		<filter-class>servlet.LoginFilter</filter-class>
 	</filter>
 	<filter-mapping>
 		<filter-name>LoginFilter</filter-name>
 		<url-pattern>/*</url-pattern>
 	</filter-mapping>
</web-app>

登录界面jsp源码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!doctype html>
<html>
<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title>会员登录</title>
		<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
		<script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>
		<script src="js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定义css文件 style.css -->
<link rel="stylesheet" href="css/style.css" type="text/css"/>

<style>
  body{
   margin-top:20px;
   margin:0 auto;
 }
 .carousel-inner .item img{
	 width:100%;
	 height:300px;
 }
 .container .row div{ 
	 /* position:relative;
	 float:left; */
 }
 
font {
    color: #666;
    font-size: 22px;
    font-weight: normal;
    padding-right:17px;
}
 </style>
</head>
<body>
	
	
	
	
			<!--
            	时间:2015-12-30
            	描述:菜单栏
            -->
			<div class="container-fluid">
				<div class="col-md-4">
					<img src="img/logo2.png" />
				</div>
				<div class="col-md-5">
					<img src="img/header.png" />
				</div>
				<div class="col-md-3" style="padding-top:20px">
					<ol class="list-inline">
						<li><a href="login.htm">登录</a></li>
						<li><a href="register.htm">注册</a></li>
						<li><a href="cart.htm">购物车</a></li>
					</ol>
				</div>
			</div>
			<!--
            	时间:2015-12-30
            	描述:导航条
            -->
			<div class="container-fluid">
				<nav class="navbar navbar-inverse">
					<div class="container-fluid">
						<!-- Brand and toggle get grouped for better mobile display -->
						<div class="navbar-header">
							<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
								<span class="sr-only">Toggle navigation</span>
								<span class="icon-bar"></span>
								<span class="icon-bar"></span>
								<span class="icon-bar"></span>
							</button>
							<a class="navbar-brand" href="#">首页</a>
						</div>

						<!-- Collect the nav links, forms, and other content for toggling -->
						<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
							<ul class="nav navbar-nav">
								<li class="active"><a href="#">手机数码<span class="sr-only">(current)</span></a></li>
								<li><a href="#">电脑办公</a></li>
								<li><a href="#">电脑办公</a></li>
								<li><a href="#">电脑办公</a></li>
							</ul>
							<form class="navbar-form navbar-right" role="search">
								<div class="form-group">
									<input type="text" class="form-control" placeholder="Search">
								</div>
								<button type="submit" class="btn btn-default">Submit</button>
							</form>

						</div>
						<!-- /.navbar-collapse -->
					</div>
					<!-- /.container-fluid -->
				</nav>
			</div>

	
	
	
	
	
	
<div class="container"  style="width:100%;height:460px;background:#FF2C4C url('images/loginbg.jpg') no-repeat;">
<div class="row"> 
	<div class="col-md-7">
		<!--<img src="./image/login.jpg" width="500" height="330" alt="会员登录" title="会员登录">-->
	</div>
	
	<div class="col-md-5">
				<div style="width:440px;border:1px solid #E7E7E7;padding:20px 0 20px 30px;border-radius:5px;margin-top:60px;background:#fff;">
				<font>会员登录</font><%=request.getAttribute("msg")==null?"":request.getAttribute("msg") %>

				<div>&nbsp;</div>
<form class="form-horizontal" action="${pageContext.request.contextPath}/login" method="post">
  
 <div class="form-group">
    <label for="username" class="col-sm-2 control-label">用户名</label>
    <div class="col-sm-6">
      <input type="text" class="form-control" name="username" id="username" placeholder="请输入用户名">
    </div>
  </div>
   <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
    <div class="col-sm-6">
      <input type="password" class="form-control" name="password" id="inputPassword3" placeholder="请输入密码">
    </div>
  </div>
   <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">验证码</label>
    <div class="col-sm-3">
      <input type="text" class="form-control" name="yzm" id="inputPassword3" placeholder="请输入验证码">
    </div>
    <div class="col-sm-3">
      <img src="${pageContext.request.contextPath}/code"/>
    </div>
    
  </div>
   <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <div class="checkbox">
        <label>
          <input type="checkbox" name="flag" value="ok"> 自动登录
        </label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <label>
          <input type="checkbox"> 记住用户名
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
    <input type="submit"  width="100" value="登录" name="submit" border="0"
    style="background: url('./images/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
    height:35px;width:100px;color:white;">
    </div>
  </div>
</form>
</div>			
	</div>
</div>
</div>	

	<div style="margin-top:50px;">
			<img src="./image/footer.jpg" width="100%" height="78" alt="我们的优势" title="我们的优势" />
		</div>

		<div style="text-align: center;margin-top: 5px;">
			<ul class="list-inline">
				<li><a>关于我们</a></li>
				<li><a>联系我们</a></li>
				<li><a>招贤纳士</a></li>
				<li><a>法律声明</a></li>
				<li><a>友情链接</a></li>
				<li><a target="_blank">支付方式</a></li>
				<li><a target="_blank">配送方式</a></li>
				<li><a>服务声明</a></li>
				<li><a>广告声明</a></li>
			</ul>
		</div>
		<div style="text-align: center;margin-top: 5px;margin-bottom:20px;">
			Copyright &copy; 2005-2016 传智商城 版权所有
		</div>
</body></html>

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Exception.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值