1. 程式人生 > >Session控制登入登出

Session控制登入登出

package com.session.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@SpringBootApplication
@RestController
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    /**
     * 一個瀏覽器對應一個唯一sessionid,瀏覽器第一次請求都會建立session,關閉瀏覽器,重啟伺服器,服務端控制session都能使session失效
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/login")
    public String login(@RequestParam String username, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(1000*60*60);
        System.out.println(session.getId());

        if (session.getAttribute("user1") == null) {
            //進行登入
            if (username.equals("user1")) {
                session.setAttribute("user1",session.getId());
                return "登入成功!";
            }else{
                return "登入失敗!";
            }
        } else if (session.getAttribute("user1") != null && session.getAttribute("user1").equals(session.getId())) {
            return "免登陸";
        }
        return "異常";
    }
    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(1000*60*60);
        System.out.println(session.getId());

        if (session.getAttribute("user1")!=null && session.getAttribute("user1").equals(session.getId())) {
            session.removeAttribute("user1");
            return "使用者已退出";
        }
        return "使用者已退出";
    }
}