文章目录
SpringMVC高级
1. 添加其它Servlet和Filter
根据Servlet3.0+特性,容器会在类路径中查找实现了javax.servlet.ServletContainerInitializer接口的类,如果能发现的话,就会用它来配置Servlet。而Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类会反过来查找实现了WebApplicationInitializer的类并将配置的任务交给它们来完成。
我们可以利用上述特点,来给项目添加其它Servlet和Filter。我们可以在自己编写的SpringWebAppInitializer中重写父类的onStartup()方法即可,因为父类已经实现了WebApplicationInitializer接口:
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
Dynamic servlet = servletContext.addServlet("helloServlet", HelloServlet.class);
servlet.addMapping("/servlet/hello");
javax.servlet.FilterRegistration.Dynamic filter = servletContext.addFilter("helloFilter", HelloFilter.class);
filter.addMappingForUrlPatterns(null, false, "/servlet/*");
System.out.println("注册完毕...");
}
2. multipart请求处理
配置multipart,需要在SpringWebAppInitializer中重写父类方法:
@Override
protected void customizeRegistration(Dynamic registration) {
super.customizeRegistration(registration);
registration.setMultipartConfig(new MultipartConfigElement(
// 上传过程中使用的临时文件路径
"c:/Other/upload",
// 上传文件的最大容量
2097152,
// 整个multipart请求的最大容量
4194304,
// 上传过程中,文件大小达到一个指定容量,将会写入到临时文件路径
0));
}
处理multipart请求:
@Controller
public class FileController {
@RequestMapping(value = "/upload", method = RequestMethod.GET)
public String showUpload() {
return "file";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestPart("icon") Part icon, String userName) throws IOException {
System.out.println(userName);
String fileName = icon.getSubmittedFileName();
icon.write("c:/Other/" + fileName);
return "success";
}
}
3. 异常处理
我们可以使用通知来统一处理控制器中出现的错误,处理方式一般为跳转至较为友好的错误提示页面:
@ControllerAdvice
public class ErrorHandler {
@ExceptionHandler(Exception.class)//设置针对什么样的异常进行处理
public String errorHandle() {
return "error";
}
}
提示:可以修改上传文件的最大容量来触发异常。
4. 基于Xml配置SpringMVC
4.1 web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-root.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>c:/Other/upload</location>
<max-file-size>2097152</max-file-size>
<max-request-size>4194304</max-request-size>
<file-size-threshold>0</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4.2 spring-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<context:component-scan
base-package="com.turing.web" />
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".html"></property>
<property name="templateMode" value="HTML"></property>
<property name="cacheable" value="false"></property>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="enableSpringELCompiler" value="true"></property>
<property name="templateResolver" ref="templateResolver"></property>
</bean>
<bean id="viewResolver"
class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine"></property>
<property name="characterEncoding" value="utf-8"></property>
</bean>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/" />
<mvc:exclude-mapping path="/login" />
<bean class="com.turing.web.interceptors.LoginInterceptors"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
4.3 spring-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan
base-package="com.turing">
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="dataSource"
class="org.apache.commons.dbcp2.BasicDataSource">
<property name="username" value="root"></property>
<property name="password" value="admin"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="driverClassName"
value="com.mysql.jdbc.Driver"></property>
<property name="initialSize" value="5"></property>
<property name="minIdle" value="2"></property>
<property name="maxIdle" value="16"></property>
<property name="maxTotal" value="8"></property>
<property name="maxWaitMillis" value="60000"></property>
<property name="validationQuery" value="select 1"></property>
</bean>
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configuration">
<bean class="org.apache.ibatis.session.Configuration">
<property name="logImpl"
value="org.apache.ibatis.logging.log4j2.Log4j2Impl"></property>
<property name="mapUnderscoreToCamelCase" value="true"></property>
<property name="lazyLoadingEnabled" value="true"></property>
<property name="aggressiveLazyLoading" value="false"></property>
<property name="lazyLoadTriggerMethods" value=""></property>
</bean>
</property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.turing.mapper"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="check*" propagation="SUPPORTS"
read-only="true" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor
pointcut="execution(* com.turing.service..*.*(..))"
advice-ref="txAdvice" />
</aop:config>
</beans>
me=“delete*” propagation=“REQUIRED” />
<tx:method name=“update*” propagation=“REQUIRED” />
</tx:attributes>
</tx:advice>
aop:config
<aop:advisor
pointcut=“execution(* com.turing.service….(…))”
advice-ref=“txAdvice” />
</aop:config>
2279

被折叠的 条评论
为什么被折叠?



