通过Session实现用户登录功能
当客户输入正确的密码是可以一直重复访问内容;否则一直输入密码直到正确为止
package com.mab.servlet;
import com.mab.pojo.User;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet(urlPatterns = "/loginServlet.do")
public class LoginServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//第一步,获取数据从html中这里的username和password必须和html的表单一致
String username = req.getParameter("username");
String password = req.getParameter("password");
//已经写好了值,索取前端用户输入的值进行比较
if ("msb".equals(username)&& "1234".equals(password)){
//如果相同输入正确
//这里给对象传入值
User user = new User("msb", "1234");
//获取httpSession内容
HttpSession session = req.getSession();
//
session.setAttribute("user",user);
//重定向将页面跳转到mainServlet内容页;意味着登录成功
resp.sendRedirect(req.getContextPath()+"/mainServlet.do");
}
else {
//不然用户输入有误,他一直输入吧,页面一直重定向到登录页
//req.getContextPath()通过这个req获取项目文件名
resp.sendRedirect(req.getContextPath()+"/login.html");
}
}
}
package com.mab.servlet;
import com.mab.pojo.User;
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 javax.servlet.http.HttpSession;
import java.io.IOException;
//@WebServlet 继承HttpServlet的类定义为Servlet组件;这里请必须加上” / “+类名+(.do可以省略)
@WebServlet(urlPatterns="/mainServlet.do")
//第一步继承HttpServlet父类
public class MainServlet extends HttpServlet {
//第二步重写service
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//第三步req获取;HTTPSession
HttpSession session = req.getSession();
//第四步,获取的HTTPSession的对象是session,用这个对象调用HTTPSession中获取数据
User user = (User) session.getAttribute("user");
//第五步,判断是否可以获取到数据,第一次访问是获取不到没有JsessionID数据的
if (user!=null){
//这里的条件是第二次访问
//获取 获得一个请求转发器getRequestDispatcher; // 由请求转发器forward作出转发动作这里需要传入req,resp
req.getRequestDispatcher("/WEB-INF/main.html").forward(req,resp);
}else {
//另一种情况查询到一次没有登录,然后重定向到设计的登录页面
resp.sendRedirect("login.html");
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="get" action="loginServlet.do">
账号:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
This is a main
</body>
</html>