spring boot combat

Next , I will explore the article , continue to go deep, and solve common codes such as custom filters, listeners, and interceptors. Let's take a look at the project structure first:

Before realizing the problems mentioned above, let's do a simple database operation. The orm framework used here is mybatis:

1. Encode database connection parameters in application.properties (application.properties is the default resource file of 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. Encoding the database connection pool, using HikariCP (parameters configured in the default resource file can get the value through @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")
	//Mark this Bean If there are multiple candidates of the same type of Bean, the Bean will be considered first. "When configuring multiple data sources, note that there must be a primary data source, and mark the bean with @Primary
    @Primary
    public DataSource dataSource() {
    	HikariDataSource dataSource = new HikariDataSource ();
        dataSource.setDriverClassName(driverClass);
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        
        dataSource.setConnectionTimeout(30000);
        //The maximum duration of a connection idle state (milliseconds), the timeout is released (retired), default: 10 minutes
        dataSource.setIdleTimeout(60000);
        //The life time of a connection (milliseconds), if it times out and is not used, it will be released (retired), default: 30 minutes, it is recommended to set 30 seconds less than the database timeout period, refer to the MySQL wait_timeout parameter (show variables like '%timeout %';)
        dataSource.setMaxLifetime(600000);
        //Maximum number of connections allowed in the connection pool. Default: 10; Recommended formula: ((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. Create model, mapper and code 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);
}

 The specific sql will not be posted, it takes up too much space.

4. Coding Controller and View (using Freemarker)

@RestController //@RestController is equivalent to @Controller+@ResponseBody
@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>

 In this way, the database operation aspect has come to an end.

Next, return to the main topic, and wait to implement the custom interceptor. The length is too long. Only the key code is posted here. The entire project code can be downloaded as an attachment.

1. Code the login interceptor

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 {
    	//Business code
	return super.preHandle(request, response, handler);
    }

}

 2. Code the Config and add the interceptor to the 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");
	}
	
}

 These are the key codes of custom interceptors.

Then implement the custom filter:

@Order(1) //Execute the filter order, the smaller the value, the first
@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 {
		//Business code
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}

 In the preliminary article, a @ServletComponentScan annotation has been added to the Run.java class. Its function is to automatically register Servlet, Filter, and Listener directly through the @WebServlet, @WebFilter, and @WebListener annotations.

It's a pity that the listener and servlet are not implemented in this project. I'll make it up later when I have time...

There are also multiple data source configurations that have been implemented, download the project yourself and see, I won't say more here...

 Make up the project sql script:

CREATE TABLE IF NOT EXISTS `t_function` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) DEFAULT NULL,
  `Authurl` varchar(100) DEFAULT NULL,
  `Url` varchar(100) DEFAULT NULL,
  `ParentID` int(11) DEFAULT NULL,
  `Sort` int(11) DEFAULT NULL,
  `Deleted` bit(1) DEFAULT b'0',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t_role` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) DEFAULT NULL,
  `Remark` varchar(50) DEFAULT NULL,
  `Deleted` bit(1) DEFAULT b'0',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t_role_function` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `RoleID` int(11) DEFAULT NULL,
  `FunctionID` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t_user` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) DEFAULT NULL,
  `Password` varchar(50) DEFAULT NULL,
  `State` bit(1) DEFAULT b'0',
  `Email` varchar(150) DEFAULT NULL,
  `CreateTime` date DEFAULT NULL,
  `Deleted` bit(1) DEFAULT b'0',
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t_user_role` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `UserID` int(11) DEFAULT NULL,
  `RoleID` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326191216&siteId=291194637