UserDao类
public class UserDao {
public boolean Check(User u)
{
if(u.getUser().equals("admin") && u.getPwd().equals("123"))
{
return true;
}
return false;
}
}
User类
public class User {
private String user;
private String pwd;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User(String user, String pwd) {
super();
this.user = user;
this.pwd = pwd;
}
}
LoginServlet处理
@WebServlet({ "/LoginServlet", "/login" })
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
this.doPost(request, response);
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
String action = request.getParameter("action");
if(action.equals("login"))
{
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
User u = new User(user,pwd);
UserDao dao = new UserDao();
if(dao.Check(u))
{
request.setAttribute("user",u.getUser());
request.getSession().setAttribute("user",u.getUser());
//验证request、session作用域内置对象
response.sendRedirect("main.jsp");
}
else
{
response.sendRedirect("fail.jsp");
}
}
else if(action.equals("logout")){
//清楚session中属性user
request.getSession().removeAttribute("user");
request.getSession().invalidate();
//跳转至登录界面
response.sendRedirect("login.jsp");
}
}
}
main.jsp
<html>
<head>
<meta charset="UTF-8">
<title>系统页面</title>
</head>
<body>
<%
if(session.getAttribute("user")==null)
{
response.sendRedirect("login.jsp");
}
%>
<p>①使用内置对象request,因为重定向所以request作用域原因导致丢失</p>
<h1>欢迎<%=request.getAttribute("user") %>登录</h1>
<p>①使用内置对象session</p>
<h1>欢迎<%=session.getAttribute("user") %>登录</h1>
<br>
<p></p>
<a href="login?action=logout">登出(用的是get方法)
</a>
</body>
</html>
fail.jsp
<html>
<head>
<meta charset="UTF-8">
<title>出错</title>
</head>
<body>
<h1>登录失败,2秒后跳转至登录界面</h1>
<%
response.setHeader("Refresh", "2;url=login.jsp");
%>
</body>
</html>
login登录页面
<html>
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="login?action=login" method="post">
账号:<input type="text" name="user">
<br>
密码:<input type="password" name="pwd">
<br>
<input type="submit" value="登录">
<input type="reset" value="重置">
</form>
</body>
</html>
示例。admin,123.
request丢失