SSM Framework Review Day 9: SpringMVC Type Conversion Service Exception Handling Interceptor restfu Programming Style
1. Type Conversion Services
For example: the date format passed from the front-end is 2021-12-30, which can not be converted normally. You need to write a date format converter yourself. It can only help you to convert 2021/12/30 format, because there are many types of converters built into SpringMVC.
1.1 Implementation Steps
Step 1: Import Dependencies
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <!--jackon Related Dependencies--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency>
2.web.xml configuration file
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!--To configure Springmvc DispatcherServlet(Springmvc Core Front End Controller)--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--Yes, let's spring Front-end controllers are loaded when they are created springmvc.xml Profile Creation Various controller object--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!--Can let Servlet Created at server startup--> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--Configure filters for resolving Chinese scrambling POST Request Random Code--> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3. Configure related components in the Spring MV profile
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Configuration Package Scan Create Ownership Controller object --> <context:component-scan base-package="com.bianyiit.web"></context:component-scan> <!--Configure View Parser--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--Specify prefix for logical-to-physical view conversion --> <property name="prefix" value="/WEB-INF/views/"></property> <!--Specify the suffix for the logical-to-physical view conversion --> <property name="suffix" value=".jsp"></property> </bean> <!--Appoint springmvc No Interception js Directory Resources--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <!--wantConfigure Type Conversion Service--> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="com.bianyiit.resolver.String2DateConverter"></bean> </set> </property> </bean> <!--Automatic Loading SpringMVC Two other component processor mapper processor adapters --> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> </beans>
4. Write a string wrap to specify a date format conversion class that implements the Converter interface
public class String2DateConverter implements Converter<String,Date> { @Override /** * Method parameter requires converted source data 2021-12-30 * Method returns object after value conversion */ public Date convert(String source) { System.out.println(source); Date date = null; try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); date = dateFormat.parse(source); } catch (ParseException e) { e.printStackTrace(); } return date; } }
2. Exception handling
In the daily development, there will inevitably be some difficult and unexpected situations. At this time, we need to do some relevant treatment to these possible anomalies, which can improve the user experience.
2.1. Implementation Steps
1. Import dependencies (same as above)
2. On the web. Configuration-related information in XML (same as above)
3. Configure related components in the springMVC configuration file
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Configuration Package Scan Create Ownership Controller object --> <context:component-scan base-package="com.bianyiit.web"></context:component-scan> <!--Configure View Parser--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--Specify prefix for logical-to-physical view conversion --> <property name="prefix" value="/WEB-INF/views/"></property> <!--Specify the suffix for the logical-to-physical view conversion --> <property name="suffix" value=".jsp"></property> </bean> <!--Register exception handling components--> <bean class="com.bianyiit.resolver.CustomExceptionResolver"></bean> <!--Appoint springmvc No Interception js Directory Resources--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <!--Automatic Loading SpringMVC Two other component processor mapper processor adapters --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
4. Define related exception classes to implement the HandlerExceptionResolver interface
/** * Exception handling component */ public class CustomExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { ModelAndView modelAndView = new ModelAndView(); //Logging modelAndView.addObject("msg",ex.getMessage()); modelAndView.setViewName("error"); return modelAndView; } }
3. Interceptors
One thing very similar to filters in the root Java Web in springMVC is interceptors.
3.1. Implementation Steps
1. Import dependencies (same as above)
2.web.xml configuration (same as above)
3.SpringMVC Profile Configuration Related Components
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--Configuration Package Scan Create Ownership Controller object --> <context:component-scan base-package="com.bianyiit.web"></context:component-scan> <!--Configure View Parser--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--Specify prefix for logical-to-physical view conversion --> <property name="prefix" value="/WEB-INF/views/"></property> <!--Specify the suffix for the logical-to-physical view conversion --> <property name="suffix" value=".jsp"></property> </bean> <!--springmvc Interceptor Configuration--> <mvc:interceptors> <!--Interceptor who configures who executes first--> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.bianyiit.intecepter.CustomIntecepter2"></bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.bianyiit.intecepter.CustomIntecepter1"></bean> </mvc:interceptor> </mvc:interceptors> <!--Appoint springmvc No Interception js Directory Resources--> <mvc:resources mapping="/js/**" location="/js/"></mvc:resources> <!--Automatic Loading SpringMVC Two other component processor mapper processor adapters --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
4. Define interceptor-related classes
public class CustomIntecepter1 implements HandlerInterceptor { /** * Execute the request before reaching the target resource * @param request * @param response * @param handler * @return * @throws Exception */ public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("CustomIntecepter1 preHandle...."); // request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request,response); // response.sendRedirect("/WEB-INF/views/error.jsp"); /* If a true release request is returned If a false intercept request is returned (no release request) */ return false; } /** * Execute after the target resource has been executed * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { System.out.println("CustomIntecepter1 postHandle ....."); // modelAndView.setViewName("error"); } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { System.out.println("CustomIntecepter1 afterCompletion........"); } }
4.restful programming style
restful style allows URL s to uniquely identify a resource in the server
There are seven ways to request http
But there are four common types: get post put delete
These four request modes correspond to one operation:
get: query data operations
post: add data operation
put: modify data operations
Delete: delete data operation
///user/id What is it, for example:1,2,3... @RequestMapping("/user/{id}") public String helloWorld4(@PathVariable("id") String id){ System.out.println("Query No." + id + "Users"); return "hello"; }
Today's learning experience: In fact, learning sometimes has a certain set of routines, there is a fixed set of learning routines, of course, you need to learn for a period of time and slowly find the rules. Writing a blog is to make a summary of what you learned that day, and to review and consolidate what you learned that day. To solve some problems encountered in learning, you can try to solve them first. This can enhance your impression and promote your learning efficiency. Last sentence: Learning is the most powerful skill in the process of human development!