一、什么是session:
1、session在网络应用中称为“会话控制”,是服务器为了保存用户状态而创建的一个特殊的对象。简单来说,session就是一个对象,用于存储信息。
2、session的作用:
我们先来想一个问题,这个问题就是我们在游览购物网站时,我们并没有登录,但是我们任然可以将商品加入购物车,并且进行查看,当我们退出游览器后再打开游览器进行查看时,购物车中依然有我们选择的商品,这该怎么实现呢?
当然,我们可以使用cookie,但是cookie能存放大量数据吗?这时,我们就需要一种新的技术,Session。session是存储于服务器端的特殊对象,服务器会为每一个游览器(客户端)创建一个唯一的session。这个session是服务器端共享,每个游览器(客户端)独享的。我们可以在session存储数据,实现数据共享。
二、登录和注销流程
用户在请求登录之后判断是否合法,如果合法说明登录成功,并且将其加入到session集合中;用户登录之后想要注销则可以将信息从Session中删除。
1、登录界面
利用jsp文件写一个登录界面login2.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
<%
HashMap<String, String> error = ((HashMap<String, String>)request. getAttribute("error"));
String fail = (String) request.getParameter("fail");
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if (cookies!=null && cookies.length>0){
for (Cookie cookie : cookies) {
String name = cookie.getName();
if ("username".equals(name)){
username = cookie.getValue();
}
if ("password".equals(name)){
password = cookie.getValue();
}
}
}
%>
<form action="UserController" method="post">
<input type="hidden" value="login" name="userAction">
<table border="1" align="center" >
<tr align="center"><th colspan="2">登录</th></tr>
<tr><td>账号:<input type="text" name="username" value="<%=username%>"><%=fail==null?"":fail%><span style="color:red"> <%=error==null?"":error.get("username")==null?"":error.get("username")%></span></td></tr>
<tr><td>密码:<input type="text" name="password" value="<%=password%>"><span style="color:red"> <%=error==null?"":error.get("password")==null?"":error.get("password")%></span></td></tr>
<tr><td><input type="checkbox" name="autoLogin" value="1">一周内自动登录</td></tr>
<tr align="center"><td colspan="2"><input type="submit" value="登录"><input type="reset" value="重置"></td></tr>
</table>
</form>
</body>
</html>
2、controller层:
@WebServlet("/UserController")
public class UserController extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String userAction = req.getParameter("userAction");
String logout = req.getParameter("logout");
//处理中文乱码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
/**
* 注销
*/
if ("loginout".equals(userAction)){
HttpSession session = req.getSession();
session.removeAttribute("username");
req.getRequestDispatcher("/WEB-INF/pages/loginoutsuccess.jsp").forward(req,resp);
}
/**
* 查询用户信息
*/
if ("showAllUser".equals(userAction)){
String username = (String)req.getSession().getAttribute("username");
if (username!=null){
List<User> users = new UserService().showAllUser();
if (users.isEmpty()){
req.setAttribute("infor","未查询到用户相关信息");
req.getRequestDispatcher("/WEB-INF/pages/showalluser.jsp").forward(req,resp);
}else {
req.setAttribute("users",users);
req.getRequestDispatcher("/WEB-INF/pages/showalluser.jsp").forward(req,resp);
}
}else {
resp.sendRedirect("/web002/loinfail.jsp");
}
}
/**
* 登录
*/
if ("login".equals(userAction)){
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
Map<String,String> error = ValidateDome.validateUser(user);
if (error.isEmpty()){
UserService userService = new UserService();
boolean flag = userService.login(user.getUsername(),user.getPassword());
if (flag){
//判断是否需要记录用户名和密码
String[] autoLogins = req.getParameterValues("autoLogin");
if (autoLogins!=null && autoLogins.length>0){
//登录成功后记录cookie
Cookie usercookie = new Cookie("username", user.getUsername());
Cookie psdcookie = new Cookie("password", user.getPassword());
usercookie.setMaxAge(60);
psdcookie.setMaxAge(60);
usercookie.setPath("FirstWeb");
psdcookie.setPath("FirstWeb");
resp.addCookie(usercookie);
resp.addCookie(psdcookie);
//设置一个登录成功标注
//这个标志设置在session中比较合适
req.getSession().setAttribute("username",user.getUsername());
//resp.sendRedirect("index01.jsp?username="+ URLEncoder. encode(user.getUsername(),"utf-8"));
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}else {
req.getSession().setAttribute("username",user.getUsername());
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}
}else {
req.setAttribute("fail","登录失败");
req.getRequestDispatcher("login2.jsp").forward(req,resp);
}
}else {
req. setAttribute( "error", error);
req.getRequestDispatcher( "login2.jsp").forward(req,resp);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* 注册
*/
if ("register".equals(userAction)){
User user = new User();
try {
BeanUtils.populate(user,req.getParameterMap());
user.setHobbies(ArrayToString.arrayToString(req.getParameterValues("hobbies")));
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
Map<String,String> error = new HashMap<>();
if (error.isEmpty()){
//调用service
UserService userService = new UserService();
int state = userService.register(user);
if (state==0){
resp.sendRedirect("registerfail.jsp");
}
if (state==1){
resp.sendRedirect("refresh.jsp");
}
if (state==2){
resp.sendRedirect("register.jsp?registerfail="+ URLEncoder. encode( "该用户已经存在!", "utf-8"));
}
}else {
req. setAttribute( "error", error);
req.getRequestDispatcher( "/register.jsp").forward(req, resp);
}
}
}
}
判断是否登录
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/ServletDome1")
public class ServletDome1 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//判断是否登录
String username = (String)req.getSession().getAttribute("username");
if (username!=null){
req.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(req,resp);
}else {
resp.sendRedirect("/web002/login2.jsp");
}
}
}
web里面建一个index.jsp
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%request.getRequestDispatcher("/WEB-INF/pages/index.jsp").forward(request,response);%>
</body>
</html>
3、user层
/**
* 封装User对象
*/
public class User {
private Integer id;
private String username;
private String password;
private String gender;
private String hobbies;
private String address;
private String remark;
private int age;
private Date birthday;
private String phone;
private String mailbox;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMailbox() {
return mailbox;
}
public void setMailbox(String mailbox) {
this.mailbox = mailbox;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
}
public String getGender() {
return gender;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday( Date birthday) {
this.birthday = birthday;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getHobby() {
return hobbies;
}
public void setHobby(String hobbies) {
this.hobbies = hobbies;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", hobbies='" + hobbies + '\'' +
", address='" + address + '\'' +
", remark='" + remark + '\'' +
", age=" + age +
", birthday=" + birthday +
", phone='" + phone + '\'' +
", mailbox='" + mailbox + '\'' +
'}';
}
}
4、不被外部访问
在WEB-INF里面建一个pages文件夹不被外部访问
index.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
用户信息:<br/>
<%=request.getAttribute("infor")==null?"":request.getAttribute("infor")%>
<table border="1" align="center" width="80%">
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>爱好</th>
<th>备注</th>
<th>性别</th>
<th>操作</th>
</tr>
<%
List<User> users = (List<User>) request.getAttribute("users");
for (User user : users) {
%>
<tr>
<td align="center"><%=user.getId()%></td>
<td align="center"><%=user.getUsername()%></td>
<td align="center"><%=user.getPassword()%></td>
<td align="center"><%=user.getAge()%></td>
<td align="center"><%=user.getHobbies()%></td>
<td align="center"><%=user.getRemark()%></td>
<td align="center"><%=user.getGender()%></td>
<td align="center"><a href="UserController?userAction=showUserBack&id=<%=user.getId()%>">修改</a> <a href="UserController?userAction=deleteUser&id=<%=user.getId()%>">删除</a> </td>
</tr>
<%
}
%>
</table>
</body>
</html>
loginoutsuccess.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
注销成功,<span style="color: red" id="span1">3</span>秒后将跳转至登录界面,如果没有跳转请点击<a href="login2.jsp">登录</a>
<script LANGUAGE="JavaScript">
function fun() {
var span1 = document.getElementById("span1");
var i = span1.innerHTML;
if (i>0){
i=i-1;
span1.innerHTML = i;
}
}
window.setInterval("fun()",1000);
</script>
<%
response.setHeader("refresh","3;url=login2.jsp");
%>
</body>
</html>
showalluser.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
用户信息:<br/>
<%=request.getAttribute("infor")==null?"":request.getAttribute("infor")%>
<table border="1" align="center" width="80%">
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>年龄</th>
<th>爱好</th>
<th>备注</th>
<th>性别</th>
<th>操作</th>
</tr>
<%
List<User> users = (List<User>) request.getAttribute("users");
for (User user : users) {
%>
<tr>
<td align="center"><%=user.getId()%></td>
<td align="center"><%=user.getUsername()%></td>
<td align="center"><%=user.getPassword()%></td>
<td align="center"><%=user.getAge()%></td>
<td align="center"><%=user.getHobbies()%></td>
<td align="center"><%=user.getRemark()%></td>
<td align="center"><%=user.getGender()%></td>
<td align="center"><a href="UserController?userAction=showUserBack&id=<%=user.getId()%>">修改</a> <a href="UserController?userAction=deleteUser&id=<%=user.getId()%>">删除</a> </td>
</tr>
<%
}
%>
</table>
</body>
</html>
5、注册
web了里面建一个register.jsp用来注册用户
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
String registerfail = request.getParameter("registerfail");
--%>
<%
HashMap<String, String> error = ((HashMap<String, String>)request. getAttribute("error"));
String registerfail = request.getParameter("registerfail");
%>
<%=registerfail==null?"":registerfail%>
<form name="form1" method="post" action="UserController" onsubmit="return fun1()">
<input type="hidden" value="register" name="userAction">
<table width="30%" heighe="300px"border="1" id="table1">
<tr align="center"><td colspan="2">注册</td></tr>
<tr><td>用户名</td><td><input type="text" id="username" name="username"/><span style="color:red"> <%=error==null?"":error.get("username")==null?"":error.get("username")%></span></td></tr>
<tr><td>密码</td><td><input type="password" id="password" name="password" /><span style="color:red"> <%=error==null?"":error.get("password")==null?"":error.get("password")%></span></td></tr>
<tr><td>年龄</td><td><input type="text" id="age" name="age" /></td></tr>
<tr><td>性别</td>
<td>
<input type="radio" value="female" name="gender">女
<input type="radio" value="male" name="gender">男
</td></tr>
<tr>
<td>爱好</td>
<td>
<input type="checkbox"value="篮球" name="hobbies" >篮球
<input type="checkbox"value="足球" name="hobbies" >足球
<input type="checkbox"value="羽毛球" name="hobbies" >羽毛球
</td>
</tr>
<tr>
<td>地址</td>
<td>
<select name="address">
<option value="成都">成都</option>
<option value="贵州">贵州</option>
</select>
</td>
</tr>
<tr><td>备注</td>
<td>
<input id="comments" name="remark" rows="4" cols="50">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交" id="sub">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
var i = 1;
function fun1() {
var sub = document.getElementById("sub");
if (i>1){
sub.disabled = "disabled";
alert("请不要重复提交")
return false;
}
i++;
}
</script>
</body>
</html>