Spring Boot session与cookie的使用
2024-09-12 08:19:50
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;
}
}
Cookie
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";
}
}
最新文章
- Linux基础练习题(二)
- apache 虚拟机配置
- EF(Linq)框架使用过程中的小技巧汇总
- MySQL与Oracle 差异比较之六触发器
- httpsClient
- HelloWorld和数据绑定
- WebPack实例与前端性能优化
- nodejs-5.2 axios请求
- 游记-WC2019
- java.lang.NoClassDefFoundError: com/sun/image/codec/jpeg/JPEGCodec
- PHP提交订单,信息的传递
- VS2017做为Unity3D的脚本编辑器需要的最精简组件
- Spring Boot基础:Spring Boot简介与快速搭建(1)
- OO课程中IDEA相关插件的使用
- 在“开始”菜单中的“运行”一栏输入特定命令打开windows程序
- SQL命令导入导出
- python的简介(一)
- Android中的httpclient框架发送get请求
- 在linux中添加环境变量
- 侵入式单链表的简单实现(cont)
热门文章
- PowerBuilder编程新思维4:钩挂(界面美化与DirectUI)
- [leetcode]238. 除自身以外数组的乘积
- 计算文章作品发布时间的php代码
- 并发编程之 CountDown 源码分析
- MVC实现更新数据库的数据
- 如何一键式搭建微信小程序
- PetaPoco源代码学习--1.使用的Attribute介绍
- JSON跨域解决方案收集
- JavaScript的三种对话框是通过调用window对象的三个方法alert(),confirm()和prompt()
- H5音乐播放器源码共享