当前位置:   article > 正文

SpringMVC +Spring+ SpringJDBC 整合 教程_springmvc引入springjdbc

springmvc引入springjdbc

项目文件结构,如下截图:


第一步:整合web.xml 文件,主要实现SpringMVC监听器(DispatchServlet)、编码过滤器、Spring监听器和内存监听器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  5. http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  6. <display-name></display-name>
  7. <!-- Spring和mybatis的配置文件 -->
  8. <context-param>
  9. <param-name>contextConfigLocation</param-name>
  10. <param-value>classpath:spring-mybatis.xml</param-value>
  11. </context-param>
  12. <!-- 编码过滤器 -->
  13. <filter>
  14. <filter-name>encodingFilter</filter-name>
  15. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  16. <init-param>
  17. <param-name>encoding</param-name>
  18. <param-value>UTF-8</param-value>
  19. </init-param>
  20. </filter>
  21. <filter-mapping>
  22. <filter-name>encodingFilter</filter-name>
  23. <url-pattern>/*</url-pattern>
  24. </filter-mapping>
  25. <!-- Spring监听器 -->
  26. <listener>
  27. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  28. </listener>
  29. <!-- 防止Spring内存溢出监听器 -->
  30. <listener>
  31. <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  32. </listener>
  33. <!-- Spring MVC servlet -->
  34. <servlet>
  35. <servlet-name>SpringMVC</servlet-name>
  36. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  37. <init-param>
  38. <param-name>contextConfigLocation</param-name>
  39. <param-value>classpath:spring-mvc.xml</param-value>
  40. </init-param>
  41. <load-on-startup>1</load-on-startup>
  42. </servlet>
  43. <servlet-mapping>
  44. <servlet-name>SpringMVC</servlet-name>
  45. <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
  46. <url-pattern>/</url-pattern>
  47. </servlet-mapping>
  48. <welcome-file-list>
  49. <welcome-file>/index.jsp</welcome-file>
  50. </welcome-file-list>
  51. </web-app>

第二步:spring-mvc.xml 和spring-mybatis.xml 配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-3.1.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
  12. <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
  13. <mvc:annotation-driven />
  14. <mvc:default-servlet-handler />
  15. <context:annotation-config />
  16. <!-- 扫描所有的controller 但是不扫描service-->
  17. <!--
  18. <context:component-scan base-package="com.wlsq.oauth">
  19. <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
  20. <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
  21. </context:component-scan> -->
  22. <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
  23. <context:component-scan base-package="com.wlsq.oauth.controller" />
  24. <context:component-scan base-package="com.wlsq.oauth.service" />
  25. <context:component-scan base-package="com.wlsq.oauth.dao" />
  26. <!-- 声明DispatcherServlet不要拦截下面声明的目录 -->
  27. <!-- <mvc:resources location="/js/" mapping="/js/**" />
  28. <mvc:resources location="/images/" mapping="/images/**" />
  29. <mvc:resources location="/css/" mapping="/css/**" />
  30. <mvc:resources location="/common/" mapping="/common/**" /> -->
  31. <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
  32. <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
  33. <!-- <context:component-scan base-package="com.cn.hnust.controller" />-->
  34. <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
  35. <bean id="mappingJacksonHttpMessageConverter"
  36. class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
  37. <property name="supportedMediaTypes">
  38. <list>
  39. <value>text/html;charset=UTF-8</value>
  40. </list>
  41. </property>
  42. </bean>
  43. <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
  44. <bean
  45. class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  46. <property name="messageConverters">
  47. <list>
  48. <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
  49. </list>
  50. </property>
  51. </bean>
  52. <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
  53. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  54. <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
  55. <!--<property name="prefix" value="/WEB-INF/jsp/" />
  56. <property name="suffix" value=".jsp" /> -->
  57. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  58. <property name="contentType" value="text/html"/>
  59. <property name="prefix" value="/WEB-INF/jsp/"/>
  60. <property name="suffix" value=".jsp"/>
  61. </bean>
  62. <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
  63. <bean id="multipartResolver"
  64. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  65. <!-- 默认编码 -->
  66. <property name="defaultEncoding" value="utf-8" />
  67. <!-- 文件大小最大值 -->
  68. <property name="maxUploadSize" value="10485760000" />
  69. <!-- 内存中的最大值 -->
  70. <property name="maxInMemorySize" value="40960" />
  71. </bean>
  72. </beans>

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:aop="http://www.springframework.org/schema/aop"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context-3.2.xsd
  11. http://www.springframework.org/schema/tx
  12. http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
  13. http://www.springframework.org/schema/aop
  14. http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
  15. http://www.springframework.org/schema/mvc
  16. http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  17. <!-- 引入配置文件 -->
  18. <bean id="propertyConfigurer"
  19. class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  20. <property name="locations">
  21. <list>
  22. <value>classpath:jdbc.properties</value>
  23. <value>classpath:memcache.properties</value>
  24. </list>
  25. </property>
  26. </bean>
  27. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
  28. init-method="init" destroy-method="close">
  29. <!-- 基本属性 url、user、password -->
  30. <property name="url" value="${url}" />
  31. <property name="username" value="${username}" />
  32. <property name="password" value="${password}" />
  33. <!-- 配置初始化大小、最小、最大 -->
  34. <property name="initialSize" value="1" />
  35. <property name="minIdle" value="1" />
  36. <property name="maxActive" value="20" />
  37. <!-- 配置获取连接等待超时的时间 -->
  38. <property name="maxWait" value="60000" />
  39. <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
  40. <property name="timeBetweenEvictionRunsMillis" value="60000" />
  41. <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
  42. <property name="minEvictableIdleTimeMillis" value="300000" />
  43. <property name="validationQuery" value="SELECT 'x'" />
  44. <property name="testWhileIdle" value="true" />
  45. <property name="testOnBorrow" value="false" />
  46. <property name="testOnReturn" value="false" />
  47. <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
  48. <property name="poolPreparedStatements" value="true" />
  49. <property name="maxPoolPreparedStatementPerConnectionSize"
  50. value="20" />
  51. <!-- 配置监控统计拦截的filters -->
  52. <property name="filters" value="stat" />
  53. </bean>
  54. <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
  55. <bean id="dataSourceProxy" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
  56. <property name="targetDataSource" ref="dataSource"/>
  57. </bean>
  58. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  59. <constructor-arg ref="dataSourceProxy"/>
  60. </bean>
  61. <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
  62. <bean id="transactionManager"
  63. class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  64. <property name="dataSource" ref="dataSourceProxy" />
  65. </bean>
  66. <!-- 通知 -->
  67. <tx:advice id="tx" transaction-manager="transactionManager">
  68. <tx:attributes>
  69. <tx:method name="*" propagation="REQUIRED"/>
  70. </tx:attributes>
  71. </tx:advice>
  72. <aop:config>
  73. <aop:pointcut id="pc"
  74. expression="execution(* com.wlsq.oauth.service.*.*(..))" />
  75. <!--把事务控制在Service层 -->
  76. <aop:advisor pointcut-ref="pc" advice-ref="tx" />
  77. </aop:config>
  78. <!--spring 集成缓存服务器(memcached) -->
  79. <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
  80. factory-method="getInstance" init-method="initialize"
  81. destroy-method="shutDown">
  82. <constructor-arg>
  83. <value>memCachedPool</value>
  84. </constructor-arg>
  85. <property name="servers">
  86. <list>
  87. <value>${memcache.server}</value>
  88. </list>
  89. </property>
  90. <property name="initConn">
  91. <value>${memcache.initConn}</value>
  92. </property>
  93. <property name="minConn">
  94. <value>${memcache.minConn}</value>
  95. </property>
  96. <property name="maxConn">
  97. <value>${memcache.maxConn}</value>
  98. </property>
  99. <property name="maintSleep">
  100. <value>${memcache.maintSleep}</value>
  101. </property>
  102. <property name="nagle">
  103. <value>${memcache.nagle}</value>
  104. </property>
  105. <property name="socketTO">
  106. <value>${memcache.socketTO}</value>
  107. </property>
  108. </bean>
  109. <bean id="memCachedClient" class="com.danga.MemCached.MemCachedClient">
  110. <constructor-arg>
  111. <value>memCachedPool</value>
  112. </constructor-arg>
  113. </bean>
  114. <!--自定义bean -->
  115. <bean id="oAuthService" class="com.wlsq.oauth.util.OauthUtil">
  116. <property name="memCachedClient">
  117. <ref bean="memCachedClient"/>
  118. </property>
  119. </bean>
  120. </beans>

3、实体类(OauthClient和OauthUser)

  1. package com.wlsq.oauth.pojo;
  2. public class OauthClient implements java.io.Serializable {
  3. /**
  4. *
  5. */
  6. private static final long serialVersionUID = 1L;
  7. private Long id;
  8. private String clientName;
  9. private String clientId;
  10. private String clientScerct;
  11. public OauthClient() {
  12. }
  13. public OauthClient(Long id, String clientName, String clientId,
  14. String clientScerct) {
  15. super();
  16. this.id = id;
  17. this.clientName = clientName;
  18. this.clientId = clientId;
  19. this.clientScerct = clientScerct;
  20. }
  21. public Long getId() {
  22. return id;
  23. }
  24. public void setId(Long id) {
  25. this.id = id;
  26. }
  27. public String getClientName() {
  28. return clientName;
  29. }
  30. public void setClientName(String clientName) {
  31. this.clientName = clientName;
  32. }
  33. public String getClientId() {
  34. return clientId;
  35. }
  36. public void setClientId(String clientId) {
  37. this.clientId = clientId;
  38. }
  39. public String getClientScerct() {
  40. return clientScerct;
  41. }
  42. public void setClientScerct(String clientScerct) {
  43. this.clientScerct = clientScerct;
  44. }
  45. }

  1. package com.wlsq.oauth.pojo;
  2. public class OauthUser implements java.io.Serializable {
  3. /**
  4. *
  5. */
  6. private static final long serialVersionUID = 1L;
  7. private Long id;
  8. private String username;
  9. private String password;
  10. private String salt;
  11. public OauthUser() {
  12. }
  13. public OauthUser(Long id, String username, String password, String salt) {
  14. super();
  15. this.id = id;
  16. this.username = username;
  17. this.password = password;
  18. this.salt = salt;
  19. }
  20. public Long getId() {
  21. return id;
  22. }
  23. public void setId(Long id) {
  24. this.id = id;
  25. }
  26. public String getUsername() {
  27. return username;
  28. }
  29. public void setUsername(String username) {
  30. this.username = username;
  31. }
  32. public String getPassword() {
  33. return password;
  34. }
  35. public void setPassword(String password) {
  36. this.password = password;
  37. }
  38. public String getSalt() {
  39. return salt;
  40. }
  41. public void setSalt(String salt) {
  42. this.salt = salt;
  43. }
  44. }

