JAVA achieve a simple Session login, logout function

session often used to store the user's login information. Then the server is how to achieve it? Here, I simply simulate it.

  • The first step, writing a login page:
<!DOCTYPE html>
<html>
  <head>
    <title>登陆页面</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
    <form action="/JavaWeb/LoginServlet" method="post">
        用户名:<input type="text" name="userName"/>
        <br/>
        密码: <input type="text" name="userPwd"/>
        <br/>
        <input type="submit" value="登陆"/>
    </form>
  </body>
</html>
  • Next, create LoginServlet class, because in order to get the server resource information, so here doGet method used to process the request. The actual process is certainly need to query the user information in the database, where simplified, aimed at understanding the Session usage can be.

 

package gz.itcast;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        //接收参数
        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");

        //判断登陆是否成功
        if(userName.equals("刘小斌") && userPwd.equals("123456")) {
            //登陆成功

            //创建session对象
            HttpSession session = request.getSession();
            //把用户数据保存在session域对象中
            session.setAttribute("loginName", userName);
            //跳转到用户主页
            response.sendRedirect(request.getContextPath()+"/IndexServlet");
        } else {
            //登陆失败,请求重定向
            response.sendRedirect(request.getContextPath() + "/fail.html");
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}
  • Request IndexServlet class successfully created:
package gz.itcast;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class IndexServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        String html = "";

        //得到session对象
        HttpSession session = request.getSession(false);
        if(session==null){
            //没有登录成功,跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        //取出会话数据
        String loginName = (String)session.getAttribute("loginName");
        if(loginName==null){
            //没有登录成功,跳转到登录页面
            response.sendRedirect(request.getContextPath()+"/login.html");
            return;
        }

        html = "<html><body>欢迎回来," +loginName+ "</a></body></html>";


        writer.write(html);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
  • Failure page created for the request fails:
<!DOCTYPE html>
<html>
  <head>
    <title>信息提示页面</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->

  </head>

  <body>
        <font color = red size = 3>用户名或密码输入错误!请重新输入。</font>
        </br></br>
        <a href="/JavaWeb/login.html">返回登陆页面,重新输入。</a>
  </body>
</html>

Project hierarchy: 
Write pictures described here

Well, here to open the tomcat server, look at the results:

  • Enter the URL of the login screen: 
    Write pictures described here

  • Enter the login name or password error: 
    Write pictures described here

  • Jump to the error page: 
    Write pictures described here

  • Enter the correct user name and password: 
    Write pictures described here

  • Jump to User Homepage: 
    Write pictures described here

Note, then refresh the user's home page or some other operation, the user information is still there. Unless session disappear, session domain objects will disappear.

Some problems arise during operation: session class name wrong, found directly after the modification is not enough, must go to the web.xml configuration, or 404 error. Of course, if the redirect process the url wrong, it will be 500 error.

 

Note: To prevent the loss of the original special Reprinted from https://blog.csdn.net/liu_wenbin/article/details/59531184

 

 

 

 

Below is a write-off Log:

public class LogoutServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        request.getSession().removeAttribute("user");
        out.write("注销成功");
        response.setHeader("Refresh", "2;URL="+request.getContextPath());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

 

Published 66 original articles · won praise 8 · views 130 000 +

Guess you like

Origin blog.csdn.net/qq_37889636/article/details/82732079