欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot实战——自定义

程序员文章站 2022-05-02 12:07:00
...

接着spring boot应用,在这里解决自定义过滤器、监听器、拦截器这些常用编码。先来看看项目结构:

spring boot实战——自定义

实现上面所说的问题前,先来个简单的数据库操作。这里用的orm框架是mybatis:

1.在application.properties编码数据库连接参数(application.properties是spring boot默认的资源文件)

jdbc.driverClassName=com.mysql.jdbc.Driver  
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8  
jdbc.username=root  
jdbc.password=123456
2.编码数据库连接池,用的是HikariCP(在默认的资源文件下配置的参数可通过@Value("${keyName}")这种方式获取值

@Configuration  
@MapperScan(basePackages = "com.tboot.mapper", sqlSessionFactoryRef = "sqlSessionFactory")  
public class DataSourceConfig {  
      
    @Value("${jdbc.url}")  
    private String url;  
   
    @Value("${jdbc.username}")  
    private String user;  
   
    @Value("${jdbc.password}")  
    private String password;  
   
    @Value("${jdbc.driverClassName}")  
    private String driverClass;  
      
    @Bean(name = "dataSource",destroyMethod = "close")  
    //标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。「多数据源配置的时候注意,必须要有一个主数据源,用 @Primary 标志该 Bean  
    @Primary  
    public DataSource dataSource() {  
        HikariDataSource dataSource = new HikariDataSource();  
        dataSource.setDriverClassName(driverClass);  
        dataSource.setJdbcUrl(url);  
        dataSource.setUsername(user);  
        dataSource.setPassword(password);  
          
        dataSource.setConnectionTimeout(30000);  
        //一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟  
        dataSource.setIdleTimeout(60000);  
        //一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';)  
        dataSource.setMaxLifetime(600000);  
        //连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)  
        dataSource.setMaximumPoolSize(15);  
        return dataSource;  
    }  
   
    @Bean(name = "transactionManager")  
    @Primary  
    @Qualifier("tm1")  
    public DataSourceTransactionManager transactionManager() {  
        return new DataSourceTransactionManager(dataSource());  
    }  
   
    @Bean(name = "sqlSessionFactory")  
    @Primary  
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource)  
            throws Exception {  
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();  
        sessionFactory.setDataSource(dataSource);  
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()  
                .getResources("classpath:mapping/*.xml"));  
        return sessionFactory.getObject();  
    }  
  
}
3.创建model、mapper和编码sql
public class User {  
    private Integer id;  
  
    private String name;  
  
    private String password;  
  
    private Boolean state;  
  
    private String email;  
  
    private Date createtime;  
  
    private Boolean deleted;  
  
……  
}
public interface UserMapper {  
    int deleteByPrimaryKey(Integer id);  
  
    int insert(User record);  
  
    int insertSelective(User record);  
  
    User selectByPrimaryKey(Integer id);  
  
    int updateByPrimaryKeySelective(User record);  
  
    int updateByPrimaryKey(User record);  
      
    User selectByPassword(@Param("name")String name, @Param("password")String password);  
}

具体的sql就不贴了,太占篇幅。

4.编码Controller和视图(用的是Freemarker)

@RestController //@RestController相当于@[email protected]  
@RequestMapping("/test")  
public class HelloController {  
      
    @Resource  
    private UserMapper userMapper;  
      
    @RequestMapping(value = "/view")  
    public ModelAndView view(int id) {  
        ModelAndView mv = new ModelAndView("backweb/view");  
        mv.addObject("user", userMapper.selectByPrimaryKey(id));  
        return mv;  
    }  
      
}
<!DOCTYPE html>  
<html>  
<head>  
<title>view</title>  
</head>  
<body>  
<div>${user.name }---${user.email}</div>  
</body>  
</html>

这样数据库操作方面就告一段落。

接下来回归正题,等来实现自定义拦截器,篇幅太长,这里只贴出关键代码,整个项目代码可下载附件。

1.编码登录拦截器

public class LoginInterceptor extends HandlerInterceptorAdapter {  
    private static Logger logger = Logger.getLogger(LoginInterceptor.class.getName());  
      
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {  
        //业务代码  
    return super.preHandle(request, response, handler);  
    }  
  
}
2.编码MyConfig,将拦截器添加到Config中
@Configuration  
public class MyConfig extends WebMvcConfigurerAdapter {  
  
    @Override  
    public void addInterceptors(InterceptorRegistry registry) {  
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/manage/**").excludePathPatterns("/manage/login");  
        //registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/manage/**")  
            //.excludePathPatterns("/manage/login","/manage/index","/manage/menu","/manage/sysExit");  
    }  
      
}

自定义拦截器的关键代码就这些。

紧接着实现自定义过滤器:

@Order(1) //执行过滤顺序,值越小,越先执行  
@WebFilter(filterName = "requestSessionFilter", urlPatterns = "/*")  
public class RequestSessionFilter implements Filter {  
    private static Logger logger = Logger.getLogger(RequestSessionFilter.class.getName());  
    @Override  
    public void destroy() {  
  
    }  
  
    @Override  
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain fchain) throws IOException, ServletException {  
        //业务代码  
    }  
  
    @Override  
    public void init(FilterConfig arg0) throws ServletException {  
  
    }  
  
}

在spring boot应用中,Run.java类上面已加了个@ServletComponentScan注解,它的作用就是可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册Servlet、Filter、Listener。

很遗憾这项目中并没有实现监听器和servlet,往后有时间再补吧……

还有多数据源配置是实现了的,自己下载项目看吧,这里就不多说了……