spring security oauth2_SpringBoot入门建站全系列(三十五)整合Oauth2做单机版认证授权

news/2024/5/16 22:42:22/文章来源:https://blog.csdn.net/weixin_39804631/article/details/110510477

v2-d1baf746d889b015bafb298056cb4973_1440w.jpg?source=172ae18b

SpringBoot入门建站全系列(三十五)整合Oauth2做单机版认证授权

一、概述

OAuth 2.0 规范定义了一个授权(delegation)协议,对于使用Web的应用程序和API在网络上传递授权决策非常有用。OAuth被用在各钟各样的应用程序中,包括提供用户认证的机制。

四种模式:

- 密码模式;

- 授权码模式;

- 简化模式;

- 客户端模式;

四种角色:

- 资源拥有者;

- 资源服务器;

- 第三方应用客户端;

- 授权服务器;

本文主要说明授权码模式。

首发地址:   品茗IT: https://www.pomit.cn/p/2806101761026561

如果大家正在寻找一个java的学习环境,或者在开发中遇到困难,可以加入我们的java学习圈,点击即可加入,共同学习,节约学习时间,减少很多在学习中遇到的难题。

本篇和Spring的整合Oauth2:《Spring整合Oauth2单机版认证授权详情》并没有多大区别,真正将Oauth2用起来做单点登录,需要考虑的东西不止这些,这里只是做单机演示说明,后续会在SpringCloud专题中对真实环境的单点登录做详细说明。

二、基本配置

2.1 Maven依赖

需要引入oauth2用到的依赖,以及数据源、mybatis依赖。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency><groupId>org.springframework.security.oauth</groupId><artifactId>spring-security-oauth2</artifactId><version>${security.oauth2.version}</version>
</dependency>

2.2 配置文件

在application.properties 中需要配置数据库相关信息的信息,如:

spring.datasource.type=org.apache.commons.dbcp2.BasicDataSource
spring.datasource.dbcp2.max-wait-millis=60000
spring.datasource.dbcp2.min-idle=20
spring.datasource.dbcp2.initial-size=2
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.connection-properties=characterEncoding=utf8
spring.datasource.dbcp2.validation-query=SELECT 1
spring.datasource.dbcp2.test-while-idle=true
spring.datasource.dbcp2.test-on-borrow=true
spring.datasource.dbcp2.test-on-return=falsespring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/boot?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC
spring.datasource.username=cff
spring.datasource.password=123456mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

这只是数据库的配置而已,无须oauth2的配置。

三、配置资源服务器

资源服务器需要使用@EnableResourceServer开启,是标明哪些资源是受Ouath2保护的。下面的代码标明/api是受保护的,而且资源id是my_rest_api。

ResourceServerConfiguration:

package com.cff.springbootwork.oauth.resource;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.security.oauth2.provider.error.OAuth2AccessDeniedHandler;@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {private static final String RESOURCE_ID = "my_rest_api";@Overridepublic void configure(ResourceServerSecurityConfigurer resources) {resources.resourceId(RESOURCE_ID).stateless(false);}@Overridepublic void configure(HttpSecurity http) throws Exception {http.anonymous().disable().requestMatchers().antMatchers("/api/**").and().authorizeRequests().antMatchers("/api/**").authenticated().and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());}}

四、配置授权服务器

授权服务器需要使用@EnableAuthorizationServer注解开启,主要负责client的认证,token的生成的。AuthorizationServerConfiguration需要依赖SpringSecurity的配置,因此下面还是要说SpringSecurity的配置。

4.1 授权配置

AuthorizationServerConfiguration:

