login.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<form action="DemoSession" method="POST">
${message}
<table border="1" cellpadding="2" cellspacing="2">
<tr>
<td>Username:</td>
<td><input type="text" name="username" value="" /> </td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="" /> </td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login" /> </td>
</tr>
</table>
</form>
</body>
</html>
Servlet: DemoSession.java
Java 2016
public class DemoSession extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user.equals("tony") && pass.equals("123")) {
HttpSession session = request.getSession();
session.setAttribute("username", user);
response.sendRedirect("index.jsp");
} else {
request.setAttribute("message", "Acount is invalid!");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
//Xoa session khi logout
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { //To change body of generated methods, choose Tools | Templates.
HttpSession session = request.getSession();
session.removeAttribute("username");
response.sendRedirect("login.jsp");
}
//Xoa session cach 2
//@Override
//protected void doGet(HttpServletRequest request, HttpServletResponse response)
// throws ServletException, IOException {
// request.getSession().invalidate();
// response.sendRedirect(request.getContextPath() + "/admin/login.jsp");
//}
}
index.jsp
Java 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index</title>
</head>
<body>
<h2>Wellcome ${sessionScope.username}</h2>
<a href="DemoSession">Logout</a>
</body>
</html>
web.xml
Java 2016
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>DemoSession</servlet-name>
<servlet-class>controller.DemoSession</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DemoSession</servlet-name>
<url-pattern>/DemoSession</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
0 nhận xét:
Post a Comment