这篇博客向大家详解如何在jsp页面实现登录功能,登陆的账号密码数据是从数据库中拿到的,匹配则登陆成功。
首先在school数据库下建立user表,字段如下:
然后,创建web项目,搭建环境如下:
然后就开始我们的代码了。
1.首先把BaseDao.java粘贴到com.tao.dao包下,lib下粘贴mysql-connector-java-5.1.19.jar;在entity包下创建User类
因为 src的内容已经在上篇博客写了,详情请点击JSP向数据库插入数据(简单注册功能),直接拿过来用就行,所以再次不在展示了。
登录页面
login.jsp
<%@ page language="java" 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>Insert title here</title>
</head>
<body>
<form action="dologin.jsp" method="post" >
<%
//获得Cookie(数组)
Cookie cs[]=request.getCookies();
String username="";
if(cs!=null){
//遍历数组拿到名为“username”的cookie
for(Cookie c:cs){
if("username".equals(c.getName())){
username=c.getValue(); //拿到cookie的value
}
}
}
%>
用户名:<input name="username" value="<%=username %>"><!-- 填充上次的登录名 -->
密码:<input name="password">
<hr>
<input type="submit" value="提交" >
<input type="reset" >
<% String msg=(String)request.getAttribute("aa");
if(msg!=null){
out.print(msg);
}
%>
</form>
</body>
</html>
登录处理页面
<%@page import="com.tao.entity.User"%>
<%@page import="com.tao.dao.UserDao"%>
<%@ page language="java" 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>Insert title here</title>
</head>
<body>
<% //获取参数
String name=request.getParameter("username");
String pass=request.getParameter("password");
UserDao udao=new UserDao();
User u=udao.dologin(name, pass);
/*
利用Cookie实现保存上次登录名的功能
*/
Cookie c=new Cookie("username",name); //获取name命名为username
c.setMaxAge(60*60);//单位为秒,设置Cookie保留时间为1h
c.setPath("/"); //当前路径下
response.addCookie(c);
String msg="";
if(u!= null){
//response.sendRedirect("success.jsp"); //重定向
/*
登陆成功跳转到success.jsp
*/
msg="登录成功,欢迎"+name;
request.setAttribute("aa", msg); //
request.getRequestDispatcher("/success.jsp").forward(request, response); //转发
}else{
//登录失败还退回到登录页面
msg="账号或密码错误,请重新登录";
//response.sendRedirect("login.jsp");
request.setAttribute("aa", msg);
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
%>
</body>
</html>
登陆成功页面
<%@ page language="java" 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>Insert title here</title>
</head>
<body>
<%
String msg=(String)request.getAttribute("aa");
out.print(msg);
%>
</body>
</html>