package com.cff.springbootwork.oauth.auth;import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;import com.cff.springbootwork.oauth.provider.DefaultPasswordEncoder;@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {private static String REALM = "MY_OAUTH_REALM";@Autowiredprivate AuthenticationManager authenticationManager;@AutowiredDefaultPasswordEncoder defaultPasswordEncoder;@Autowired@Qualifier("authorizationCodeServices")private AuthorizationCodeServices authorizationCodeServices;/*** 可以在这里将客户端数据替换成数据库配置。* * @return*/@Beanpublic ClientDetailsService clientDetailsService() {InMemoryClientDetailsService inMemoryClientDetailsService = new InMemoryClientDetailsService();BaseClientDetails baseClientDetails = new BaseClientDetails();baseClientDetails.setClientId("MwonYjDKBuPtLLlK");baseClientDetails.setClientSecret(defaultPasswordEncoder.encode("123456"));baseClientDetails.setAccessTokenValiditySeconds(120);baseClientDetails.setRefreshTokenValiditySeconds(600);Set<String> salesWords = new HashSet<String>() {{add("http://www.pomit.cn");}};baseClientDetails.setRegisteredRedirectUri(salesWords);List<String> scope = Arrays.asList("read", "write", "trust");baseClientDetails.setScope(scope);List<String> authorizedGrantTypes = Arrays.asList("authorization_code", "refresh_token");baseClientDetails.setAuthorizedGrantTypes(authorizedGrantTypes);Map<String, ClientDetails> clientDetailsStore = new HashMap<>();clientDetailsStore.put("MwonYjDKBuPtLLlK", baseClientDetails);inMemoryClientDetailsService.setClientDetailsStore(clientDetailsStore);return inMemoryClientDetailsService;}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.withClientDetails(clientDetailsService());}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authenticationManager(authenticationManager);endpoints.authorizationCodeServices(authorizationCodeServices);}@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.allowFormAuthenticationForClients();oauthServer.realm(REALM + "/client");}
}

这里的 - clientDetailsService是配置文件中配置的客户端详情; - tokenStore是token存储bean; - authenticationManager安全管理器,使用Spring定义的即可,但要声明为bean。 - authorizationCodeServices是配置文件中我们自定义的token生成bean。 - PasswordEncoder密码处理工具类,必须指定的一个bean,可以使用NoOpPasswordEncoder来表明并未对密码做任何处理,实际上你可以实现PasswordEncoder来写自己的密码处理方案。 - UserApprovalHandler 需要定义为bean的Oauth2授权通过处理器。

4.2 密码处理器

DefaultPasswordEncoder 负责对密码进行转换。

DefaultPasswordEncoder :

package com.cff.springbootwork.oauth.provider;import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;@Component
public class DefaultPasswordEncoder implements PasswordEncoder {public DefaultPasswordEncoder() {this(-1);}/*** @param strength*            the log rounds to use, between 4 and 31*/public DefaultPasswordEncoder(int strength) {}public String encode(CharSequence rawPassword) {return rawPassword.toString();}public boolean matches(CharSequence rawPassword, String encodedPassword) {return rawPassword.toString().equals(encodedPassword);}
}

4.3 自定义的Token的Code生成逻辑

这个就是定义在授权服务器AuthorizationServerConfiguration 中的authorizationCodeServices。

InMemoryAuthorizationCodeServices:

package com.cff.springbootwork.oauth.token;import java.util.concurrent.ConcurrentHashMap;import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;@Service("authorizationCodeServices")
public class InMemoryAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {protected final ConcurrentHashMap<String, OAuth2Authentication> authorizationCodeStore = new ConcurrentHashMap<String, OAuth2Authentication>();private RandomValueStringGenerator generator = new RandomValueStringGenerator(16);@Overrideprotected void store(String code, OAuth2Authentication authentication) {this.authorizationCodeStore.put(code, authentication);}@Overridepublic OAuth2Authentication remove(String code) {OAuth2Authentication auth = this.authorizationCodeStore.remove(code);return auth;}@Overridepublic String createAuthorizationCode(OAuth2Authentication authentication) {String code = generator.generate();store(code, authentication);return code;}
}

五、SpringSecurity配置

5.1 SpringSecurity常规配置

SpringSecurity的配置在客户端和认证授权服务器中是必须的,这里是单机,它更是必须的。

ClientSecurityConfiguration:

package com.cff.springbootwork.oauth.client;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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;import com.cff.springbootwork.oauth.handler.AjaxAuthFailHandler;
import com.cff.springbootwork.oauth.handler.AjaxAuthSuccessHandler;
import com.cff.springbootwork.oauth.handler.AjaxLogoutSuccessHandler;
import com.cff.springbootwork.oauth.handler.UnauthorizedEntryPoint;
import com.cff.springbootwork.oauth.provider.SimpleAuthenticationProvider;@Configuration
@EnableWebSecurity
public class ClientSecurityConfiguration extends WebSecurityConfigurerAdapter {@Autowiredprivate SimpleAuthenticationProvider simpleAuthenticationProvider;@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(simpleAuthenticationProvider);}@Overridepublic void configure(HttpSecurity http) throws Exception {SimpleUrlAuthenticationFailureHandler hander = new SimpleUrlAuthenticationFailureHandler();hander.setUseForward(true);hander.setDefaultFailureUrl("/login.html");http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint()).and().csrf().disable().authorizeRequests().antMatchers("/oauth/**").permitAll().antMatchers("/mybatis/**").authenticated().and().formLogin().loginPage("/login.html").usernameParameter("userName").passwordParameter("userPwd").loginProcessingUrl("/login").successHandler(new AjaxAuthSuccessHandler()).failureHandler(new AjaxAuthFailHandler()).and().logout().logoutUrl("/logout").logoutSuccessHandler(new AjaxLogoutSuccessHandler());http.authorizeRequests().antMatchers("/user/**").authenticated();}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}
}

这里,

  • SimpleAuthenticationProvider 是用户名密码认证处理器。下面会说。
  • authenticationManager安全管理器,使用Spring定义的即可,但要声明为bean。
  • configure方法是SpringSecurity配置的常规写法。
  • UnauthorizedEntryPoint:未授权的统一处理方式。
  • successHandler、failureHandler、logoutSuccessHandler顾名思义,就是响应处理逻辑,如果不打算单独处理,只做跳转,有响应的successForwardUrl、failureForwardUrl、logoutSuccessUrl等。

5.2 SpringSecurity用户名密码验证器

SimpleAuthenticationProvider 实现了AuthenticationProvider 接口的authenticate方法,提供用户名密码的校验,校验成功后,生成UsernamePasswordAuthenticationToken。

这里面用到的userInfoService,是自己实现从数据库中获取用户信息的业务逻辑。

SimpleAuthenticationProvider :

package com.cff.springbootwork.oauth.provider;import java.util.Collection;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;import com.cff.springbootwork.mybatis.domain.UserInfo;
import com.cff.springbootwork.mybatis.service.UserInfoService;@Component
public class SimpleAuthenticationProvider implements AuthenticationProvider {@Autowiredprivate UserInfoService userInfoService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String userName = authentication.getPrincipal().toString();UserInfo user = userInfoService.getUserInfoByUserName(userName);if (user == null) {throw new BadCredentialsException("查无此用户");}if (user.getPasswd() != null && user.getPasswd().equals(authentication.getCredentials())) {Collection<? extends GrantedAuthority> authorities = AuthorityUtils.NO_AUTHORITIES;return new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPasswd(), authorities);} else {throw new BadCredentialsException("用户名或密码错误。");}}@Overridepublic boolean supports(Class<?> arg0) {return true;}}

六、测试Oauth2

6.1 Web测试接口

OauthRest :

package com.cff.springbootwork.oauth.web;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;import com.cff.springbootwork.mybatis.domain.UserInfo;
import com.cff.springbootwork.mybatis.service.UserInfoService;@RestController
@RequestMapping("/api")
public class OauthRest {@AutowiredUserInfoService userInfoService;@RequestMapping(value = "/page", method = { RequestMethod.GET })public List<UserInfo> page() {return userInfoService.page(1, 10);}}

6.2 测试过程

  1. 首先访问http://127.0.0.1:8080/api/test。 提示
<oauth>
<error_description>
An Authentication object was not found in the SecurityContext
</error_description>
<error>unauthorized</error>
</oauth>

这标明,oauth2控制了资源,需要access_token。

  1. 请求授权接口oauth/authorize:http://localhost:8080/oauth/authorize?response_type=code&client_id=MwonYjDKBuPtLLlK&redirect_uri=http://www.pomit.cn

client_id是配置文件中写的,redirect_uri随意,因为单机版的只是测试接口。后面会整理下多机版的博文。

打开后自动调整到登录页面:

v2-8a42bfa3777c651d0f03a2fa740658c0_b.jpg

输入正确的用户名密码,调整到授权页面。

v2-585c344c876ad87d56f98d981538d66d_b.jpg

点击同意以后,调整到redirect_uri指定的页面。

v2-217c929660ff92492eac1e7fa714f4d9_b.jpg