4、dao层和dao层 实现

  1. package com.wlsq.oauth.dao;
  2. import java.util.List;
  3. import com.wlsq.oauth.pojo.OauthClient;
  4. public interface OauthClientMapper {
  5. public OauthClient createClient(OauthClient client);// 创建客户端
  6. public OauthClient updateClient(OauthClient client);// 更新客户端
  7. public void deleteClient(Long clientId);// 删除客户端
  8. OauthClient findOne(Long clientId);// 根据id查找客户端
  9. List<OauthClient> findAll();// 查找所有
  10. OauthClient findByClientId(String clientId);// 根据客户端id查找客户端
  11. OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
  12. }
  1. package com.wlsq.oauth.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  8. import org.springframework.jdbc.core.JdbcTemplate;
  9. import org.springframework.jdbc.core.PreparedStatementCreator;
  10. import org.springframework.jdbc.support.GeneratedKeyHolder;
  11. import org.springframework.stereotype.Repository;
  12. import com.wlsq.oauth.pojo.OauthClient;
  13. @Repository
  14. public class OauthClientMapperImpl implements OauthClientMapper {
  15. @Autowired
  16. private JdbcTemplate jdbcTemplate;
  17. @Override
  18. public OauthClient createClient(final OauthClient client) {
  19. // TODO Auto-generated method stub
  20. final String sql = "insert into oauth2_client(client_name, client_id, client_secret) values(?,?,?)";
  21. GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
  22. jdbcTemplate.update(new PreparedStatementCreator() {
  23. @Override
  24. public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
  25. PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
  26. int count = 1;
  27. psst.setString(count++, client.getClientName());
  28. psst.setString(count++, client.getClientId());
  29. psst.setString(count++, client.getClientScerct());
  30. return psst;
  31. }
  32. }, keyHolder);
  33. client.setId(keyHolder.getKey().longValue());
  34. return client;
  35. }
  36. @Override
  37. public OauthClient updateClient(OauthClient client) {
  38. // TODO Auto-generated method stub
  39. String sql = "update oauth2_client set client_name=?, client_id=?, client_secret=? where id=?";
  40. jdbcTemplate.update(
  41. sql,
  42. client.getClientName(), client.getClientId(), client.getClientScerct(), client.getId());
  43. return client;
  44. }
  45. @Override
  46. public void deleteClient(Long clientId) {
  47. // TODO Auto-generated method stub
  48. String sql = "delete from oauth2_client where id=?";
  49. jdbcTemplate.update(sql, clientId);
  50. }
  51. @Override
  52. public OauthClient findOne(Long clientId) {
  53. // TODO Auto-generated method stub
  54. String sql = "select id, client_name, client_id, client_secret from oauth2_client where id=?";
  55. List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
  56. if(clientList.size() == 0) {
  57. return null;
  58. }
  59. return clientList.get(0);
  60. }
  61. @Override
  62. public List<OauthClient> findAll() {
  63. // TODO Auto-generated method stub
  64. String sql = "select id, client_name, client_id, client_secret from oauth2_client";
  65. return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class));
  66. }
  67. @Override
  68. public OauthClient findByClientId(String clientId) {
  69. // TODO Auto-generated method stub
  70. String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_id=?";
  71. List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
  72. if(clientList.size() == 0) {
  73. return null;
  74. }
  75. return clientList.get(0);
  76. }
  77. @Override
  78. public OauthClient findByClientSecret(String clientSecret) {
  79. // TODO Auto-generated method stub
  80. String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_secret=?";
  81. List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientSecret);
  82. if(clientList.size() == 0) {
  83. return null;
  84. }
  85. return clientList.get(0);
  86. }
  87. }


  1. package com.wlsq.oauth.dao;
  2. import java.util.List;
  3. import com.wlsq.oauth.pojo.OauthUser;
  4. public interface OauthUserMapper {
  5. public OauthUser createUser(OauthUser user);// 创建用户
  6. public OauthUser updateUser(OauthUser user);// 更新用户
  7. public void deleteUser(Long userId);// 删除用户
  8. public void changePassword(Long userId, String newPassword); //修改密码
  9. OauthUser findOne(Long userId);// 根据id查找用户
  10. List<OauthUser> findAll();// 得到所有用户
  11. public OauthUser findByUsername(String username);// 根据用户名查找用户
  12. }
  1. package com.wlsq.oauth.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. import javax.annotation.Resource;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  9. import org.springframework.jdbc.core.JdbcTemplate;
  10. import org.springframework.jdbc.core.PreparedStatementCreator;
  11. import org.springframework.jdbc.support.GeneratedKeyHolder;
  12. import org.springframework.stereotype.Repository;
  13. import com.wlsq.oauth.pojo.OauthUser;
  14. @Repository
  15. public class OauthUserMapperImpl implements OauthUserMapper {
  16. @Autowired
  17. private JdbcTemplate jdbcTemplate;
  18. @Override
  19. public OauthUser createUser(final OauthUser user) {
  20. final String sql = "insert into oauth2_user(username, password, salt) values(?,?,?)";
  21. GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
  22. jdbcTemplate.update(new PreparedStatementCreator() {
  23. @Override
  24. public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
  25. PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
  26. int count = 1;
  27. psst.setString(count++, user.getUsername());
  28. psst.setString(count++, user.getPassword());
  29. psst.setString(count++, user.getSalt());
  30. return psst;
  31. }
  32. }, keyHolder);
  33. user.setId(keyHolder.getKey().longValue());
  34. return user;
  35. }
  36. @Override
  37. public OauthUser updateUser(OauthUser user) {
  38. // TODO Auto-generated method stub
  39. String sql = "update oauth2_user set username=?, password=?, salt=? where id=?";
  40. jdbcTemplate.update(
  41. sql,
  42. user.getUsername(), user.getPassword(), user.getSalt(), user.getId());
  43. return user;
  44. }
  45. @Override
  46. public void deleteUser(Long userId) {
  47. // TODO Auto-generated method stub
  48. String sql = "delete from oauth2_user where id=?";
  49. jdbcTemplate.update(sql, userId);
  50. }
  51. @Override
  52. public void changePassword(Long userId, String newPassword) {
  53. // TODO Auto-generated method stub
  54. }
  55. @Override
  56. public OauthUser findOne(Long userId) {
  57. // TODO Auto-generated method stub
  58. String sql = "select id, username, password, salt from oauth2_user where id=?";
  59. List<OauthUser> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), userId);
  60. if(userList.size() == 0) {
  61. return null;
  62. }
  63. return userList.get(0);
  64. }
  65. @Override
  66. public List<OauthUser> findAll() {
  67. // TODO Auto-generated method stub
  68. String sql = "select id, username, password, salt from oauth2_user";
  69. return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class));
  70. }
  71. @Override
  72. public OauthUser findByUsername(String username) {
  73. // TODO Auto-generated method stub
  74. String sql = "select id, username, password, salt from oauth2_user where username=?";
  75. List<OauthUser> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), username);
  76. if(userList.size() == 0) {
  77. return null;
  78. }
  79. return userList.get(0);
  80. }
  81. }
