精华内容
下载资源
问答
  • springboot登陆实现

    千次阅读 2018-12-18 18:34:06
    springboot登陆实现 相关知识 一、 session简介 服务器可以为每个用户浏览器创建一个会话对象(session对象),一个浏览器只能产生一个session,当新建一个窗口访问服务器时,还是原来的那个session。session中默认...

    springboot登陆实现

    相关知识

    一、 session简介

    服务器可以为每个用户浏览器创建一个会话对象(session对象),一个浏览器只能产生一个session,当新建一个窗口访问服务器时,还是原来的那个session。session中默认保存的是当前用户的信息。因此,在需要保存其他用户数据时,我们可以自己给session添加属性。session(会话)可以看为是一种标识,通过带session的请求,可以让服务器知道是谁在请求数据。

    二、 session相关

    1. session的创建

      @GetMapping"demo"public void demo(HttpServletRequest request){
      HttpSession sessoin=request.getSession();//这就是session的创建
      session.setAttribute("username","root");//给session添加属性属性name: username,属性 value:root
      session.setAttribute("password","123456");//添加属性 name: password; value: 123456
      System.out.println(session.getId());
      }
      
      

      其中HttpSession session=request.getSession(true); true表示如果这个HTTP请求中,有session,那么可以直接通过getSession获取当前的session,如果当前的请求中没有session,则会自动新建一个session

      HttpSession session=request.getSession(false);
      //false表示只能获取当前请求中的session,如果没有也不能自动创建。
      
    2. session的 获取属性

      session.getAttribute("username");
      session.getAttribute("password");
      
    3. session,cookies的超时设置

      1. 在.yml里面或.xml配置文件里面设置

      2. 在创建session时

        session.setMaxInactiveInterval(30*60);
        //以秒为单位,即在没有活动30分钟后,session将失效
        

    三、获取Request和Response的方法

    • 通过参数直接获取,只要在你的方法上加上参数,Springboot就会帮你绑定,你可以直接使用。如果你的方法有其他参数,把这两个加到后面即可。
        @GetMapping(value = "")
        public String center(HttpServletRequest request,HttpServletResponse response) {
            //...
        }
      
    • 注入到类,这样就不用每个方法都写了
        @Autowired
        private HttpServletRequest request;
        @Autowired
        private HttpServletResponse response;
        @GetMapping(value = "")
        public String center() {
            //...
        }
      

    实现登陆跳转的两种方法

    1. form表单提交,后台验证并跳转。
    2. js提交,后台验证后交予js跳转。

    后台跳转方式

    提交表单

    <div class="htmleaf-container">
    	<div class="wrapper">
    		<div class="container">
    				<h1 th:text="${msg}" style="text-align: center">Welcome</h1>
    
    	<form id="loginform" class="form" th:action="@{/test}"
    					method="post"  style="text-align: center"><br> 
            <label>用户:</label> <input type="text" name="username"  placeholder="Username"><br> <br> 
            <label>密码:</label><input type="password" name="password" placeholder="Password"><br><br>
    		<div class="form-actions">
    		<span class="pull-right"><a type="submit"
    				href="javascript:$('#loginform').submit();"
    				class="btn btn-success">登陆</a></span>
    		</div>
    	</form>
    		</div>
    	</div>
    </div>
    <script type="text/javascript" th:src="@{/js/jquery-1.11.2.min.js}"></script>
    

    后台处理

    	@Autowired
    	CategoryMapper categoryMapper;	
    	@RequestMapping("/")
    	public String index(HttpServletRequest request, ModelMap map) {
    		HttpSession sessoin = request.getSession();
    		if (sessoin.getAttribute("username") != null) {
    			map.addAttribute("host", "Hello");
    			map.addAttribute("user", "User: " + sessoin.getAttribute("username"));
    			map.addAttribute("name", "Name: " + sessoin.getAttribute("name"));
    			map.addAttribute("age", "Age: " + sessoin.getAttribute("age"));
    			return "index";
    		} else {
    			//若未登陆则直接跳转至登陆界面
    			return "redirect:/login";
    		}
    	}
    
    	@RequestMapping(value = "/login", method = RequestMethod.GET)
    	public String login() {
    		return "login";
    	}
    	
    	@RequestMapping(value = "/login", method = RequestMethod.POST)
    	public String login(HttpServletRequest request) {
    		HttpSession sessoin = request.getSession();
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		boolean check;
    		Category test = categoryMapper.findByUsername(username);
    		if (test != null) {
    			if (test.getPassword().equals(password))
    				check = true;
    			else
    				check = false;
    		} else {
    			request.setAttribute("msg", "用户不存在!");
    			return "redirect:/login";
    		}
    
    		if (check) {
    			sessoin.setAttribute("username", username);
    			sessoin.setAttribute("password", password);
    			return "redirect:/";
    		} else {
    			request.setAttribute("msg", "密码不正确!");
    			return "redirect:/login";
    		}
    	}
    

    流程图

    Created with Raphaël 2.2.0/GET /(是否登陆?)USER 页面GET /loginLOGIN 页面POST /loginyesnoyesno

    js跳转方式

    前台交互

    <script type="text/javascript">
    		//回车键或者点击提交表单,禁止浏览器默认跳转:
    	$('#loginform').submit(function() {
    			
    		var name = document.getElementById('inputText').value;
    		var pass = document.getElementById('inputPassword').value;
    		var json = {
    			"username" : name,
    			"password" : pass
    		};
    		var url = "/login";
    
    		$.post(url, {
    			"data" : JSON.stringify(json)
    		}, function(data) {
    			//alert(data);
    			if (data === "0") {location.href = "/";
    			} else if (data === "404") {$("#msg").text("用户未找到!");
    			} else if (data === "error") {$("#msg").text("密码错误!");
    			} else {$("#msg").text("未知错误!");
    			}	
    		});
    		return false;
    		});
    </script>
    

    后台处理

    	@ResponseBody
    	@RequestMapping(value = "/login", method = RequestMethod.POST)
    	public String login(HttpServletRequest request, Category user, Model model) {
    		String data = request.getParameter("data");
    		System.out.println("获取提交数据:" + data);
    		YamlJsonParser json = new YamlJsonParser();
    		Map<String, Object> parser = json.parseMap(data);
    		String username = parser.get("username").toString();
    		String password = parser.get("password").toString();
    		System.out.println("转换为JSON对象:" + username + password);
    
    		boolean check;
    		Category test = categoryMapper.findByUsername(username);
    		if (test != null) {	
    			if (test.getPassword().equals(password))
    				check = true;
    			else
    				check = false;
    		} else {
    			System.out.println(username + "用户不存在!");
    			return "404";
    		}
    		if (check) {
    			HttpSession sessoin = request.getSession();
    			sessoin.setAttribute("username", username);
    			sessoin.setAttribute("password", password);
    			sessoin.setAttribute("name", test.getName());
    			sessoin.setAttribute("age", test.getAge());
    			System.out.println("登陆成功,跳转");
    			return "0";
    		} else {
    			System.out.println("密码不正确!" + test.getPassword() + password);
    			return "error";
    		}
    	}
    

    流程图

    Created with Raphaël 2.2.0/GET /(是否登陆?)USER 页面GET /loginLOGIN 页面js functionPOST /loginyesnoyesno

    方法比较

    ​ 使用第一种方法时,当后台程序有异常时会直接使返回页面异常,而使用前台跳转则无此问题。

    展开全文
  • 主要介绍了springboot登陆过滤功能的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • springboot-登陆实现和拦截器:springboot登陆页面进行登陆验证,并完成登陆跳转。错误的账户提示用户名密码错误,正确的账户跳转到dashboard页面。
  • 主要介绍了springboot登陆页面图片验证码简单的web项目实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • SpringBoot实现登陆拦截

    2019-11-11 20:35:34
    一、创建interceptor包,在interceptor中创建一个拦截器并实现HandlerInterceptor @Component public class LoginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle...

    一、创建interceptor包,在interceptor中创建一个拦截器并实现HandlerInterceptor

    @Component
    public class LoginHandlerInterceptor implements HandlerInterceptor {
     
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
     
           //拦截逻辑
            Object user = request.getSession().getAttribute("loginUser");
            if (user == null) {
                System.out.println("没有权限请先登陆");
                //未登陆,返回登陆界面
                request.setAttribute("msg","没有权限请先登陆");
                request.getRequestDispatcher("/login").forward(request,response);
                return false;
            } else {
                //已登陆,放行请求
                return true;
            }
        }
    }
    

    注意:在低版本的SpringBoot中需要实现postHandle方法和afterCompletion方法,高版本的SpringBoot需要用到这两个方法直接重写就行了,在这就不做过多的介绍了。

    二、创建一个SpringMvc配置类并实现WebMvcConfigurer类

    @Configuration
    public class MyWebMvcConfiguration implements WebMvcConfigurer {
     
        @Autowired
        LoginHandlerInterceptor loginHandlerInterceptor;
     
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/").setViewName("forward:/login");
            registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        }
     
        //注册拦截器
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            //拦截所有的请求
            registry.addInterceptor(loginHandlerInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/register").excludePathPatterns("/static/**");
        }
     
    }
    

    注意:在SpringBoot中,只能通过创建SpringMVC配置文件来注册拦截器,.addPathPatterns("/**")表示拦截所有的请求, excludePathPatterns表示路径不需要拦截哪些路径一定要在这里排除拦截static路径下的静态文件,或者在SpringBoot配置文件上配置,否则页面加载不到样式。

    展开全文
  • 基于 springboot2.0 实现的人脸识别登陆demo,调用旷视的接口调用的人脸识别对比。需要自行更改数据库链接和api_key,api_secret
  • SpringBoot写一个登陆注册功能,开发工具使用IDEA,技术使用SpringBoot2.1.3+Mybatis+Jpa+mysql,项目中主要使用Mybatis,jpa只做了demo,实体转换使用的是mapstruct,集成了swagger文档配置,redis缓存demo,代码...
  • 使用oauth2+redis+mysql来完成登陆校验,本案例使用oauth2简单的密码模式来实现。 最终实现的效果为: 登陆页面不设置权限审核,用户通过登陆界面登陆,输入账户密码,后端接收到账户密码之后会去数据库验证,如果...

    实现思路

    使用oauth2+redis+mysql来完成登陆校验,本案例使用oauth2简单的密码模式来实现。
    最终实现的效果为:

    • 登陆页面不设置权限审核,用户通过登陆界面登陆,输入账户密码,后端接收到账户密码之后会去数据库验证,如果验证通过,则返回token给前端。
    • 除了登陆页面之外,其余的页面访问的时候会进行权限的鉴定,如果携带的token对应用户的权限不足或没有携带token、携带了错误的token,不允许访问。
    • token具有时限,超时token会失效,可以通过refresh_token来刷新token的持续时间。

    项目结构

    项目的结构为:

    ├─.idea
    │  └─dictionaries
    ├─log
    ├─src
    │  ├─main
    │  │  ├─java
    │  │  │  └─Rush
    │  │  │      ├─config
    │  │  │      ├─controller
    │  │  │      ├─mapper
    │  │  │      ├─pojo
    │  │  │      ├─service
    │  │  │      └─util
    │  │  └─resource
    │  └─test
    │
    └─target
    

    项目的重点其实也就在于config包内
    config包内定义了4个类

    1. AuthorizationServerConfig
    2. ResourceServerConfig
    3. WebSecurityConfig
    4. CORSFilter「额外针对OAuth跨域问题」

    除此之外,继承了UserDetails接口的User类,继承UserDetailsService类的UserService类也很关键。
    除了这6个类之外,别的类和普通mybatis项目无异

    • AuthorizationServerConfig
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.data.redis.connection.RedisConnectionFactory;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
    import org.springframework.web.bind.annotation.CrossOrigin;
    
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig
            extends AuthorizationServerConfigurerAdapter {
        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        RedisConnectionFactory redisConnectionFactory;
        @Autowired
        UserDetailsService userDetailsService;
        @Bean
        PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
        @Override
        public void configure(ClientDetailsServiceConfigurer clients)
                throws Exception {
            clients.inMemory()
                    .withClient("password")
                    .authorizedGrantTypes("password", "refresh_token")
                    .accessTokenValiditySeconds(1800)
                    .resourceIds("rid")
                    .scopes("all")
                    .secret("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq");
        }
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService);
        }
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security)
                throws Exception {
            security.allowFormAuthenticationForClients();
        }
    }
    
    • ResourceServerConfig
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
    import org.springframework.web.bind.annotation.CrossOrigin;
    
    @Configuration
    @EnableResourceServer
    public class ResourceServerConfig
            extends ResourceServerConfigurerAdapter {
        @Override
        public void configure(ResourceServerSecurityConfigurer resources)
                throws Exception {
            resources.resourceId("rid").stateless(true);
        }
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/admin/**").hasRole("admin")
                    .antMatchers("/user/**").hasAnyRole("user","admin")
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginProcessingUrl("/home").permitAll()
                    .and()
                    .csrf().disable();
        }
    }
    
    • WebSecurityConfig
    import bocRush.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.web.bind.annotation.CrossOrigin;
    
    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        UserService userService;
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
        @Bean
        @Override
        protected UserDetailsService userDetailsService() {
            return super.userDetailsService();
        }
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //        auth.inMemoryAuthentication()
    //                .withUser("admin")
    //                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq")
    //                .roles("admin")
    //                .and()
    //                .withUser("sang")
    //                .password("$2a$10$RMuFXGQ5AtH4wOvkUqyvuecpqUSeoxZYqilXzbz50dceRsga.WYiq")
    //                .roles("user");
            auth.userDetailsService(userService);
        }
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/oauth/**").authorizeRequests()
                    .antMatchers("/oauth/**").permitAll()
                    .and().cors()
                    .and().csrf().disable();
        }
    }
    
    • CORSFilter
    /**
     * Date   : 2021/3/25 17:48
     * Author : nicolas
     */
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.Ordered;
    import org.springframework.core.annotation.Order;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    
    /*全局跨域配置*/
    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Configuration
    public class CORSFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest servletRequest,
                             ServletResponse servletResponse,
                             FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,PATCH,HEAD");
            response.setHeader("Access-Control-Allow-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    
        @Override
        public void destroy() {
    
        }
    }
    
    • User
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    
    public class User implements UserDetails {
        private Integer id;
        private String username;
        private String password;
        private Boolean enabled;
        private Boolean locked;
        private List<Role> roles;
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
            }
            return authorities;
        }
        @Override
        public String getPassword() {
            return password;
        }
        @Override
        public String getUsername() {
            return username;
        }
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
        @Override
        public boolean isAccountNonLocked() {
            return !locked;
        }
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
        @Override
        public boolean isEnabled() {
            return enabled;
        }
        //省略getter/setter
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
    
        public void setEnabled(Boolean enabled) {
            this.enabled = enabled;
        }
    
        public Boolean getLocked() {
            return locked;
        }
    
        public void setLocked(Boolean locked) {
            this.locked = locked;
        }
    
        public List<Role> getRoles() {
            return roles;
        }
    
        public void setRoles(List<Role> roles) {
            this.roles = roles;
        }
    
    }
    
    • UserService
    import bocRush.mapper.UserInfoMapper;
    import bocRush.mapper.UserMapper;
    import bocRush.pojo.User;
    import bocRush.pojo.UserInfo;
    import org.apache.ibatis.annotations.Param;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    
    @Service
    public class UserService implements UserDetailsService {
        @Autowired
        UserMapper userMapper;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            User user = userMapper.loadUserByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("账户不存在!");
            }
            user.setRoles(userMapper.getUserRolesByUid(user.getId()));
            //System.out.println(user.getRoles().get(1).getName() + " --- " + user.getUsername());
            return user;
        }
    }
    

    对于接口的传参数

    获取token

    使用POST方法

    http://localhost:8080/oauth/token?username=sang&password=123&grant_type=password&client_id=password&scope=all&client_secret=123
    

    刷新token

    使用POST方法

    http://localhost:8080/oauth/token?grant_type=refresh_token&refresh_token=1a1c67a0-5f9b-49b1-9f95-dc7889c85cf5&client_id=password&client_secret=123
    

    携带token访问资源

    • 在url内直接携带token
      GET方法
    http://localhost:8080/user/hello?access_token=9bdde947-19b7-46fe-8fe0-0f2804150768
    
    • 在header内携带token
      GET方法
    http://localhost:8080/admin/hello
    ------------Header----------------
    Authorization : bearer 3929d92d-f5be-4b2d-9223-8b13e2412f14
    Accept : application/json
    
    展开全文
  • SpringBoot 登陆拦截

    2018-10-26 16:37:55
    1.登陆拦截器 :创建一个类 实现 HandlerInterceptor 看具体代码 package com.bw.data.portal.conf; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import ...

    1.登陆拦截器 :创建一个类 实现 HandlerInterceptor 看具体代码

    package com.bw.data.portal.conf;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    /**
     * 登陆拦截
     * @author wangmx
     */
    public class LoginHanderInterceptor implements HandlerInterceptor{
    
    	@Override
    	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    			throws Exception {
    		// TODO Auto-generated method stub
            //获取 session中的 用户信息
    		Object user = request.getSession().getAttribute( "fuser" );
    		if (user == null){
                System.out.println( "登陆拦截" );
                //跳转到 登陆的controller  /ful/nologin   是直接返回 到登陆界面的 controller
                request.getRequestDispatcher( "/ful/nologin" ).forward( request,response );
                return false;
            }else {
                return true;
            }
    	}
    
    	@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 {
    		
    	}
    	
    
    }
    

    2.拦截器注册:创建 一个类继承 WebMvcConfigurerAdapter  接着看代码

     package com.bw.data.portal.common.config.mvc;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    import com.bw.data.portal.conf.LoginHanderInterceptor;
    
    /*
    * 类描述:springMVC的配置
    * @auther wangmx
    * @create 2018/8/20  
    */
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter {
    
        /**
         * 登陆拦截
         * wangmx
         */
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
        	 registry.addInterceptor( new LoginHanderInterceptor())
             .addPathPatterns( "/**" ).excludePathPatterns("/", "/index.jsp","/ful/nologin","/ful/login");
            //除了index.jsp 和 /ful/nologin 和 /ful/login 全部拦截
        }
        
    
    }

    3.登陆的controller:

    //登陆拦截之后 跳转的 controller 返回到 登陆的 jsp 页面
    @RequestMapping(value = "/nologin")
    	 public String myDataAndReport() {
    		
    		return "redirect:/login.jsp";
    }
    
    

    登陆页面 正常采用 from表单提交就可以了

    展开全文
  • springboot实现同一个用户只能登陆一次 再次登陆顶下上一次登陆的用户 创建session管理器 上下文MySessionContext public class MySessionContext { private static MySessionContext context; private Map&...
  • 主要介绍了springboot+jwt实现token登陆权限认证的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 13,450
精华内容 5,380
关键字:

springboot登陆实现

spring 订阅