获取到code:TnSFA6vrIZiKadwr

  1. 用code换取access_token,请求token接口:http://127.0.0.1:8080/oauth/token?grant_type=authorization_code&code=TnSFA6vrIZiKadwr&client_id=MwonYjDKBuPtLLlK&client_secret=secret&redirect_uri=http://www.pomit.cn。这个请求必须是post,因此不能在浏览器中输入了,可以使用postman:

v2-76f9aeb0ab5ee1d6a45651618f5bbe22_b.jpg

获取到access_token为:686dc5d5-60e9-48af-bba7-7f16b49c248b。

  1. 用access_token请求/api/test接口:

http://127.0.0.1:8080/api/test?access_token=686dc5d5-60e9-48af-bba7-7f16b49c248b结果为:

v2-f7b2e9ed049e3c74a7d9bb0652a3a6f5_b.png

七、过程中用到的其他实体及逻辑

AjaxAuthFailHandler:

package com.cff.springbootwork.oauth.handler;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;public class AjaxAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,AuthenticationException exception) throws IOException, ServletException {if (isAjaxRequest(request)) {ResultModel rm = new ResultModel(ResultCode.CODE_00014.getCode(), exception.getMessage());ObjectMapper mapper = new ObjectMapper();response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);mapper.writeValue(response.getWriter(), rm);} else {setDefaultFailureUrl("/login.html");super.onAuthenticationFailure(request, response, exception);}}public static boolean isAjaxRequest(HttpServletRequest request) {String ajaxFlag = request.getHeader("X-Requested-With");return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);}
}

AjaxAuthSuccessHandler:

package com.cff.springbootwork.oauth.handler;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;public class AjaxAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {protected final Log logger = LogFactory.getLog(this.getClass());@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,Authentication authentication) throws IOException, ServletException {request.getSession().setAttribute("userName", authentication.getName());if (isAjaxRequest(request)) {ResultModel rm = new ResultModel(ResultCode.CODE_00000);ObjectMapper mapper = new ObjectMapper();response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);mapper.writeValue(response.getWriter(), rm);} else {super.onAuthenticationSuccess(request, response, authentication);}}public static boolean isAjaxRequest(HttpServletRequest request) {String ajaxFlag = request.getHeader("X-Requested-With");return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);}
}

AjaxLogoutSuccessHandler:

package com.cff.springbootwork.oauth.handler;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;public class AjaxLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)throws IOException, ServletException {if (isAjaxRequest(request)) {ResultModel rm = new ResultModel(ResultCode.CODE_00000);ObjectMapper mapper = new ObjectMapper();response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);mapper.writeValue(response.getWriter(), rm);} else {super.onLogoutSuccess(request, response, authentication);}}public static boolean isAjaxRequest(HttpServletRequest request) {String ajaxFlag = request.getHeader("X-Requested-With");return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);}
}

UnauthorizedEntryPoint:

package com.cff.springbootwork.oauth.handler;import java.io.IOException;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;import com.cff.springbootwork.oauth.model.ResultCode;
import com.cff.springbootwork.oauth.model.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {@Overridepublic void commence(HttpServletRequest request, HttpServletResponse response,AuthenticationException authException) throws IOException, ServletException {if (isAjaxRequest(request)) {ResultModel rm = new ResultModel(ResultCode.CODE_40004);ObjectMapper mapper = new ObjectMapper();response.setStatus(HttpStatus.OK.value());response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);mapper.writeValue(response.getWriter(), rm);} else {response.sendRedirect("/login.html");}}public static boolean isAjaxRequest(HttpServletRequest request) {String ajaxFlag = request.getHeader("X-Requested-With");return ajaxFlag != null && "XMLHttpRequest".equals(ajaxFlag);}
}

ResultModel:

