Sprigmvc project to springboot method

  • 2021-01-25 07:33:02
  • OfStack

If you have an old springmvc program that you want to convert to springboot, read this article.

instructions

If your project is not even an maven project, please switch to an maven project by yourself and follow this tutorial.

This tutorial is for maven projects with spring+springmvc+mybatis+shiro.

1. Modify pom file dependencies

Remove the previous spring dependency and add the springboot dependency


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
</parent>
<dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>

      <!--  This one comes with the knockout  tomcat The deployment of -->
      <exclusions>
        <exclusion>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
      </exclusions>

    </dependency>
    <!-- tomcat Container deployment  -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <!--<scope>compile</scope>-->
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
    </dependency>
    <!--  support  @ConfigurationProperties  annotations  -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-configuration-processor</artifactId>
      <optional>true</optional>
    </dependency>
 <dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
 </dependency>
</dependencies>

Add the springboot build plug-in


<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <source>1.7</source>
      <target>1.7</target>
    </configuration>
  </plugin>
  <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>1.5.9.RELEASE</version>
    <executions>
      <execution>
        <goals>
          <goal>repackage</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>

2. Add application startup file

Note that if Application is in a layer above controller, service, dao, no need to configure @ComponentScan.

Otherwise, you need to indicate which packets to scan.


@SpringBootApplication
//@ComponentScan({"com.cms.controller","com.cms.service","com.cms.dao"})
public class Applicationextends SpringBootServletInitializer{

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
    return application.sources(Application.class);
  }

  public static void main(String[] args)throws Exception {
    SpringApplication.run(Application.class, args);
  }
}

3. Add springboot configuration file

Add the application.properties file below resources


 Add basic configuration 
# The default prefix 
server.contextPath=/
#  Specify the environment 
spring.profiles.active=local
# jsp configuration 
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
#log The configuration file 
logging.config=classpath:logback-cms.xml
#log The path 
logging.path=/Users/mac/work-tommy/cms-springboot/logs/
# The data source 
spring.datasource.name=adminDataSource
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/mycms?useUnicode=true&autoReconnect=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 123456

4. Use @Configuration to inject the configuration

Injection mybatis configuration, paging plug-in please choose


@Configuration
@MapperScan(basePackages = "com.kuwo.dao",sqlSessionTemplateRef = "adminSqlSessionTemplate")
public class AdminDataSourceConfig{

  @Bean(name = "adminDataSource")
  @ConfigurationProperties(prefix = "spring.datasource")
  @Primary
  public DataSource adminDataSource(){
    return DataSourceBuilder.create().build();
  }

