【Spring boot】session与cookie的使用
程序员文章站
2024-03-19 22:41:10
...
总体而言使用方法非常简单,可以直接参考下面的例子。
package cn.smileyan.boot.test.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
@CrossOrigin
public class HelloSessionController {
@RequestMapping("/add")
public String addSession(HttpServletRequest httpServletRequest,
@RequestParam("username")String username) {
HttpSession session = httpServletRequest.getSession();
session.setAttribute("username",username);
session.setMaxInactiveInterval(10000);
return "添加成功";
}
@RequestMapping("/show")
public Object showSession(HttpServletRequest httpServletRequest) {
HttpSession session = httpServletRequest.getSession();
Object object = session.getAttribute("username");
return object;
}
}
测试方法:打开浏览器,访问addSession方法对应的访问路径,然后添加url参数,比如说
localhost/test/add?username=smileyan
然后直接访问这个路径,可以看到“添加成功”这个返回结果。
道理基本相同,cookie的使用也是如此
package cn.smileyan.boot.test.session;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/cookie")
public class HelloCookieController {
@RequestMapping("/add")
public String addCookie(HttpServletRequest request,HttpServletResponse response,
@RequestParam("username")String username) {
Cookie cookie = new Cookie("username", username);
cookie.setPath(request.getContextPath());
cookie.setMaxAge(80000);
response.addCookie(cookie);
return "添加成功";
}
@RequestMapping("/show")
public String showCookie(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if(cookie.getName().equals("username")) {
System.out.println(cookie.getName());
System.out.println(cookie.getValue());
return cookie.getValue().toString();
}
}
return "null";
}
}
补充:
如果setSession和getSession所在的类不同的话,需要修改path为"/"。
推荐阅读
-
【Spring boot】session与cookie的使用
-
@SpringBootApplication的使用 博客分类: Spring Boot
-
MongoDB最简单的入门教程之四:使用Spring Boot操作MongoDB 数据库mongoDBSpringBoot
-
spring boot单元测试类的使用.Loading class `com.mysql.jdbc.Driver'. This is deprecated.
-
MongoDB最简单的入门教程之四:使用Spring Boot操作MongoDB 数据库mongoDBSpringBoot
-
php及codeigniter使用session-cookie的方法(详解)
-
Django中的cookie与session操作实例代码
-
Django中的cookie与session操作实例代码
-
php及codeigniter使用session-cookie的方法(详解)
-
Spring中属性文件properties的读取与使用详解