1、首页(login.jsp)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/8/8
Time: 18:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
<form action="checkServlet" method="post">
用户名:<input type="text" name="username" > <br>
密码:<input type="text" name="userpwd" ><br>
<input type="submit" value="登陆">
</form>
</body>
</html>
2、加入session
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;
import javax.servlet.http.HttpSession;
@WebServlet( "/checkServlet")
public class checkServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//编码问题
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//拿到数据
String username = request.getParameter("username");
String userpwd = request.getParameter("userpwd");
//模拟是否登陆成功,实际情况中会牵扯到数据库。假定数据库中就只有一条数据
if(username.equals("海棠")&& userpwd.equals("909911"))
{
//登陆成功创建session,保存用户信息,跳转到欢迎页面
//session不是内置对象,不能使用new
HttpSession session = request.getSession();
session.setAttribute("name", username);
session.setAttribute("pwd",userpwd);
//设置有效时间,单位是秒
session.setMaxInactiveInterval(10);
response.sendRedirect("success.jsp");
}
//登陆失败跳转到登陆页面
else{
response.sendRedirect("login.jsp");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
3、成功页面(success.jsp)
<%@ page import="java.io.PrintWriter" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/8/8
Time: 19:04
To change this template use File | Settings | File Templates.
b站Javaweb第十个视频session共享问题
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陆成功</title>
</head>
<body>
<%
response.setContentType("text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
String name= (String) session.getAttribute("name");
if (name.equals(null))
{
response.sendRedirect("login.jsp");
}
else
{
writer.println("登陆成功:"+name);
}
%>
</body>
</html>