3、service层和service层实现

  1. package com.wlsq.oauth.service;
  2. import java.util.List;
  3. import com.wlsq.oauth.pojo.OauthClient;
  4. public interface IOauthClientMapperService {
  5. public OauthClient createClient(OauthClient client);// 创建客户端
  6. public OauthClient updateClient(OauthClient client);// 更新客户端
  7. public void deleteClient(Long clientId);// 删除客户端
  8. OauthClient findOne(Long clientId);// 根据id查找客户端
  9. List<OauthClient> findAll();// 查找所有
  10. OauthClient findByClientId(String clientId);// 根据客户端id查找客户端
  11. OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
  12. }
  1. package com.wlsq.oauth.service.impl;
  2. import java.util.List;
  3. import java.util.UUID;
  4. import javax.annotation.Resource;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.transaction.annotation.Transactional;
  8. import com.wlsq.oauth.dao.OauthClientMapper;
  9. import com.wlsq.oauth.pojo.OauthClient;
  10. import com.wlsq.oauth.service.IOauthClientMapperService;
  11. @Transactional
  12. @Service("oauthClientService")
  13. public class OauthClientServiceImpl implements IOauthClientMapperService {
  14. @Autowired
  15. private OauthClientMapper clientDao;
  16. @Override
  17. public OauthClient createClient(OauthClient client) {
  18. // TODO Auto-generated method stub
  19. client.setClientId(UUID.randomUUID().toString());
  20. client.setClientScerct(UUID.randomUUID().toString());
  21. return clientDao.createClient(client);
  22. }
  23. @Override
  24. public OauthClient updateClient(OauthClient client) {
  25. // TODO Auto-generated method stub
  26. return clientDao.updateClient(client);
  27. }
  28. @Override
  29. public void deleteClient(Long clientId) {
  30. // TODO Auto-generated method stub
  31. clientDao.deleteClient(clientId);
  32. }
  33. @Override
  34. public OauthClient findOne(Long clientId) {
  35. // TODO Auto-generated method stub
  36. return clientDao.findOne(clientId);
  37. }
  38. @Override
  39. public List<OauthClient> findAll() {
  40. // TODO Auto-generated method stub
  41. return clientDao.findAll();
  42. }
  43. @Override
  44. public OauthClient findByClientId(String clientId) {
  45. // TODO Auto-generated method stub
  46. return clientDao.findByClientId(clientId);
  47. }
  48. @Override
  49. public OauthClient findByClientSecret(String clientSecret) {
  50. // TODO Auto-generated method stub
  51. return clientDao.findByClientSecret(clientSecret);
  52. }
  53. }


  1. package com.wlsq.oauth.service;
  2. import java.util.List;
  3. import com.wlsq.oauth.pojo.OauthUser;
  4. public interface IOauthUserMapperService {
  5. public OauthUser createUser(OauthUser user);// 创建用户
  6. public OauthUser updateUser(OauthUser user);// 更新用户
  7. public void deleteUser(Long userId);// 删除用户
  8. public void changePassword(Long userId, String newPassword); //修改密码
  9. OauthUser findOne(Long userId);// 根据id查找用户
  10. List<OauthUser> findAll();// 得到所有用户
  11. public OauthUser findByUsername(String username);// 根据用户名查找用户
  12. }
  1. package com.wlsq.oauth.service.impl;
  2. import java.util.List;
  3. import javax.annotation.Resource;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Transactional;
  7. import com.wlsq.oauth.dao.OauthUserMapper;
  8. import com.wlsq.oauth.pojo.OauthUser;
  9. import com.wlsq.oauth.service.IOauthUserMapperService;
  10. @Transactional
  11. @Service("oauthUserService")
  12. public class OauthUserServiceImpl implements IOauthUserMapperService {
  13. @Autowired
  14. private OauthUserMapper oauthUserMapper;
  15. @Override
  16. public OauthUser createUser(OauthUser user) {
  17. // TODO Auto-generated method stub
  18. return this.oauthUserMapper.createUser(user);
  19. }
  20. @Override
  21. public OauthUser updateUser(OauthUser user) {
  22. // TODO Auto-generated method stub
  23. return this.oauthUserMapper.updateUser(user);
  24. }
  25. @Override
  26. public void deleteUser(Long userId) {
  27. // TODO Auto-generated method stub
  28. this.oauthUserMapper.deleteUser(userId);
  29. }
  30. @Override
  31. public void changePassword(Long userId, String newPassword) {
  32. // TODO Auto-generated method stub
  33. this.oauthUserMapper.changePassword(userId, newPassword);
  34. }
  35. @Override
  36. public OauthUser findOne(Long userId) {
  37. // TODO Auto-generated method stub
  38. return this.oauthUserMapper.findOne(userId);
  39. }
  40. @Override
  41. public List<OauthUser> findAll() {
  42. // TODO Auto-generated method stub
  43. return this.oauthUserMapper.findAll();
  44. }
  45. @Override
  46. public OauthUser findByUsername(String username) {
  47. // TODO Auto-generated method stub
  48. return this.oauthUserMapper.findByUsername(username);
  49. }
  50. }