  @Bean(name = "adminSqlSessionFactory")
  @Primary
  public SqlSessionFactory adminSqlSessionFactory(@Qualifier("adminDataSource")DataSource dataSource)throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    // Paging plug-in 
// PageHelper pageHelper = new PageHelper();
    PagePlugin pagePlugin = new PagePlugin();
// Properties props = new Properties();
// props.setProperty("reasonable", "true");
// props.setProperty("supportMethodsArguments", "true");
// props.setProperty("returnPageInfo", "check");
// props.setProperty("params", "count=countSql");
// pageHelper.setProperties(props);
    // Add the plug-in 
    bean.setPlugins(new Interceptor[]{pagePlugin});
    //  add mybatis The configuration file 
    bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis/mybatis-config.xml"));
    //  add mybatis The mapping file 
    bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/system/*.xml"));
    return bean.getObject();
  }

  @Bean(name = "adminTransactionManager")
  @Primary
  public DataSourceTransactionManager adminTransactionManager(@Qualifier("adminDataSource")DataSource dataSource){
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "adminSqlSessionTemplate")
  @Primary
  public SqlSessionTemplate adminSqlSessionTemplate(@Qualifier("adminSqlSessionFactory")SqlSessionFactory sqlSessionFactory)throws Exception {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}

Add Interceptor configuration, note the order of addInterceptor, don't mess it up


@Configuration
public class InterceptorConfigurationextends WebMvcConfigurerAdapter{
  @Override
  public void addInterceptors(InterceptorRegistry registry){
    registry.addInterceptor(new LoginHandlerInterceptor());
  }
}

Add the shiro configuration file

Note: redis was originally used for session caching, but there is a problem with shiro integration. After user object is stored, it cannot be converted after being retrieved from shiro, so it is temporarily abandoned for redis to cache session.


@Configuration
public class ShiroConfiguration{
  @Value("${spring.redis.host}")
  private String host;

  @Value("${spring.redis.port}")
  private int port;

  @Value("${spring.redis.timeout}")
  private int timeout;
  @Bean
  public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor(){
    return new LifecycleBeanPostProcessor();
  }

  /**
   * ShiroFilterFactoryBean  Handle issues with intercepting resource files. 
   *  Note: Alone 1 a ShiroFilterFactoryBean The configuration is or reported an error because in 
   *  Initialize the ShiroFilterFactoryBean When you need to inject: SecurityManager
   *
   Filter Chain specifies 
   1 , 1 a URL You can configure more than one Filter , separated by commas 
   2 When multiple filters are set, all of them are verified to be passed 
   3 , partial filters can be specified parameters, such as perms . roles
   *
   */
  @Bean
  public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){
    System.out.println("ShiroConfiguration.shirFilter()");
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

    //  You must set up  SecurityManager
    shiroFilterFactoryBean.setSecurityManager(securityManager);
    //  It is automatically found if the default is not set Web Project root directory "/login.jsp" page 
    shiroFilterFactoryBean.setLoginUrl("/login_toLogin");
    //  Link to skip after successful login 
    shiroFilterFactoryBean.setSuccessUrl("/usersPage");
    // Unauthorized interface ;
    shiroFilterFactoryBean.setUnauthorizedUrl("/403");
    // The interceptor .
    Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();

    // Configuration to exit   The filter , Which of the specific exit code Shiro It's been done for us 
    filterChainDefinitionMap.put("/logout", "logout");
    filterChainDefinitionMap.put("/login_toLogin", "anon");
    filterChainDefinitionMap.put("/login_login", "anon");
    filterChainDefinitionMap.put("/static/login/**","anon");
    filterChainDefinitionMap.put("/static/js/**","anon");
    filterChainDefinitionMap.put("/uploadFiles/uploadImgs/**","anon");
    filterChainDefinitionMap.put("/code.do","anon");
    filterChainDefinitionMap.put("/font-awesome/**","anon");
    //<!--  Filter chain definitions, executed from top to bottom, 1 As will be  /** Put it at the bottom  -->: This is a 1 A hole? 1 The code won't work if you're not careful ;
    //<!-- authc: all url Must be authenticated to be able to access ; anon: all url Both can be accessed anonymously -->

    filterChainDefinitionMap.put("/**", "authc");


    shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
    return shiroFilterFactoryBean;
  }


  @Bean
  public SecurityManager securityManager(){
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    // Set up the realm.
    securityManager.setRealm(myShiroRealm());
    //  Custom cache implementation   use redis
    //securityManager.setCacheManager(cacheManager());
    //  The custom session management   use redis
    securityManager.setSessionManager(sessionManager());
    return securityManager;
  }

  @Bean
  public ShiroRealm myShiroRealm(){
    ShiroRealm myShiroRealm = new ShiroRealm();
// myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
    return myShiroRealm;
  }

}
  /**
   *  open shiro aop Annotation support .
   *  Use proxy mode ; So you need to turn on code support ;
   * @param securityManager
   * @return
   */
  @Bean
  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
    AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
    authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
    return authorizationAttributeSourceAdvisor;
  }

  /**
   *  configuration shiro redisManager
   *  Using the shiro-redis Open source plug-in 
   * @return
   */
  public RedisManager redisManager(){
    RedisManager redisManager = new RedisManager();
    redisManager.setHost(host);
    redisManager.setPort(port);
    redisManager.setExpire(1800);
    redisManager.setTimeout(timeout);
    // redisManager.setPassword(password);
    return redisManager;
  }

  /**
   * cacheManager  The cache  redis implementation 
   *  Using the shiro-redis Open source plug-in 
   * @return
   */
  public RedisCacheManager cacheManager(){
    RedisCacheManager redisCacheManager = new RedisCacheManager();
    redisCacheManager.setRedisManager(redisManager());
    return redisCacheManager;
  }

  /**
   * RedisSessionDAO shiro sessionDao The realization of the layer   through redis
   *  Using the shiro-redis Open source plug-in 
   */
  @Bean
  public RedisSessionDAO redisSessionDAO(){
    RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
    redisSessionDAO.setRedisManager(redisManager());
    return redisSessionDAO;
  }

  @Bean
  public DefaultWebSessionManager sessionManager(){
    DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
// sessionManager.setSessionDAO(redisSessionDAO());
    return sessionManager;
  }

}

conclusion


Related articles: