Struts2.3.7+Spring3.0.0+Hibernate4.0.0 整合(四)Spring 升级到 3.1.0

10 篇文章 0 订阅
10 篇文章 0 订阅

在之前的文章《Struts2.x+Spring3.x+Hibernate4.x 整合》(一)、(二)、(三)中,由于Spring3.0与Hibernate4.0存在兼容性问题(主要是Spring3.0在配置时遇到 问题),最后决定升级Spring至3.1。在前一篇 的基础上进行如下操作:

1、更新Spring jar包,并新添加如下两个jar包:

aopalliance-1.0.jar

aspectjweaver.jar


2、修改web.xml配置文件,最终结果如下:

<?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> 
    <filter> 
        <filter-name>struts2</filter-name> 
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 
    </filter> 
    <filter-mapping> 
        <filter-name>struts2</filter-name> 
        <url-pattern>/*</url-pattern> 
    </filter-mapping> 
          
    <listener> 
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 
          
    <filter> 
        <filter-name>hibernateFilter</filter-name> 
    <filter-mapping> 
        <filter-name>hibernateFilter</filter-name> 
        <url-pattern>/*</url-pattern> 
    </filter-mapping> 
</web-app>

3、修改applicationContext.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="      
          http://www.springframework.org/schema/beans       
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
          http://www.springframework.org/schema/aop       
          http://www.springframework.org/schema/aop/spring-aop-3.0.xsd      
          http://www.springframework.org/schema/tx       
          http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 
         
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /> 
        <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" /> 
        <property name="username" value="bwcui" /> 
        <property name="password" value="bwcui" /> 
    </bean> 
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
        <property name="dataSource" ref="dataSource" /> 
        <property name="mappingResources"> 
            <list> 
                <value>com/manage/department/model/Department.hbm.xml</value> 
            </list> 
        </property> 
        <property name="hibernateProperties"> 
            <value> 
                hibernate.dialect=org.hibernate.dialect.Oracle10gDialect 
                hibernate.show_sql=true 
                hibernate.format_sql=true 
            </value> 
        </property> 
    </bean> 
         
    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
        <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 
         
    <!-- 这是事务通知操作,使用的事务管理器引用自 transactionManager -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
        <tx:attributes> 
            <!-- 指定哪些方法需要加入事务,可以使用通配符来只加入需要的方法 -->
            <tx:method name="get*" propagation="NOT_SUPPORTED"
                read-only="true" /> 
            <tx:method name="*" propagation="REQUIRED" /> 
        </tx:attributes> 
    </tx:advice> 
    <!-- 需要引入aop的命名空间 -->
    <aop:config> 
        <!-- 切入点指明了在执行Service的所有方法时产生事务拦截操作 -->
        <aop:pointcut id="daoMethods"
            expression="execution(* com.manage.department.dao.impl.*.*(..))" /> 
        <!-- 定义了将采用何种拦截操作,这里引用到 txAdvice -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="daoMethods" /> 
    </aop:config> 
         
    <bean id="departmentDao" class="com.manage.department.dao.impl.DepartmentDaoImpl"
        scope="singleton"> 
        <property name="sessionFactory" ref="sessionFactory"></property> 
    </bean> 
    <bean id="departmentService"
        class="com.manage.department.service.impl.DepartmentServiceImpl"> 
        <property name="departmentDao" ref="departmentDao"></property> 
    </bean> 
    <bean id="departmentAction" class="com.manage.department.action.DepartmentAction"> 
        <property name="departmentService" ref="departmentService"></property> 
    </bean> 
         
    <bean id="enterService" class="com.manage.enter.service.impl.EnterServiceImpl"> 
    </bean> 
    <bean id="enterAction" class="com.manage.enter.action.EnterAction"> 
        <property name="service" ref="enterService"></property> 
    </bean> 
</beans>

4、Hibernate中的配置删除,内容如下:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE hibernate-configuration PUBLIC 
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
    <session-factory> 
    </session-factory> 
</hibernate-configuration>

5、修改DAO类,内容如下

package com.manage.department.dao.impl; 
       
import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.Transaction; 
       
import com.manage.department.dao.DepartmentDao; 
import com.manage.department.model.Department; 
       
public class DepartmentDaoImpl implements DepartmentDao { 
       
    private SessionFactory sessionFactory; 
       
    public SessionFactory getSessionFactory() { 
        return sessionFactory; 
    } 
       
    public void setSessionFactory(SessionFactory sessionFactory) { 
        this.sessionFactory = sessionFactory; 
    } 
       
    public Session getSession() { 
        return this.sessionFactory.getCurrentSession(); 
    } 
       
    public Department readByCode(String code) { 
//      Transaction transaction = this.sessionFactory.getCurrentSession() 
//              .beginTransaction(); 
//      Department dept = (Department) this.sessionFactory.getCurrentSession() 
//              .get(Department.class, code); 
//      transaction.commit(); 
//      return dept; 
               
        return (Department) this.getSession().get(Department.class, code); 
    } 
}

6、测试访问

最后测试访问配置后的结果。


这里附上最终源码:http://download.csdn.net/detail/xz2001/4853949




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是Spring Boot集成Spring Security、JWT和OAuth2的示例代码: 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.7.RELEASE</version> </dependency> <!-- JWT --> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 配置Spring Security 在Spring Boot应用程序中,可以通过配置类来配置Spring Security。创建一个配置类,命名为SecurityConfig.java,并添加以下内容: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private PasswordEncoder passwordEncoder; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests().antMatchers("/oauth/**").permitAll() .anyRequest().authenticated() .and().formLogin().permitAll(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ``` 这个类配置了Spring Security,启用了Web安全性,并定义了一个UserDetailsService实例,该实例将用于验证用户。 3. 配置OAuth2 创建一个OAuth2配置类,命名为OAuth2Config.java,并添加以下内容: ```java @Configuration @EnableAuthorizationServer public class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Autowired private PasswordEncoder passwordEncoder; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .userDetailsService(userDetailsService) .accessTokenConverter(accessTokenConverter()); } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource); } @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("secret"); return converter; } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Bean public ClientDetailsService clientDetailsService() { return new JdbcClientDetailsService(dataSource); } @Bean public ApprovalStore approvalStore() { return new JdbcApprovalStore(dataSource); } } ``` 这个类配置了OAuth2服务端,启用了授权服务器,并定义了一个客户端详情服务实例,该实例将用于管理客户端的详细信息。它还定义了一个令牌存储实例,该实例将用于存储访问令牌。 4. 配置JWT 创建一个JWT配置类,命名为JwtConfig.java,并添加以下内容: ```java @Configuration public class JwtConfig { @Value("${jwt.secret}") private String secret; @Bean public Key key() { return Keys.hmacShaKeyFor(secret.getBytes()); } @Bean public JwtDecoder jwtDecoder() { return NimbusJwtDecoder.withSecretKey(key()).build(); } @Bean public JwtEncoder jwtEncoder() { return NimbusJwtEncoder.withSecretKey(key()).build(); } } ``` 这个类配置了JWT,定义了一个秘钥,该秘钥将用于签署和验证JWT令牌。 5. 配置资源服务器 创建一个资源服务器配置类,命名为ResourceServerConfig.java,并添加以下内容: ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private JwtAccessTokenConverter accessTokenConverter; @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.tokenStore(tokenStore()).accessTokenConverter(accessTokenConverter); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter); } } ``` 这个类配置了资源服务器,启用了资源服务器,并定义了一个令牌存储实例,该实例将用于存储访问令牌。 6. 创建实体类 创建一个User实体类,命名为User.java,并添加以下内容: ```java @Entity @Table(name = "users") public class User implements UserDetails { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(unique = true) private String username; private String password; @ElementCollection(fetch = FetchType.EAGER) private List<String> roles; @Override public Collection<? extends GrantedAuthority> getAuthorities() { return roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } } ``` 这个类定义了一个用户实体,实现了UserDetails接口,该接口提供了有关用户的详细信息。 7. 创建数据访问对象 创建一个UserRepository接口,命名为UserRepository.java,并继承JpaRepository接口,添加以下内容: ```java @Repository public interface UserRepository extends JpaRepository<User, Long> { Optional<User> findByUsername(String username); } ``` 这个接口定义了一个用户数据访问对象,用于管理用户。 8. 实现用户服务 创建一个UserServiceImpl类,命名为UserServiceImpl.java,并添加以下内容: ```java @Service public class UserServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return userRepository.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException("User not found")); } } ``` 这个类实现了UserDetailsService接口,该接口提供了一个方法,根据用户名加载用户信息。 9. 创建控制器 创建一个UserController类,命名为UserController.java,并添加以下内容: ```java @RestController @RequestMapping("/api") public class UserController { @GetMapping("/users") public List<User> getUsers() { return userRepository.findAll(); } @PostMapping("/users") public User createUser(@RequestBody User user) { user.setPassword(passwordEncoder.encode(user.getPassword())); return userRepository.save(user); } @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; } ``` 这个类定义了一个RESTful API控制器,用于管理用户。 10. 测试 启动应用程序,并使用Postman测试API接口。例如,使用POST方法向/api/users端点发送请求,创建一个新用户。 这就是Spring Boot集成Spring Security、JWT和OAuth2的示例代码。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值