4、controller层

  1. package com.wlsq.oauth.controller;
  2. import org.apache.oltu.oauth2.as.issuer.MD5Generator;
  3. import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
  4. import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
  5. import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
  6. import org.apache.oltu.oauth2.as.response.OAuthASResponse;
  7. import org.apache.oltu.oauth2.common.OAuth;
  8. import org.apache.oltu.oauth2.common.error.OAuthError;
  9. import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
  10. import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
  11. import org.apache.oltu.oauth2.common.message.OAuthResponse;
  12. import org.apache.oltu.oauth2.common.message.types.GrantType;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.http.HttpEntity;
  15. import org.springframework.http.HttpStatus;
  16. import org.springframework.http.ResponseEntity;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RestController;
  19. import com.wlsq.oauth.util.OauthUtil;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. import java.net.URISyntaxException;
  23. @RestController
  24. public class AccessTokenController {
  25. @Autowired
  26. private OauthUtil oAuthService;
  27. //@Autowired
  28. //private IOauthUserMapperService userService;
  29. @RequestMapping("/accessToken")
  30. public HttpEntity token(HttpServletRequest request)
  31. throws URISyntaxException, OAuthSystemException {
  32. try {
  33. //构建OAuth请求
  34. OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
  35. //检查提交的客户端id是否正确
  36. if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
  37. OAuthResponse response =
  38. OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  39. .setError(OAuthError.TokenResponse.INVALID_CLIENT)
  40. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  41. .buildJSONMessage();
  42. return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  43. }
  44. // 检查客户端安全KEY是否正确
  45. if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
  46. OAuthResponse response =
  47. OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  48. .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
  49. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  50. .buildJSONMessage();
  51. return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  52. }
  53. String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
  54. // 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
  55. if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
  56. if (!oAuthService.checkAuthCode(authCode)) {
  57. OAuthResponse response = OAuthASResponse
  58. .errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  59. .setError(OAuthError.TokenResponse.INVALID_GRANT)
  60. .setErrorDescription("错误的授权码")
  61. .buildJSONMessage();
  62. return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  63. }
  64. }
  65. //生成Access Token
  66. OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
  67. final String accessToken = oauthIssuerImpl.accessToken();
  68. oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
  69. //生成OAuth响应
  70. OAuthResponse response = OAuthASResponse
  71. .tokenResponse(HttpServletResponse.SC_OK)
  72. .setAccessToken(accessToken)
  73. .setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
  74. .buildJSONMessage();
  75. //根据OAuthResponse生成ResponseEntity
  76. return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  77. } catch (OAuthProblemException e) {
  78. //构建错误响应
  79. OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
  80. .buildJSONMessage();
  81. return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
  82. }
  83. }
  84. }

  1. package com.wlsq.oauth.controller;
  2. import java.net.URISyntaxException;
  3. import javax.annotation.Resource;
  4. import javax.security.auth.Subject;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. import org.apache.oltu.oauth2.as.issuer.MD5Generator;
  8. import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
  9. import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
  10. import org.apache.oltu.oauth2.as.response.OAuthASResponse;
  11. import org.apache.oltu.oauth2.common.OAuth;
  12. import org.apache.oltu.oauth2.common.error.OAuthError;
  13. import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
  14. import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
  15. import org.apache.oltu.oauth2.common.message.OAuthResponse;
  16. import org.apache.oltu.oauth2.common.message.types.ResponseType;
  17. import org.apache.oltu.oauth2.common.utils.OAuthUtils;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.http.HttpEntity;
  20. import org.springframework.http.HttpHeaders;
  21. import org.springframework.http.HttpStatus;
  22. import org.springframework.http.ResponseEntity;
  23. import org.springframework.stereotype.Controller;
  24. import org.springframework.ui.Model;
  25. import org.springframework.util.StringUtils;
  26. import org.springframework.web.bind.annotation.RequestMapping;
  27. import org.springframework.web.bind.annotation.RestController;
  28. import javax.servlet.http.HttpServletRequest;
  29. import javax.servlet.http.HttpServletResponse;
  30. import java.net.URI;
  31. import java.net.URISyntaxException;
  32. import com.wlsq.oauth.pojo.OauthUser;
  33. import com.wlsq.oauth.service.IOauthClientMapperService;
  34. import com.wlsq.oauth.service.IOauthUserMapperService;
  35. import com.wlsq.oauth.util.OauthUtil;
  36. @Controller
  37. public class AuthorizeController {
  38. @Autowired
  39. private OauthUtil oAuthService;
  40. @Resource
  41. private IOauthClientMapperService oauthClientService;
  42. @Autowired
  43. private IOauthUserMapperService userService;
  44. @RequestMapping("/authorize")
  45. public Object authorize(
  46. Model model,
  47. HttpServletRequest request)
  48. throws URISyntaxException, OAuthSystemException {
  49. try {
  50. //构建OAuth 授权请求
  51. OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
  52. //检查传入的客户端id是否正确
  53. if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
  54. OAuthResponse response =
  55. OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
  56. .setError(OAuthError.TokenResponse.INVALID_CLIENT)
  57. .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
  58. .buildJSONMessage();
  59. return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
  60. }
  61. //Subject subject = SecurityUtils.getSubject();
  62. //如果用户没有登录,跳转到登陆页面
  63. // if(!subject.isAuthenticated()) {
  64. if(!login(request)) {//登录失败时跳转到登陆页面
  65. model.addAttribute("client", oauthClientService.findByClientId(oauthRequest.getClientId()));
  66. return "oauth2login";
  67. }
  68. // }
  69. // String username = (String)subject.getPrincipal();
  70. String username =(String)request.getParameter("username");
  71. //生成授权码
  72. String authorizationCode = null;
  73. //responseType目前仅支持CODE,另外还有TOKEN
  74. String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
  75. if (responseType.equals(ResponseType.CODE.toString())) {
  76. OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
  77. authorizationCode = oauthIssuerImpl.authorizationCode();
  78. oAuthService.addAuthCode(authorizationCode, username);
  79. }
  80. //进行OAuth响应构建
  81. OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
  82. OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
  83. //设置授权码
  84. builder.setCode(authorizationCode);
  85. //得到到客户端重定向地址
  86. String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
  87. //构建响应
  88. final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
  89. //根据OAuthResponse返回ResponseEntity响应
  90. HttpHeaders headers = new HttpHeaders();
  91. headers.setLocation(new URI(response.getLocationUri()));
  92. return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
  93. } catch (OAuthProblemException e) {
  94. //出错处理
  95. String redirectUri = e.getRedirectUri();
  96. if (OAuthUtils.isEmpty(redirectUri)) {
  97. //告诉客户端没有传入redirectUri直接报错
  98. return new ResponseEntity("OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
  99. }
  100. //返回错误消息(如?error=)
  101. final OAuthResponse response =
  102. OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
  103. .error(e).location(redirectUri).buildQueryMessage();
  104. HttpHeaders headers = new HttpHeaders();
  105. headers.setLocation(new URI(response.getLocationUri()));
  106. return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
  107. }
  108. }
  109. //用户登入方法
  110. private boolean login(HttpServletRequest request) {
  111. if("get".equalsIgnoreCase(request.getMethod())) {
  112. return false;
  113. }
  114. String username = request.getParameter("username");
  115. String password = request.getParameter("password");
  116. if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
  117. return false;
  118. }
  119. OauthUser user=userService.findByUsername(username);
  120. // UsernamePasswordToken token = new UsernamePasswordToken(username, password);
  121. try {
  122. if(user != null){
  123. return true;
  124. }
  125. return false;
  126. } catch (Exception e) {
  127. request.setAttribute("error", "登录失败:" + e.getClass().getName());
  128. return false;
  129. }
  130. }
  131. }


  1. package com.wlsq.oauth.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  9. import com.wlsq.oauth.pojo.OauthClient;
  10. import com.wlsq.oauth.service.IOauthClientMapperService;
  11. @Controller
  12. @RequestMapping("/client")
  13. public class ClientController {
  14. @Autowired
  15. private IOauthClientMapperService clientService;
  16. @RequestMapping(method = RequestMethod.GET)
  17. public String list(Model model) {
  18. model.addAttribute("clientList", clientService.findAll());
  19. return "client/list";
  20. }
  21. @RequestMapping(value = "/create", method = RequestMethod.GET)
  22. public String showCreateForm(Model model) {
  23. model.addAttribute("client", new OauthClient());
  24. model.addAttribute("op", "新增");
  25. return "client/edit";
  26. }
  27. @RequestMapping(value = "/create", method = RequestMethod.POST)
  28. public String create(OauthClient client, RedirectAttributes redirectAttributes) {
  29. clientService.createClient(client);
  30. redirectAttributes.addFlashAttribute("msg", "新增成功");
  31. return "redirect:/client";
  32. }
  33. @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
  34. public String showUpdateForm(@PathVariable("id") Long id, Model model) {
  35. model.addAttribute("client", clientService.findOne(id));
  36. model.addAttribute("op", "修改");
  37. return "client/edit";
  38. }
  39. @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
  40. public String update(OauthClient client, RedirectAttributes redirectAttributes) {
  41. clientService.updateClient(client);
  42. redirectAttributes.addFlashAttribute("msg", "修改成功");
  43. return "redirect:/client";
  44. }
  45. @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
  46. public String showDeleteForm(@PathVariable("id") Long id, Model model) {
  47. model.addAttribute("client", clientService.findOne(id));
  48. model.addAttribute("op", "删除");
  49. return "client/edit";
  50. }
  51. @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
  52. public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
  53. clientService.deleteClient(id);
  54. redirectAttributes.addFlashAttribute("msg", "删除成功");
  55. return "redirect:/client";
  56. }
  57. }


  1. package com.wlsq.oauth.controller;
  2. public class Constants {
  3. public static String RESOURCE_SERVER_NAME = "chapter17-server";
  4. public static final String INVALID_CLIENT_DESCRIPTION = "客户端验证失败,如错误的client_id/client_secret。";
  5. }


  1. package com.wlsq.oauth.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. public class IndexController {
  7. @RequestMapping("/")
  8. public String index(Model model) {
  9. return "index";
  10. }
  11. }


  1. package com.wlsq.oauth.controller;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. @Controller
  7. public class LoginController {
  8. @RequestMapping(value = "/login")
  9. public String showLoginForm(HttpServletRequest req, Model model) {
  10. String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
  11. String error = null;
  12. // if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
  13. // error = "用户名/密码错误";
  14. // } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
  15. // error = "用户名/密码错误";
  16. // } else
  17. if(exceptionClassName != null) {
  18. error = "其他错误:" + exceptionClassName;
  19. }
  20. model.addAttribute("error", error);
  21. return "login";
  22. }
  23. }

  1. package com.wlsq.oauth.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  9. import com.wlsq.oauth.pojo.OauthUser;
  10. import com.wlsq.oauth.service.IOauthUserMapperService;
  11. @Controller
  12. @RequestMapping("/user")
  13. public class UserController {
  14. @Autowired
  15. private IOauthUserMapperService userService;
  16. @RequestMapping(method = RequestMethod.GET)
  17. public String list(Model model) {
  18. model.addAttribute("userList", userService.findAll());
  19. return "user/list";
  20. }
  21. @RequestMapping(value = "/create", method = RequestMethod.GET)
  22. public String showCreateForm(Model model) {
  23. model.addAttribute("user", new OauthUser());
  24. model.addAttribute("op", "新增");
  25. return "user/edit";
  26. }
  27. @RequestMapping(value = "/create", method = RequestMethod.POST)
  28. public String create(OauthUser user, RedirectAttributes redirectAttributes) {
  29. userService.createUser(user);
  30. redirectAttributes.addFlashAttribute("msg", "新增成功");
  31. return "redirect:/user";
  32. }
  33. @RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
  34. public String showUpdateForm(@PathVariable("id") Long id, Model model) {
  35. model.addAttribute("user", userService.findOne(id));
  36. model.addAttribute("op", "修改");
  37. return "user/edit";
  38. }
  39. @RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
  40. public String update(OauthUser user, RedirectAttributes redirectAttributes) {
  41. userService.updateUser(user);
  42. redirectAttributes.addFlashAttribute("msg", "修改成功");
  43. return "redirect:/user";
  44. }
  45. @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
  46. public String showDeleteForm(@PathVariable("id") Long id, Model model) {
  47. model.addAttribute("user", userService.findOne(id));
  48. model.addAttribute("op", "删除");
  49. return "user/edit";
  50. }
  51. @RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
  52. public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
  53. userService.deleteUser(id);
  54. redirectAttributes.addFlashAttribute("msg", "删除成功");
  55. return "redirect:/user";
  56. }
  57. @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
  58. public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
  59. model.addAttribute("user", userService.findOne(id));
  60. model.addAttribute("op", "修改密码");
  61. return "user/changePassword";
  62. }
  63. @RequestMapping(value = "/{id}/changePassword", method = RequestMethod.POST)
  64. public String changePassword(@PathVariable("id") Long id, String newPassword, RedirectAttributes redirectAttributes) {
  65. userService.changePassword(id, newPassword);
  66. redirectAttributes.addFlashAttribute("msg", "修改密码成功");
  67. return "redirect:/user";
  68. }
  69. }


  1. package com.wlsq.oauth.controller;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.oltu.oauth2.common.OAuth;
  5. import org.apache.oltu.oauth2.common.error.OAuthError;
  6. import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
  7. import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
  8. import org.apache.oltu.oauth2.common.message.OAuthResponse;
  9. import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
  10. import org.apache.oltu.oauth2.common.utils.OAuthUtils;
  11. import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
  12. import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.http.HttpEntity;
  15. import org.springframework.http.HttpHeaders;
  16. import org.springframework.http.HttpStatus;
  17. import org.springframework.http.ResponseEntity;
  18. import org.springframework.web.bind.annotation.RequestMapping;
  19. import org.springframework.web.bind.annotation.RestController;
  20. import com.wlsq.oauth.util.OauthUtil;
  21. @RestController
  22. public class UserInfoController {
  23. @Autowired
  24. private OauthUtil oAuthService;
  25. @RequestMapping("/userInfo")
  26. public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
  27. try {
  28. //构建OAuth资源请求
  29. OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
  30. //获取Access Token
  31. String accessToken = oauthRequest.getAccessToken();
  32. //验证Access Token
  33. if (!oAuthService.checkAccessToken(accessToken)) {
  34. // 如果不存在/过期了,返回未验证错误,需重新验证
  35. OAuthResponse oauthResponse = OAuthRSResponse
  36. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  37. .setRealm(Constants.RESOURCE_SERVER_NAME)
  38. .setError(OAuthError.ResourceResponse.INVALID_TOKEN)
  39. .buildHeaderMessage();
  40. HttpHeaders headers = new HttpHeaders();
  41. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  42. return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
  43. }
  44. //返回用户名
  45. String username = oAuthService.getUsernameByAccessToken(accessToken);
  46. return new ResponseEntity(username, HttpStatus.OK);
  47. } catch (OAuthProblemException e) {
  48. //检查是否设置了错误码
  49. String errorCode = e.getError();
  50. if (OAuthUtils.isEmpty(errorCode)) {
  51. OAuthResponse oauthResponse = OAuthRSResponse
  52. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  53. .setRealm(Constants.RESOURCE_SERVER_NAME)
  54. .buildHeaderMessage();
  55. HttpHeaders headers = new HttpHeaders();
  56. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  57. return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
  58. }
  59. OAuthResponse oauthResponse = OAuthRSResponse
  60. .errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
  61. .setRealm(Constants.RESOURCE_SERVER_NAME)
  62. .setError(e.getError())
  63. .setErrorDescription(e.getDescription())
  64. .setErrorUri(e.getUri())
  65. .buildHeaderMessage();
  66. HttpHeaders headers = new HttpHeaders();
  67. headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
  68. return new ResponseEntity(HttpStatus.BAD_REQUEST);
  69. }
  70. }
  71. }


相关项目待补充上传

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/319720
推荐阅读
相关标签
  

闽ICP备14008679号