Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to achieve persistent login status acquisition by SpringBoot

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to achieve persistent login status acquisition by SpringBoot". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to achieve persistent login status acquisition by SpringBoot".

SpringBoot persistent login status to get 1. Write the controller file for login

Write to cookie

/ / after successful login / /. Store the user account information in the database / / write cookie, (because it is stored in the database, there is no need to write session) response.addCookie (new Cookie ("token", token)); 2. Write the home Controller logic @ Controllerpublic class IndexController {@ Autowired private UserMapper userMapper; @ GetMapping ("/") public String index (HttpServletRequest request) {Cookie [] cookies = request.getCookies (); if (cookies! = null) {for (Cookie cookie: cookies) {if (cookie.getName (). Equals ("token")) {String token = cookie.getValue () System.out.println ("ready to enter the database"); User user = userMapper.findByToken (token); / / go to the database to find the user information of the token value System.out.println (user.toString ()) If (user! = null) {/ / if you find this user information / / write it into session, let the page display request.getSession () .setAttribute ("user", user);} break } return "index";}} 3. Run the test, successfully log in and log out with SpringBoot, and manage the login state.

Login and logout of the necessary functions in the account module. I believe this is often used by everyone. A brief introduction to the implementation in SpringBoot

First of all, let's talk about the implementation ideas:

The user name and password are stored in the database, the front end sends a request, and the interceptor first detects whether the user is logged in or not, and if there is a login, you can directly request the interface. Interfaces that can be requested without logging in need to be annotated with @ NoLogin customization. If not, the front end jumps to the login page, calls the login interface, and the system verifies the user name and password in the background by storing the user information in redis and in the thread context.

1. Design table structure

In addition to the necessary user name and password, other account information fields can be added according to your own system needs.

CREATE TABLE `t_ Secrett` (`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT 'key', `name` varchar (64) NOT NULL DEFAULT''COMMENT' name', `mobile` varchar (32) NOT NULL COMMENT 'mobile number', `identity`varchar (32) NOT NULL COMMENT'ID number', `user_ name` varchar (32) NOT NULL COMMENT 'account', `password` varchar (64) NOT NULL DEFAULT''COMMENT' login password', `accept_ region`bigint (20) NOT NULL COMMENT 'acceptance center (network) number' `status` int (11) NOT NULL DEFAULT'1' COMMENT 'status: 0 disabled, 1 normal, 9 deleted', `status` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'creation time', `update_ by` bigint (20) DEFAULT NULL COMMENT 'creator Id', `update_ time`timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT' modification time, `update_ by` bigint (20) DEFAULT NULL COMMENT 'modifier Id' PRIMARY KEY (`id`) account table of ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='C network personnel' 2.controller layer

Receive parameters from the client, call the API to match the database information, and return user information if the match is successful. And it is stored in redis, and the current reply sessionid is key, and the user information is value.

@ RestController@RequestMapping (value = WebConstants.WEB_PREFIX + "/ account") @ Api (tags = "Account", description = "account module") @ NoAuthpublic class AccountController {@ Autowired private AccountService accountService; @ Autowired private StringRedisTemplate redisTemplate @ PostMapping (value = "/ login") @ ApiOperation ("login") public ResponseVologin (@ RequestBody LoginForm form, HttpServletRequest request, HttpServletResponse response) {HttpSession session=request.getSession (); AccountDto accountDto=accountService.login (form.getUserName (), form.getPassword ()); if (null==accountDto) {throw new BizException ("wrong username or password!") ;} redisTemplate.opsForValue () .set (session.getId (), JSON.toJSONString (accountDto)); AccountVo accountVo= BeanCopy.of (accountDto,new AccountVo ()) .copy (BeanUtils::copyProperties) .get (); accountVo.setAceptRegion (AcceptRegionEnum.getDescByValue (accountDto.getAceptRegion (); return ResponseVo.successResponse (accountVo) } @ Login @ PostMapping (value = "/ logout") @ ApiOperation ("logout") public ResponseVo logout (HttpServletRequest request,HttpServletResponse response) {HttpSession session=request.getSession (); session.invalidate (); redisTemplate.delete (session.getId ()); return ResponseVo.successResponse ();}} 3. Create a request interceptor

Create a request interceptor to detect the user's login status. Check whether there is user information in redis by session_id. If it exists, the user information is stored in the current thread context (the user thread context is essentially a HashMap-based cache) for later use. This step can also be placed after a successful login (which is also more rigorous).

@ Componentpublic class LoginInterceptor implements HandlerInterceptor {private Logger logger= LoggerFactory.getLogger (LoginInterceptor.class); @ Autowired private StringRedisTemplate redisTemplate; @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {HandlerMethod handlerMethod = (HandlerMethod) handler; Class clazz = handlerMethod.getBeanType (); Method m = handlerMethod.getMethod () / / if (clazz.isAnnotationPresent (NoLogin.class) | | m.isAnnotationPresent (NoLogin.class)) {return true;} HttpSession session=request.getSession () that can be accessed by login; / / check whether sessionId String val=redisTemplate.opsForValue () .get (session.getId ()) is included in the redis. If {logger.info (val); AccountDto accountDto= JSON.parseObject (val,AccountDto.class); AcceptRegionUserVistor vistor=new AcceptRegionUserVistor (); BeanUtils.copyProperties (accountDto,vistor); AcceptRegionUserThreadContext.putSessionVisitor (vistor); return true;} else {response.setStatus (401) Throw new BizException ("common.system.user.not.login");} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}

Register interceptor: (only the registered interceptor will take effect)

@ Configurationpublic class WebConfiguration extends WebMvcConfigurationSupport {@ Autowired private LoginInterceptor loginInterceptor; / * interceptor configuration * * @ param registry registration class * / @ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (loginInterceptor) .addPathPatterns (WebConstants.WEB_PREFIX + "/ *"); super.addInterceptors (registry);}} 4. Log out

Get the current session, clear the reply information, and delete the user information of the corresponding sessionid in the redis. For the code, see the logout method in the second paragraph above.

At this point, I believe you have a deeper understanding of "how to achieve persistent login status acquisition by SpringBoot". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report