SpringMVC +Spring+ SpringJDBC 整合 教程
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC +Spring+ SpringJDBC 整合 教程相关的知识,希望对你有一定的参考价值。
项目文件结构,如下截图:
第一步:整合web.xml 文件,主要实现SpringMVC监听器(DispatchServlet)、编码过滤器、Spring监听器和内存监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<!-- Spring和mybatis的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 防止Spring内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- Spring MVC servlet -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
第二步:spring-mvc.xml 和spring-mybatis.xml 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<context:annotation-config />
<!-- 扫描所有的controller 但是不扫描service-->
<!--
<context:component-scan base-package="com.wlsq.oauth">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan> -->
<!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
<context:component-scan base-package="com.wlsq.oauth.controller" />
<context:component-scan base-package="com.wlsq.oauth.service" />
<context:component-scan base-package="com.wlsq.oauth.dao" />
<!-- 声明DispatcherServlet不要拦截下面声明的目录 -->
<!-- <mvc:resources location="/js/" mapping="/js/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/css/" mapping="/css/**" />
<mvc:resources location="/common/" mapping="/common/**" /> -->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>
<!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->
<!-- <context:component-scan base-package="com.cn.hnust.controller" />-->
<!--避免IE执行AJAX时,返回JSON出现下载文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->
</list>
</property>
</bean>
<!-- 定义跳转的文件的前后缀 ,视图模式配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->
<!--<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" /> -->
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="contentType" value="text/html"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 默认编码 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 文件大小最大值 -->
<property name="maxUploadSize" value="10485760000" />
<!-- 内存中的最大值 -->
<property name="maxInMemorySize" value="40960" />
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 引入配置文件 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:memcache.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${url}" />
<property name="username" value="${username}" />
<property name="password" value="${password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1" />
<property name="minIdle" value="1" />
<property name="maxActive" value="20" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="20" />
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat" />
</bean>
<!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
<bean id="dataSourceProxy" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<property name="targetDataSource" ref="dataSource"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSourceProxy"/>
</bean>
<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSourceProxy" />
</bean>
<!-- 通知 -->
<tx:advice id="tx" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pc"
expression="execution(* com.wlsq.oauth.service.*.*(..))" />
<!--把事务控制在Service层 -->
<aop:advisor pointcut-ref="pc" advice-ref="tx" />
</aop:config>
<!--spring 集成缓存服务器(memcached) -->
<bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
factory-method="getInstance" init-method="initialize"
destroy-method="shutDown">
<constructor-arg>
<value>memCachedPool</value>
</constructor-arg>
<property name="servers">
<list>
<value>${memcache.server}</value>
</list>
</property>
<property name="initConn">
<value>${memcache.initConn}</value>
</property>
<property name="minConn">
<value>${memcache.minConn}</value>
</property>
<property name="maxConn">
<value>${memcache.maxConn}</value>
</property>
<property name="maintSleep">
<value>${memcache.maintSleep}</value>
</property>
<property name="nagle">
<value>${memcache.nagle}</value>
</property>
<property name="socketTO">
<value>${memcache.socketTO}</value>
</property>
</bean>
<bean id="memCachedClient" class="com.danga.MemCached.MemCachedClient">
<constructor-arg>
<value>memCachedPool</value>
</constructor-arg>
</bean>
<!--自定义bean -->
<bean id="oAuthService" class="com.wlsq.oauth.util.OauthUtil">
<property name="memCachedClient">
<ref bean="memCachedClient"/>
</property>
</bean>
</beans>
3、实体类(OauthClient和OauthUser)
package com.wlsq.oauth.pojo;
public class OauthClient implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String clientName;
private String clientId;
private String clientScerct;
public OauthClient() {
}
public OauthClient(Long id, String clientName, String clientId,
String clientScerct) {
super();
this.id = id;
this.clientName = clientName;
this.clientId = clientId;
this.clientScerct = clientScerct;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientScerct() {
return clientScerct;
}
public void setClientScerct(String clientScerct) {
this.clientScerct = clientScerct;
}
}
package com.wlsq.oauth.pojo;
public class OauthUser implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String password;
private String salt;
public OauthUser() {
}
public OauthUser(Long id, String username, String password, String salt) {
super();
this.id = id;
this.username = username;
this.password = password;
this.salt = salt;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
4、dao层和dao层 实现
package com.wlsq.oauth.dao;
import java.util.List;
import com.wlsq.oauth.pojo.OauthClient;
public interface OauthClientMapper {
public OauthClient createClient(OauthClient client);// 创建客户端
public OauthClient updateClient(OauthClient client);// 更新客户端
public void deleteClient(Long clientId);// 删除客户端
OauthClient findOne(Long clientId);// 根据id查找客户端
List<OauthClient> findAll();// 查找所有
OauthClient findByClientId(String clientId);// 根据客户端id查找客户端
OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
}
package com.wlsq.oauth.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import com.wlsq.oauth.pojo.OauthClient;
@Repository
public class OauthClientMapperImpl implements OauthClientMapper {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public OauthClient createClient(final OauthClient client) {
// TODO Auto-generated method stub
final String sql = "insert into oauth2_client(client_name, client_id, client_secret) values(?,?,?)";
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
int count = 1;
psst.setString(count++, client.getClientName());
psst.setString(count++, client.getClientId());
psst.setString(count++, client.getClientScerct());
return psst;
}
}, keyHolder);
client.setId(keyHolder.getKey().longValue());
return client;
}
@Override
public OauthClient updateClient(OauthClient client) {
// TODO Auto-generated method stub
String sql = "update oauth2_client set client_name=?, client_id=?, client_secret=? where id=?";
jdbcTemplate.update(
sql,
client.getClientName(), client.getClientId(), client.getClientScerct(), client.getId());
return client;
}
@Override
public void deleteClient(Long clientId) {
// TODO Auto-generated method stub
String sql = "delete from oauth2_client where id=?";
jdbcTemplate.update(sql, clientId);
}
@Override
public OauthClient findOne(Long clientId) {
// TODO Auto-generated method stub
String sql = "select id, client_name, client_id, client_secret from oauth2_client where id=?";
List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
if(clientList.size() == 0) {
return null;
}
return clientList.get(0);
}
@Override
public List<OauthClient> findAll() {
// TODO Auto-generated method stub
String sql = "select id, client_name, client_id, client_secret from oauth2_client";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class));
}
@Override
public OauthClient findByClientId(String clientId) {
// TODO Auto-generated method stub
String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_id=?";
List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientId);
if(clientList.size() == 0) {
return null;
}
return clientList.get(0);
}
@Override
public OauthClient findByClientSecret(String clientSecret) {
// TODO Auto-generated method stub
String sql = "select id, client_name, client_id, client_secret from oauth2_client where client_secret=?";
List<OauthClient> clientList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthClient.class), clientSecret);
if(clientList.size() == 0) {
return null;
}
return clientList.get(0);
}
}
package com.wlsq.oauth.dao;
import java.util.List;
import com.wlsq.oauth.pojo.OauthUser;
public interface OauthUserMapper {
public OauthUser createUser(OauthUser user);// 创建用户
public OauthUser updateUser(OauthUser user);// 更新用户
public void deleteUser(Long userId);// 删除用户
public void changePassword(Long userId, String newPassword); //修改密码
OauthUser findOne(Long userId);// 根据id查找用户
List<OauthUser> findAll();// 得到所有用户
public OauthUser findByUsername(String username);// 根据用户名查找用户
}
package com.wlsq.oauth.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import com.wlsq.oauth.pojo.OauthUser;
@Repository
public class OauthUserMapperImpl implements OauthUserMapper {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public OauthUser createUser(final OauthUser user) {
final String sql = "insert into oauth2_user(username, password, salt) values(?,?,?)";
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
int count = 1;
psst.setString(count++, user.getUsername());
psst.setString(count++, user.getPassword());
psst.setString(count++, user.getSalt());
return psst;
}
}, keyHolder);
user.setId(keyHolder.getKey().longValue());
return user;
}
@Override
public OauthUser updateUser(OauthUser user) {
// TODO Auto-generated method stub
String sql = "update oauth2_user set username=?, password=?, salt=? where id=?";
jdbcTemplate.update(
sql,
user.getUsername(), user.getPassword(), user.getSalt(), user.getId());
return user;
}
@Override
public void deleteUser(Long userId) {
// TODO Auto-generated method stub
String sql = "delete from oauth2_user where id=?";
jdbcTemplate.update(sql, userId);
}
@Override
public void changePassword(Long userId, String newPassword) {
// TODO Auto-generated method stub
}
@Override
public OauthUser findOne(Long userId) {
// TODO Auto-generated method stub
String sql = "select id, username, password, salt from oauth2_user where id=?";
List<OauthUser> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), userId);
if(userList.size() == 0) {
return null;
}
return userList.get(0);
}
@Override
public List<OauthUser> findAll() {
// TODO Auto-generated method stub
String sql = "select id, username, password, salt from oauth2_user";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class));
}
@Override
public OauthUser findByUsername(String username) {
// TODO Auto-generated method stub
String sql = "select id, username, password, salt from oauth2_user where username=?";
List<OauthUser> userList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(OauthUser.class), username);
if(userList.size() == 0) {
return null;
}
return userList.get(0);
}
}
3、service层和service层实现
package com.wlsq.oauth.service;
import java.util.List;
import com.wlsq.oauth.pojo.OauthClient;
public interface IOauthClientMapperService {
public OauthClient createClient(OauthClient client);// 创建客户端
public OauthClient updateClient(OauthClient client);// 更新客户端
public void deleteClient(Long clientId);// 删除客户端
OauthClient findOne(Long clientId);// 根据id查找客户端
List<OauthClient> findAll();// 查找所有
OauthClient findByClientId(String clientId);// 根据客户端id查找客户端
OauthClient findByClientSecret(String clientSecret);// 根据客户端安全KEY查找客户端
}
package com.wlsq.oauth.service.impl;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wlsq.oauth.dao.OauthClientMapper;
import com.wlsq.oauth.pojo.OauthClient;
import com.wlsq.oauth.service.IOauthClientMapperService;
@Transactional
@Service("oauthClientService")
public class OauthClientServiceImpl implements IOauthClientMapperService {
@Autowired
private OauthClientMapper clientDao;
@Override
public OauthClient createClient(OauthClient client) {
// TODO Auto-generated method stub
client.setClientId(UUID.randomUUID().toString());
client.setClientScerct(UUID.randomUUID().toString());
return clientDao.createClient(client);
}
@Override
public OauthClient updateClient(OauthClient client) {
// TODO Auto-generated method stub
return clientDao.updateClient(client);
}
@Override
public void deleteClient(Long clientId) {
// TODO Auto-generated method stub
clientDao.deleteClient(clientId);
}
@Override
public OauthClient findOne(Long clientId) {
// TODO Auto-generated method stub
return clientDao.findOne(clientId);
}
@Override
public List<OauthClient> findAll() {
// TODO Auto-generated method stub
return clientDao.findAll();
}
@Override
public OauthClient findByClientId(String clientId) {
// TODO Auto-generated method stub
return clientDao.findByClientId(clientId);
}
@Override
public OauthClient findByClientSecret(String clientSecret) {
// TODO Auto-generated method stub
return clientDao.findByClientSecret(clientSecret);
}
}
package com.wlsq.oauth.service;
import java.util.List;
import com.wlsq.oauth.pojo.OauthUser;
public interface IOauthUserMapperService {
public OauthUser createUser(OauthUser user);// 创建用户
public OauthUser updateUser(OauthUser user);// 更新用户
public void deleteUser(Long userId);// 删除用户
public void changePassword(Long userId, String newPassword); //修改密码
OauthUser findOne(Long userId);// 根据id查找用户
List<OauthUser> findAll();// 得到所有用户
public OauthUser findByUsername(String username);// 根据用户名查找用户
}
package com.wlsq.oauth.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.wlsq.oauth.dao.OauthUserMapper;
import com.wlsq.oauth.pojo.OauthUser;
import com.wlsq.oauth.service.IOauthUserMapperService;
@Transactional
@Service("oauthUserService")
public class OauthUserServiceImpl implements IOauthUserMapperService {
@Autowired
private OauthUserMapper oauthUserMapper;
@Override
public OauthUser createUser(OauthUser user) {
// TODO Auto-generated method stub
return this.oauthUserMapper.createUser(user);
}
@Override
public OauthUser updateUser(OauthUser user) {
// TODO Auto-generated method stub
return this.oauthUserMapper.updateUser(user);
}
@Override
public void deleteUser(Long userId) {
// TODO Auto-generated method stub
this.oauthUserMapper.deleteUser(userId);
}
@Override
public void changePassword(Long userId, String newPassword) {
// TODO Auto-generated method stub
this.oauthUserMapper.changePassword(userId, newPassword);
}
@Override
public OauthUser findOne(Long userId) {
// TODO Auto-generated method stub
return this.oauthUserMapper.findOne(userId);
}
@Override
public List<OauthUser> findAll() {
// TODO Auto-generated method stub
return this.oauthUserMapper.findAll();
}
@Override
public OauthUser findByUsername(String username) {
// TODO Auto-generated method stub
return this.oauthUserMapper.findByUsername(username);
}
}
4、controller层
package com.wlsq.oauth.controller;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wlsq.oauth.util.OauthUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URISyntaxException;
@RestController
public class AccessTokenController {
@Autowired
private OauthUtil oAuthService;
//@Autowired
//private IOauthUserMapperService userService;
@RequestMapping("/accessToken")
public HttpEntity token(HttpServletRequest request)
throws URISyntaxException, OAuthSystemException {
try {
//构建OAuth请求
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
//检查提交的客户端id是否正确
if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
OAuthResponse response =
OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
// 检查客户端安全KEY是否正确
if (!oAuthService.checkClientSecret(oauthRequest.getClientSecret())) {
OAuthResponse response =
OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
String authCode = oauthRequest.getParam(OAuth.OAUTH_CODE);
// 检查验证类型,此处只检查AUTHORIZATION_CODE类型,其他的还有PASSWORD或REFRESH_TOKEN
if (oauthRequest.getParam(OAuth.OAUTH_GRANT_TYPE).equals(GrantType.AUTHORIZATION_CODE.toString())) {
if (!oAuthService.checkAuthCode(authCode)) {
OAuthResponse response = OAuthASResponse
.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_GRANT)
.setErrorDescription("错误的授权码")
.buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
}
//生成Access Token
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
final String accessToken = oauthIssuerImpl.accessToken();
oAuthService.addAccessToken(accessToken, oAuthService.getUsernameByAuthCode(authCode));
//生成OAuth响应
OAuthResponse response = OAuthASResponse
.tokenResponse(HttpServletResponse.SC_OK)
.setAccessToken(accessToken)
.setExpiresIn(String.valueOf(oAuthService.getExpireIn()))
.buildJSONMessage();
//根据OAuthResponse生成ResponseEntity
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
//构建错误响应
OAuthResponse res = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e)
.buildJSONMessage();
return new ResponseEntity(res.getBody(), HttpStatus.valueOf(res.getResponseStatus()));
}
}
}
package com.wlsq.oauth.controller;
import java.net.URISyntaxException;
import javax.annotation.Resource;
import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthAuthzRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ResponseType;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URI;
import java.net.URISyntaxException;
import com.wlsq.oauth.pojo.OauthUser;
import com.wlsq.oauth.service.IOauthClientMapperService;
import com.wlsq.oauth.service.IOauthUserMapperService;
import com.wlsq.oauth.util.OauthUtil;
@Controller
public class AuthorizeController {
@Autowired
private OauthUtil oAuthService;
@Resource
private IOauthClientMapperService oauthClientService;
@Autowired
private IOauthUserMapperService userService;
@RequestMapping("/authorize")
public Object authorize(
Model model,
HttpServletRequest request)
throws URISyntaxException, OAuthSystemException {
try {
//构建OAuth 授权请求
OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
//检查传入的客户端id是否正确
if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
OAuthResponse response =
OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
.setError(OAuthError.TokenResponse.INVALID_CLIENT)
.setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION)
.buildJSONMessage();
return new ResponseEntity(response.getBody(), HttpStatus.valueOf(response.getResponseStatus()));
}
//Subject subject = SecurityUtils.getSubject();
//如果用户没有登录,跳转到登陆页面
// if(!subject.isAuthenticated()) {
if(!login(request)) {//登录失败时跳转到登陆页面
model.addAttribute("client", oauthClientService.findByClientId(oauthRequest.getClientId()));
return "oauth2login";
}
// }
// String username = (String)subject.getPrincipal();
String username =(String)request.getParameter("username");
//生成授权码
String authorizationCode = null;
//responseType目前仅支持CODE,另外还有TOKEN
String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
if (responseType.equals(ResponseType.CODE.toString())) {
OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
authorizationCode = oauthIssuerImpl.authorizationCode();
oAuthService.addAuthCode(authorizationCode, username);
}
//进行OAuth响应构建
OAuthASResponse.OAuthAuthorizationResponseBuilder builder =
OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);
//设置授权码
builder.setCode(authorizationCode);
//得到到客户端重定向地址
String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);
//构建响应
final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();
//根据OAuthResponse返回ResponseEntity响应
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(response.getLocationUri()));
return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
} catch (OAuthProblemException e) {
//出错处理
String redirectUri = e.getRedirectUri();
if (OAuthUtils.isEmpty(redirectUri)) {
//告诉客户端没有传入redirectUri直接报错
return new ResponseEntity("OAuth callback url needs to be provided by client!!!", HttpStatus.NOT_FOUND);
}
//返回错误消息(如?error=)
final OAuthResponse response =
OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
.error(e).location(redirectUri).buildQueryMessage();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI(response.getLocationUri()));
return new ResponseEntity(headers, HttpStatus.valueOf(response.getResponseStatus()));
}
}
//用户登入方法
private boolean login(HttpServletRequest request) {
if("get".equalsIgnoreCase(request.getMethod())) {
return false;
}
String username = request.getParameter("username");
String password = request.getParameter("password");
if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
return false;
}
OauthUser user=userService.findByUsername(username);
// UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
if(user != null){
return true;
}
return false;
} catch (Exception e) {
request.setAttribute("error", "登录失败:" + e.getClass().getName());
return false;
}
}
}
package com.wlsq.oauth.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.wlsq.oauth.pojo.OauthClient;
import com.wlsq.oauth.service.IOauthClientMapperService;
@Controller
@RequestMapping("/client")
public class ClientController {
@Autowired
private IOauthClientMapperService clientService;
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("clientList", clientService.findAll());
return "client/list";
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String showCreateForm(Model model) {
model.addAttribute("client", new OauthClient());
model.addAttribute("op", "新增");
return "client/edit";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(OauthClient client, RedirectAttributes redirectAttributes) {
clientService.createClient(client);
redirectAttributes.addFlashAttribute("msg", "新增成功");
return "redirect:/client";
}
@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
public String showUpdateForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("client", clientService.findOne(id));
model.addAttribute("op", "修改");
return "client/edit";
}
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(OauthClient client, RedirectAttributes redirectAttributes) {
clientService.updateClient(client);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/client";
}
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String showDeleteForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("client", clientService.findOne(id));
model.addAttribute("op", "删除");
return "client/edit";
}
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
clientService.deleteClient(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/client";
}
}
package com.wlsq.oauth.controller;
public class Constants {
public static String RESOURCE_SERVER_NAME = "chapter17-server";
public static final String INVALID_CLIENT_DESCRIPTION = "客户端验证失败,如错误的client_id/client_secret。";
}
package com.wlsq.oauth.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
public String index(Model model) {
return "index";
}
}
package com.wlsq.oauth.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping(value = "/login")
public String showLoginForm(HttpServletRequest req, Model model) {
String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
String error = null;
// if(UnknownAccountException.class.getName().equals(exceptionClassName)) {
// error = "用户名/密码错误";
// } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
// error = "用户名/密码错误";
// } else
if(exceptionClassName != null) {
error = "其他错误:" + exceptionClassName;
}
model.addAttribute("error", error);
return "login";
}
}
package com.wlsq.oauth.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.wlsq.oauth.pojo.OauthUser;
import com.wlsq.oauth.service.IOauthUserMapperService;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IOauthUserMapperService userService;
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("userList", userService.findAll());
return "user/list";
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String showCreateForm(Model model) {
model.addAttribute("user", new OauthUser());
model.addAttribute("op", "新增");
return "user/edit";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(OauthUser user, RedirectAttributes redirectAttributes) {
userService.createUser(user);
redirectAttributes.addFlashAttribute("msg", "新增成功");
return "redirect:/user";
}
@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
public String showUpdateForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "修改");
return "user/edit";
}
@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
public String update(OauthUser user, RedirectAttributes redirectAttributes) {
userService.updateUser(user);
redirectAttributes.addFlashAttribute("msg", "修改成功");
return "redirect:/user";
}
@RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
public String showDeleteForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "删除");
return "user/edit";
}
@RequestMapping(value = "/{id}/delete", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
userService.deleteUser(id);
redirectAttributes.addFlashAttribute("msg", "删除成功");
return "redirect:/user";
}
@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.GET)
public String showChangePasswordForm(@PathVariable("id") Long id, Model model) {
model.addAttribute("user", userService.findOne(id));
model.addAttribute("op", "修改密码");
return "user/changePassword";
}
@RequestMapping(value = "/{id}/changePassword", method = RequestMethod.POST)
public String changePassword(@PathVariable("id") Long id, String newPassword, RedirectAttributes redirectAttributes) {
userService.changePassword(id, newPassword);
redirectAttributes.addFlashAttribute("msg", "修改密码成功");
return "redirect:/user";
}
}
package com.wlsq.oauth.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.ParameterStyle;
import org.apache.oltu.oauth2.common.utils.OAuthUtils;
import org.apache.oltu.oauth2.rs.request.OAuthAccessResourceRequest;
import org.apache.oltu.oauth2.rs.response.OAuthRSResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wlsq.oauth.util.OauthUtil;
@RestController
public class UserInfoController {
@Autowired
private OauthUtil oAuthService;
@RequestMapping("/userInfo")
public HttpEntity userInfo(HttpServletRequest request) throws OAuthSystemException {
try {
//构建OAuth资源请求
OAuthAccessResourceRequest oauthRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);
//获取Access Token
String accessToken = oauthRequest.getAccessToken();
//验证Access Token
if (!oAuthService.checkAccessToken(accessToken)) {
// 如果不存在/过期了,返回未验证错误,需重新验证
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(Constants.RESOURCE_SERVER_NAME)
.setError(OAuthError.ResourceResponse.INVALID_TOKEN)
.buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
}
//返回用户名
String username = oAuthService.getUsernameByAccessToken(accessToken);
return new ResponseEntity(username, HttpStatus.OK);
} catch (OAuthProblemException e) {
//检查是否设置了错误码
String errorCode = e.getError();
if (OAuthUtils.isEmpty(errorCode)) {
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(Constants.RESOURCE_SERVER_NAME)
.buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(headers, HttpStatus.UNAUTHORIZED);
}
OAuthResponse oauthResponse = OAuthRSResponse
.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setRealm(Constants.RESOURCE_SERVER_NAME)
.setError(e.getError())
.setErrorDescription(e.getDescription())
.setErrorUri(e.getUri())
.buildHeaderMessage();
HttpHeaders headers = new HttpHeaders();
headers.add(OAuth.HeaderType.WWW_AUTHENTICATE, oauthResponse.getHeader(OAuth.HeaderType.WWW_AUTHENTICATE));
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
相关项目待补充上传
以上是关于SpringMVC +Spring+ SpringJDBC 整合 教程的主要内容,如果未能解决你的问题,请参考以下文章
Spring+SpringMVC+MybatisSpring+SpringMVC+Mybatis实现前端到后台完整项目
spring 和 springmvc spring boot优点及区别