Spring study day 3
1, Spring jdbctemplate basic usage
1.1 overview of JdbcTemplate
It is an object provided in the spring framework and a simple encapsulation of the original cumbersome Jdbc API object. The spring framework provides us with many operation template classes. For example: JdbcTemplate and HibernateTemplate for operating relational data, RedisTemplate for operating nosql database, JmsTemplate for operating message queue, etc.
1.2 development steps of JdbcTemplate
① Import spring JDBC and spring TX coordinates
<!--Import spring of jdbc coordinate--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--Import spring of tx coordinate--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.5.RELEASE</version> </dependency>
② Create database tables and entities
③ Create a JdbcTemplate object
④ Perform database operations
//1. Create data source object ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test"); dataSource.setUser("root"); dataSource.setPassword("root"); //2. Create a JdbcTemplate object JdbcTemplate jdbcTemplate = new JdbcTemplate(); //3. Set data source to JdbcTemplate jdbcTemplate.setDataSource(dataSource); //4. Perform operation jdbcTemplate.update("insert into account values(?,?)","tom",5000);
We can give Spring the right to create the JdbcTemplate and the right to create the data source DataSource. Inject the data source DataSource into the JdbcTemplate template object inside the Spring container. The configuration is as follows:
Use profile:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=root
<!--1,load jdbc.properties--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2,Configure data source objects--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--3,to configure JdbcTemplate object--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean>
@Test public void testSpringJdbcTemplate() throws PropertyVetoException { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class); jdbcTemplate.update("insert into account values(?,?)","lucy",5000); }
1.3 common operations of JdbcTemplate
-
Modify operation
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:applicationContext.xml") public class JdbcTemplateCRUDTest { @Autowired private JdbcTemplate jdbcTemplate; @Test //Test modification operation public void testUpdate(){ jdbcTemplate.update("update account set money=? where name=?",1000,"tom"); } }
-
Delete and query all operations
@Test public void testDelete(){ jdbcTemplate.update("delete from account where name=?","tom"); } @Test public void testQueryAll(){ List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class)); for (Account account : accounts) { System.out.println(account.getName()); } }
-
Query single data operation
@Test //Test query single object operation public void testQueryOne(){ Account account = jdbcTemplate.queryForObject("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), "tom"); System.out.println(account.getName()); } @Test //Test query single simple data operation (aggregate query) public void testQueryCount(){ Long aLong = jdbcTemplate.queryForObject("select count(*) from account", Long.class); System.out.println(aLong); }
2, Spring MVC interceptor
1.1 function of interceptor
The interceptor of Spring MVC is similar to the Filter in Servlet development, which is used to preprocess and post process the processor.
The interceptors are connected into a chain in a certain order, which is called Interceptor Chain. When accessing the intercepted method or field, the interceptors in the Interceptor Chain will be called in the order they were previously defined. Interceptor is also the concrete implementation of AOP idea
1.2 difference between interceptor and filter
difference | filter | Interceptor |
---|---|---|
Scope of use | Is part of the servlet specification and can be used by any Java Web project | It belongs to the spring MVC framework itself. Only projects that use the spring MVC framework can use it |
Interception range | After / * is configured in URL pattern, all resources to be accessed can be intercepted | Only the accessed controller methods will be intercepted. If the accessed controller methods are jsp, html,css,image or js, they will not be intercepted |
1.3 interceptor is a quick start
The custom interceptor is very simple. There are only three steps:
① Create an interceptor class to implement the HandlerInterceptor interface
Method name | explain |
---|---|
preHandle() | Method will be called before the request is processed. The return value of this method is Boolean. When it returns false, it means that the request ends and subsequent interceptors and controllers will not execute again; When the return value is true, it will continue to call the preHandle method of the next Interceptor |
postHandle() | This method is called after the current request is processed, provided that the return value of the preHandle method is true, and it will be called before the dispatcher servlet renders the view return, so we can operate on the ModelAndView object processed by the Controller in this method |
afterCompletion() | This method will be executed after the end of the entire request, that is, after the dispatcher servlet renders the corresponding view. Only when the return value of the preHandle method is true can it be called |
public class MyHandlerInterceptor1 implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println("preHandle running..."); return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { System.out.println("postHandle running..."); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { System.out.println("afterCompletion running..."); } }
② Configure interceptor
<!--Configuring Interceptors --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.itheima.interceptor.MyHandlerInterceptor1"/> </mvc:interceptor> </mvc:interceptors>
③ Test the interception effect of the interceptor
@RequestMapping("/quick23") @ResponseBody public ModelAndView quickMethod23() throws IOException, ParseException { System.out.println("Target method execution...."); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("name","itcast"); modelAndView.setViewName("index"); return modelAndView; }
result:
If there are multiple interceptors, follow the principle of first in, first in and then out
3, Spring MVC exception handling
1.1 ideas for exception handling
There are two types of exceptions in the system: expected exception and runtime exception RuntimeException. The former obtains exception information by capturing exceptions, and the latter mainly reduces the occurrence of runtime exceptions by standardizing code development and testing.
Dao, Service and Controller of the system are thrown upward through throws Exception. Finally, the spring MVC front-end Controller sends it to the exception handler for exception handling, as shown in the following figure:
1.2 two methods of exception handling
-
Use the simple exception handler SimpleMappingExceptionResolver provided by Spring MVC
-
Implement the exception handling interface of Spring, HandlerExceptionResolver, and customize its own exception handler
1.3 simple exception handler SimpleMappingExceptionResolver
Spring MVC has defined this type converter. When using it, you can map and configure the corresponding exceptions and views according to the project situation
1.4 custom exception handling steps
① Create an exception handler class to implement HandlerExceptionResolver
public class MyExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { //Code implementation for handling exceptions //Create ModelAndView object ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("exceptionPage"); return modelAndView; } } We can also go to different pages according to the exception type
② Configure exception handler
③ Write exception page
④ Test abnormal jump
@RequestMapping("/quick22") @ResponseBody public void quickMethod22() throws IOException, ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); simpleDateFormat.parse("abcde"); }