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=false
spring.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=123456
mybatis.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";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public 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";
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
DefaultPasswordEncoder defaultPasswordEncoder;
@Autowired
@Qualifier("authorizationCodeServices")
private AuthorizationCodeServices authorizationCodeServices;
/**
* 可以在这里将客户端数据替换成数据库配置。
*
* @return
*/
@Bean
public 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;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
endpoints.authorizationCodeServices(authorizationCodeServices);
}
@Override
public 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);
@Override
protected void store(String code, OAuth2Authentication authentication) {
this.authorizationCodeStore.put(code, authentication);
}
@Override
public OAuth2Authentication remove(String code) {
OAuth2Authentication auth = this.authorizationCodeStore.remove(code);
return auth;
}
@Override
public 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 {
@Autowired
private SimpleAuthenticationProvider simpleAuthenticationProvider;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(simpleAuthenticationProvider);
}
@Override
public 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
@Bean
public 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 {
@Autowired
private UserInfoService userInfoService;
@Override
public 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("用户名或密码错误。");
}
}
@Override
public 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 {
@Autowired
UserInfoService userInfoService;
@RequestMapping(value = "/page", method = { RequestMethod.GET })
public List<UserInfo> page() {
return userInfoService.page(1, 10);
}
}
6.2 测试过程
- 首先访问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。
- 请求授权接口oauth/authorize:
http://localhost:8080/oauth/authorize?response_type=code&client_id=MwonYjDKBuPtLLlK&redirect_uri=http://www.pomit.cn
client_id是配置文件中写的,redirect_uri随意,因为单机版的只是测试接口。后面会整理下多机版的博文。
打开后自动调整到登录页面:
输入正确的用户名密码,调整到授权页面。
点击同意以后,调整到redirect_uri指定的页面。
获取到code:TnSFA6vrIZiKadwr
- 用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:
获取到access_token为:686dc5d5-60e9-48af-bba7-7f16b49c248b。
- 用access_token请求/api/test接口:
http://127.0.0.1:8080/api/test?access_token=686dc5d5-60e9-48af-bba7-7f16b49c248b
结果为:
七、过程中用到的其他实体及逻辑
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 {
@Override
public 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());
@Override
public 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 {
@Override
public 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 {
@Autowired
UserInfoDao 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项目快速开发工具:
喜欢这篇文章么,喜欢就加入我们一起讨论Java Web吧!