package com.cff.springbootwork.oauth.model;public class ResultModel {String code;String message;public String getCode() {return code;}public void setCode(String code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public ResultModel() {}public ResultModel(String code, String messgae) {this.code = code;this.message = messgae;}public ResultModel(String messgae) {this.code = "00000";this.message = messgae;}public static ResultModel ok(String messgae) {return new ResultModel("00000", messgae);}
}

八、Mybatis的逻辑及实体

UserInfoService:

package com.cff.springbootwork.mybatis.service;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import com.cff.springbootwork.mybatis.dao.UserInfoDao;
import com.cff.springbootwork.mybatis.domain.UserInfo;@Service
public class UserInfoService {@AutowiredUserInfoDao userInfoDao;public UserInfo getUserInfoByUserName(String userName){return userInfoDao.findByUserName(userName);}public List<UserInfo> page(int page, int size){return userInfoDao.testPageSql(page, size);}public List<UserInfo> testTrimSql(UserInfo userInfo){return userInfoDao.testTrimSql(userInfo);}
}

UserInfoMapper:

package com.cff.springbootwork.mybatis.dao;import java.util.List;import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;import com.cff.springbootwork.mybatis.domain.UserInfo;@Mapper
public interface UserInfoDao {@Select({"<script>","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","FROM user_info","WHERE user_name = #{userName,jdbcType=VARCHAR}","</script>"})UserInfo findByUserName(@Param("userName") String userName);@Select({"<script>","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","FROM user_info","WHERE mobile = #{mobile,jdbcType=VARCHAR}","<if test='userType != null and userType != "" '> and user_type = #{userType, jdbcType=VARCHAR} </if>","</script>"})List<UserInfo> testIfSql(@Param("mobile") String mobile,@Param("userType") String userType);@Select({"<script>","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","     FROM user_info ","    WHERE mobile IN (","   <foreach collection = 'mobileList' item='mobileItem' index='index' separator=',' >","      #{mobileItem}","   </foreach>","   )","</script>"})List<UserInfo> testForeachSql(@Param("mobileList") List<String> mobile);@Update({"<script>","   UPDATE user_info","   SET ","   <choose>","   <when test='userType!=null'> user_type=#{user_type, jdbcType=VARCHAR} </when>","   <otherwise> user_type='0000' </otherwise>","   </choose>","   WHERE user_name = #{userName, jdbcType=VARCHAR}","</script>" })int testUpdateWhenSql(@Param("userName") String userName,@Param("userType") String userType);@Select({"<script>","<bind name="tableName" value="item.getIdentifyTable()" />","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","FROM ${tableName}","WHERE mobile = #{item.mobile,jdbcType=VARCHAR}","</script>"})public List<UserInfo> testBindSql(@Param("item") UserInfo userInfo);@Select({"<script>","<bind name="startNum" value="page*pageSize" />","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","FROM user_info","ORDER BY mobile ASC","LIMIT #{pageSize} OFFSET #{startNum}","</script>"})public List<UserInfo> testPageSql(@Param("page") int page, @Param("pageSize") int size);@Select({"<script>","SELECT ","user_name as userName,passwd,name,mobile,valid, user_type as userType","FROM user_info","<trim prefix=" where " prefixOverrides="AND">","<if test='item.userType != null and item.userType != "" '> and user_type = #{item.userType, jdbcType=VARCHAR} </if>","<if test='item.mobile != null and item.mobile != "" '> and mobile = #{item.mobile, jdbcType=VARCHAR} </if>","</trim>","</script>"})public List<UserInfo> testTrimSql(@Param("item") UserInfo userInfo);@Update({"<script>","   UPDATE user_info","   <set> ","<if test='item.userType != null and item.userType != "" '>user_type = #{item.userType, jdbcType=VARCHAR}, </if>","<if test='item.mobile != null and item.mobile != "" '> mobile = #{item.mobile, jdbcType=VARCHAR} </if>","   </set>","   WHERE user_name = #{item.userName, jdbcType=VARCHAR}","</script>" })public int testSetSql(@Param("item") UserInfo userInfo);
}

UserInfo:

package com.cff.springbootwork.mybatis.domain;public class UserInfo {private String userName;private String passwd;private String name;private String mobile;private Integer valid;private String userType;public UserInfo() {}public UserInfo(UserInfo src) {this.userName = src.userName;this.passwd = src.passwd;this.name = src.name;this.mobile = src.mobile;this.valid = src.valid;}public UserInfo(String userName, String passwd, String name, String mobile, Integer valid) {super();this.userName = userName;this.passwd = passwd;this.name = name;this.mobile = mobile;this.valid = valid;}public void setUserName(String userName) {this.userName = userName;}public String getUserName() {return userName;}public void setPasswd(String passwd) {this.passwd = passwd;}public String getPasswd() {return passwd;}public void setName(String name) {this.name = name;}public String getName() {return name;}public void setMobile(String mobile) {this.mobile = mobile;}public String getMobile() {return mobile;}public void setValid(Integer valid) {this.valid = valid;}public Integer getValid() {return valid;}public String getUserType() {return userType;}public void setUserType(String userType) {this.userType = userType;}public String getIdentifyTable(){return "user_info";}
}

品茗IT-博客专题:https://www.pomit.cn/lecture.html汇总了Spring专题、Springboot专题、SpringCloud专题、web基础配置专题。

快速构建项目

Spring项目快速开发工具:

一键快速构建Spring项目工具

一键快速构建SpringBoot项目工具

一键快速构建SpringCloud项目工具

一站式Springboot项目生成

Mysql一键生成Mybatis注解Mapper

Spring组件化构建

SpringBoot组件化构建

SpringCloud服务化构建

喜欢这篇文章么,喜欢就加入我们一起讨论Java Web吧!

v2-054f041a8817d9c16f3ee0eaf3b73242_b.jpg

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_772745.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

html个人博客完整代码_GitHub Pages 建立个人网站详细教程

本文作者&#xff1a;雨知一、Git简介Git是一个开源的分布式版本控制系统&#xff0c;用以有效、高速的处理从很小到非常大的项目版本管理。GitHub可以托管各种git库的站点。GitHub Pages是免费的静态站点&#xff0c;三个特点&#xff1a;免费托管、自带主题、支持自制页面和J…

律师事务所php源码,扁平化PHPCMS律师网站模板,PHPCMS律师事务所源码

【程序版本】&#xff1a;PHPCMS V9.5 UTF-8 开源无限制【网站编号】&#xff1a;65网站说明&#xff1a;此站采用当下最流行的扁平化风格&#xff0c;大气不失庄严&#xff0c;首页 侧栏 咨询页面的提交表单完美整合&#xff0c;加入JS验证&#xff0c;防止软件恶意提交&#…

推荐两个免费下载Smartphone桌面主题的网站

http://smartphone.krisdoff.net/ http://smartphone.kleinweder.ch/downloads/ 看着流口水吧&#xff1f;快去下载吧&#xff0c;给自己的手机装扮一下&#xff01;

黑群晖安装docker跑ssr_JSRender: 一个SEO优化的SSR工具包

JSRender 是一个基于koa puppeteer 构建的 SSR 服务端渲染 SEO 工具&#xff0c;可以帮助任何类型的前端渲染页面进行快速服务端渲染&#xff0c;从而实现前端渲染类页面进行SEO优化。因为当时正好有个项目是用phpjq进行数据获取的&#xff0c;现在市面上的SSR工具多针对react…

javaeye网站推出了为博客做pdf电子书的服务

这是个非常好的功能&#xff0c;希望博客园也能跟进。风格很好。 http://robbin.javaeye.com/blog/269765 转载于:https://www.cnblogs.com/yukaizhao/archive/2008/11/21/1338536.html

xpath爬取页面内容保存成文档_利用python爬取慕课网站上面课程

1、抓取网站情况介绍抓取网站&#xff1a;http://www.imooc.com/course/list 抓取内容&#xff1a;要抓取的内容是全部的课程名称&#xff0c;课程简介&#xff0c;课程URL &#xff0c;课程图片URL&#xff0c;课程人数&#xff08;由于动态渲染暂时没有获取到&#xff09;网站…

两个很好玩的网站

第一个网站模拟了Windows 3的界面。请注意不只是界面&#xff0c;里面的程序是可以运行的&#xff0c;包括可以扫雷&#xff0c;以及使用内部的Internet Explorer去上网 第二个模拟了Visual Studio的界面和功能&#xff0c;请注意不只是界面&#xff0c;是包含功能&#xff0c;…

html结尾的网址有哪些,网站 URL 结尾使用斜杠是否有利于 SEO 优化?

相信对于很多人来说&#xff0c;只要你足够重视网站 SEO 优化&#xff0c;那么相比你可能也曾纠结过网站 URL 该这样操作才更有利于优化排名&#xff0c;前段时间子凡就成对泪雪网的 URL 做过升级&#xff0c;其中也曾小小的纠结过这个问题&#xff0c;那么就给大家分享一下。首…

如何修改WP主题优化SEO效果

为什么80%的码农都做不了架构师&#xff1f;>>> 现在有越来越多的SEO主题发布&#xff0c;寻找一款SEO优化过的主题并不是件难事&#xff0c;只需要百度或者google下。很多人为了更好地提高百度收录&#xff0c;而选择使用一些所谓的SEO主题&#xff0c;其实并没有…

作者为何要创作《网站转换率优化之道》

创作本书的动机来自一次痛苦的教训。 2005年年末&#xff0c;我&#xff08;Khalid&#xff0c;作者之一&#xff09;得到了一个机会&#xff0c;去领导设计和实现一家电子商务网站&#xff0c;那是北美最大的电子商务网站之一&#xff0c;这个项目获得了1500万美元的巨额预算。…

做网站用什么语言_做网站SEO优化每天都做什么

做网站SEO优化每天都做什么在SEO优化一个站点时候&#xff0c;通常来说我们是很忙碌的&#xff0c;因为网站SEO优化所涉及到很多领域&#xff0c;网站SEO优化并不只是SEO优化网站本身&#xff0c;甚至连互联网圈以及互联网圈周边的事都需要有着提前的洞察能力。哪怕是凑热点&am…

redis list应用–大型网站缓冲队列服务器

2019独角兽企业重金招聘Python工程师标准>>> 1. 起因&#xff0c; 随着twitter sina微博&#xff0c;腾讯微博的开放平台相继推出, 大部分和互联网相关的公司又多了一个营销的手段&#xff1a;信息同步。也即是用户把自己的新浪微博账号或者腾讯微博账号和你的网站关…

linux搭建cdn教程_网站搭建新手教程:一步一步教你拥有一个属于自己WordPress网站...

应网友要求&#xff0c;今天知识吧为大家分享一篇新手建站教程&#xff0c;本来是打算做一个视频教程的&#xff0c;毕竟大家看的会直观一些&#xff0c;但是由于我的个人电脑在并不在身边&#xff0c;在公司电脑录新手建站视频又不太合适&#xff0c;所以就为大家写一篇图文教…

23套新鲜出炉的网站和手机界面 PSD 素材

Web 用户界面&#xff0c;移动用户界面和线框套件对设计师很有用&#xff0c;因为这些套件让他们使用快速和有效的方式复制用户界面。这些类型的工具包提供了一个基本的用户界面元素&#xff0c;用于它们需要制作的网站或软件模型。 在这篇文章中&#xff0c;我们展示的是自由和…

网站导航不止有hao123!

网址导航对于我们上网而言非常的重要&#xff0c;在一定程度上决定了我们每天都在接触一些什么样的网络信息。我个人一直用的是hao123&#xff0c;总体感觉这个网址导航是非常的不错的&#xff0c;不过网址导航不只只有这一个好的更不只有这一个&#xff01;下面是我认为挺不错…

app打开小程序_小程序可以替代app吗 小程序网站app开发

小程序唤起App&#xff0c;开发者如何使用新能力通过小程序唤起 App 要求很严格&#xff0c;小程序才能唤起 App。同时&#xff0c;如果没有安装 App&#xff0c;唤起有可能会失败。现在&#xff0c;开发者可以通过修改配置文件的方式&#xff0c;将标题栏整体隐藏&#xff0c;…

网站运维之道 之流程规范

2019独角兽企业重金招聘Python工程师标准>>> 流程规范 对于相对正规的网站维护工作&#xff0c;所有网站的所有变更必须能做到有记录&#xff0c;可回溯。如果是单枪匹马作战&#xff0c;那么要实现这个目标并不是很难&#xff0c;只需要把好习惯培养起来就成了&…

世界各国语言学习网站大全

2019独角兽企业重金招聘Python工程师标准>>> 亚洲&#xff08;Asia) http://www.zanhe.com/ 【上海话教程】http://www.shanghai.or.jp/zw/shanghai/ 【当代上海话】 ☆☆☆☆Chinese (Cantonese)汉语(广州话)http://www.khuang.com/chinese/cantonese.asp 【粤语角…

Nginx配置SSL证书部署HTTPS网站

一、什么是 SSL 证书&#xff0c;什么是 HTTPS SSL 证书是一种数字证书&#xff0c;它使用 Secure Socket Layer 协议在浏览器和 Web 服务器之间建立一条安全通道&#xff0c;从而实现&#xff1a; 1、数据信息在客户端和服务器之间的加密传输&#xff0c;保证双方传递信息的安…