5.1 Demo 实现网站自动登录功能

自动登录流程

1.页面login.jsp

<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>USER LOGIN
					
					<!-- 17.如果登录失败在这里显示信息 -->
					<div>
						<span style="color: red">${loginInfo }</span>
					</div>
					
				<!-- 1.找到登录按钮的form表单 然后设置action  -->
				<!-- 2.给用户名 密码 自动登录 输入框设置name标签  自动登录设置value标签 -->
				
					<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" id="username" name="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" id="inputPassword3" name="password"
									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" id="inputPassword3" 
									placeholder="请输入验证码">
							</div>
							<div class="col-sm-3">
								<img src="./image/captcha.jhtml" />
							</div>
						</div>
						<div class="form-group">
							<div class="col-sm-offset-2 col-sm-10">
								<div class="checkbox">
									<label> <input type="checkbox" name="autoLogin" value="autoLogin"> 自动登录
									</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"
									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>

2.LoginServlet

package com.xiaowei.web.servlet;

import java.io.IOException;
import java.net.URLEncoder;
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 com.xiaowei.domain.User;
import com.xiaowei.service.LoginService;

public class LoginServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		解决中文乱码
		request.setCharacterEncoding("UTF-8");
		
		// 15.1 获得session域
		HttpSession session = request.getSession();

		// 3.获取请求参数
		String username = request.getParameter("username");
		System.out.println("servlet  -----"+username);
		String password = request.getParameter("password");

		// 4.将用户名和密码的值传递到service层 通过查询用户名和密码看有没有这个用户user
		// 5.创建User实体
		LoginService service = new LoginService();
		// 11.返回数据看有没有这个User
		User user = null;
		try {
			user = service.login(username, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		// 12.如果为空则没有
		if (user != null) {
			System.out.println("查到了");
			// 13.然后判断用户是否勾选了自动登录
			// 获取自动登录的请求参数
			String autoLogin = request.getParameter("autoLogin");
			if (autoLogin != null) {
				
//				26.因为cookie不支持中文 将获取到的中文进行编码 然后在cookie中存储 转码操作
				String usernameCode = URLEncoder.encode(username, "UTF-8");
				
				// 14.用户勾选了
				// 用户勾选自动登录之后 将用户名和密码分别存储到cookie当中
				Cookie usernameCookie = new Cookie("username", usernameCode);
				Cookie passwordCookie = new Cookie("password", password);

				// 设置cookie的最大持久化时间 单位是秒
				usernameCookie.setMaxAge(60 * 60);
				passwordCookie.setMaxAge(60 * 60);

				// 设置cookie的携带路径
				usernameCookie.setPath(request.getContextPath());
				passwordCookie.setPath(request.getContextPath());

				// 发送cookie
				response.addCookie(usernameCookie);
				response.addCookie(passwordCookie);
			}

			// 15.将User存储到session中
			session.setAttribute("user", user);
			// 重定向到首页
			response.sendRedirect(request.getContextPath());

		} else {
			System.out.println("没有查到");
			// 16.登录失败将错误信息存储到request域中 然后转发到登录页面
			request.setAttribute("loginInfo", "用户名或则密码错误");
			request.getRequestDispatcher("/login.jsp").forward(request,
					response);
		}
	}

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

3.service层

package com.xiaowei.service;

import java.sql.SQLException;
import com.xiaowei.dao.LoginDao;
import com.xiaowei.domain.User;
public class LoginService {

//	6.通过用户名和密码进行查询操作
	public User login(String username, String password) throws SQLException {
//		7.将用户名和密码传递到dao层
		LoginDao dao = new LoginDao();
		return dao.login(username,password);
	}
}

4.dao层

package com.xiaowei.dao;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.xiaowei.domain.User;
import com.xiaowei.utils.DataSourceUtils;

public class LoginDao {
//	8.通过用户名和密码进行查询操作
	public User login(String username, String password) throws SQLException {
		System.out.println("dao"+ username + password);
//		9.导入连接mysql DBUtils c3p0 的包 连接数据库缓存池的工具类 和c3p0的配置文件
//		10.在数据库中创建数据表User 将c3p0的配置文件 中的数据库写成这个数据库
		QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
		String sql = "select * from user where username=? and password=?";
		return runner.query(sql, new BeanHandler<User>(User.class), username,password);
	}
}

5.user实体

package com.xiaowei.domain;

public class User {

	private int id;
	private String username;
	private String password;
	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 getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

6.AutoLoginFilter

package com.xiaowei.web.filter;

import java.io.IOException;
import java.net.URLDecoder;
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 javax.servlet.http.HttpSession;
import com.xiaowei.domain.User;
import com.xiaowei.service.LoginService;

//25.在web.xml文件中配置

//19.创建自动登录类实现filter接口
public class AutoLoginFilter implements Filter {

	// 20.重写接口中的方法
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
//		21.类型转换
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		
		HttpSession session = req.getSession();
		String username = null;
		String password = null;
		
//		22.从请求中获取cookie 进行判断
		Cookie[] cookies = req.getCookies();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("username")) {
//					27.将cookie中存储的字符转成中文 解码操作
					String usernameCode = cookie.getValue();
					username = URLDecoder.decode(usernameCode, "UTF-8");
				}
				if (cookie.getName().equals("password")) {
					password = cookie.getValue();
				}
			}
		}
		
//		23.如果用户名和密码有值 进行登录操作
		if (username != null && password != null) {
			LoginService service = new LoginService();
			User user = null;
			try {
				user = service.login(username, password);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			session.setAttribute("user", user);
		}
		
//		24.放行
		chain.doFilter(req, resp);
	}

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void destroy() {

	}

}

猜你喜欢

转载自blog.csdn.net/qq_43629005/article/details/84679242
5.1