笔者自学的框架,知识点来自网上学习教程,方便实惠,推荐,特此声明。
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
1.2 设置maven参数<build>
<finalName>springmybatis</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<!-- jdk的版本号 -->
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
1.3 .额外依赖 <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.9.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.9.Final</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 注册spring MVC中央控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<!-- spring MVC中的核心控制器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 静态资源解释器 方式1 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
</web-app>
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
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-3.2.xsd">
<!-- 静态资源解释器 方式2 -->
<mvc:default-servlet-handler/>
<!-- 静态资源解释器 方式3 -->
<mvc:resources mapping="/images/**" location="/images/" />
<!-- 注册组件扫描器 -->
<context:component-scan base-package="com.java.*"/>
<!-- 视图解释类 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!--解决返回json数据乱码问题-->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 通过xml注册Controller -->
<bean id="/hello.do" class="com.java.Controller.HelloSpringMVC"/>
</beans>
<!-- 静态资源解释器 方式1 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
1.2 注册spring MVC核心控制器DispatcherServlet,扫描springmvc.xml<!-- 注册spring MVC中央控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<!-- spring MVC中的核心控制器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
1.3 设置utf-8,解决数据乱码 </servlet-mapping>
<!--字符编码过滤器-->
<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>
<!--强制指定字符编码,即如果在request中指定了字符编码,那么也会为其强制指定当前设置的字符编码-->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*
<!-- 静态资源解释器 方式2 -->
<mvc:default-servlet-handler/>
<!-- 静态资源解释器 方式3 -->
<mvc:resources mapping="/images/**" location="/images/" />
2.2 注册controller<bean id="/hello.do" class="com.java.Controller.HelloSpringMVC" />
2.2.2 注解方式(注解需要添加注解驱动,用来注册controller的驱动,用来注册AnnotationDrivenBeanDefinitionParser 对象,并且AnnotationDrivenBeanDefinitionParser 中注册 RequestMappingHandlerMapping & RequestMappingHandlerAdapter 这两个 Bean,如果不添加会导致无法创建controller,报出404错误。注解分析详解)之后在类上添加@Controller() <!-- 注册组件(注解)扫描器 -->
<context:component-scan base-package="com.java.*"/>
<!-- 注册注解驱动-->
<mvc:annotation-driven/>
传入com.monkey1024.Product类型,会将其命名为"product"
com.monkey1024.MyProduct 命名为 "myProduct"
com.monkey1024.UKProduct 命名为 "UKProduct"
model.addAttribute(name);
model.addAttribute("username", name);
model可添加Collection参数,例如list以value为name和value、map以key为name,value为value<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
<!--定义外部资源view对象-->
<bean id="baidu" class="org.springframework.web.servlet.view.RedirectView">
<property name="url" value="http://www.baidu.com/"/>
</bean>
c:void 有两种用法,靠servlet自带的跳转 request.setAttribute("student", student);
//因为使用servlet中的api,所以视图解析就不能使用了,转发
request.getRequestDispatcher("/jsp/welcome.jsp").forward(request,response);
//重定向
response.sendRedirect("/other-app/Other");
方式2:通过response.getWriter()返回ajax数据时,不需要返回页面,所以返回类型为viod$(function () {
$("#ajaxRequest").click(function () {
$.ajax({
method:"post",
url:"/ajaxRequest.do",
data:{name:"java",age:18},
dataType:"json",
success:function (result) {
alert(result.name + "," + result.age);
}
});
});
});
PrintWriter out = response.getWriter();
String jsonString = JSON.toJSONString(student);
out.write(jsonString);
d:返回类型为object,使用了jackjson来数据类型转换//返回类型为ModelAndView
//手动显式指定使用转发,此时springmvc.xml配置文件中的视图解析器将会失效
mv.setViewName("forward:/jsp/result.jsp");
//手动重定向
mv.setViewName("redirect:/jsp/result.jsp");
//返回类型为/String
//转发
return "forward:/jsp/result.jsp";
//重定向
return "redirect:/jsp/result.jsp";
//返回类型为void
//转发
request.getRequestDispatcher("/jsp/result.jsp").forward(request, response);
//重定向
response.sendRedirect(request.getContextPath()+"/jsp/result.jsp");
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.java.Tool.MyException">error/MyError</prop>
</props>
</property>
<property name="defaultErrorView" value="error/error"/>
<property name="exceptionAttribute" value="ex"/>
</bean>
可自定义异常处理类,并且绑定自定义异常页面,也有默认异常处理,需要指定页面。ex为异常信息。@ExceptionHandler(MyException.class)
public ModelAndView handleMyException(Exception ex) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("/error/MyError");
return mv;
}
c: 可写一个异常父类,子类全部继承即可无需重写,缺点是无法继承其他类,同时可书写一个默认异常处理方法。/**
* 处理MyException异常的方法
* @param ex
* @return
*/
@ExceptionHandler(MyException.class)
public ModelAndView handleMyException(Exception ex) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("/error/MyError");
return mv;
}
/**
* 其他异常处理,注解中不用写value属性
* @param ex
* @return
*/
@ExceptionHandler
public ModelAndView handleException(Exception ex) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", ex);
mv.setViewName("/error/error");
return mv;
}
<!--注册注解驱动-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--注册类型转换器-->
<bean id="dateConverter" class="com.java.Tool.DateConverter"/>
<!--注册类型转换服务bean-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters" ref="dateConverter"/>
</bean>
方法代码public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
if (s != null && !"".equals(s)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
之后转换器会自动把String转换为Date类型<!--验证器-->
<bean id="monkey1024Validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
</bean>
<!--注册注解驱动-->
<mvc:annotation-driven validator="monkey1024Validator"/>
c: 常用注解@RequestMapping("/register.do")
//不能将@Validated 注解在String类型和基本类型的形参前。
//BindingResult参数可以获取到所有验证异常的信息
public ModelAndView register(@Validated User user, BindingResult br) {
ModelAndView mv = new ModelAndView();
List<ObjectError> allErrors = br.getAllErrors();
System.out.println(allErrors.size());
if (allErrors != null && allErrors.size() > 0) {
FieldError nameError = br.getFieldError("name");
FieldError ageError = br.getFieldError("age");
FieldError phoneError = br.getFieldError("phone");
if (nameError != null) {
mv.addObject("nameError", nameError.getDefaultMessage());
}
if (ageError != null) {
mv.addObject("ageError", ageError.getDefaultMessage());
}
if (phoneError != null) {
mv.addObject("phoneError", phoneError.getDefaultMessage());
}
mv.setViewName("/register");
return mv;
}
mv.addObject("name", user.getName());
mv.setViewName("/user");
return mv;
}
<!--注册multipartResolver,由DispatcherServlet来负责调用-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--设置字符编码防止文件名乱码-->
<property name="defaultEncoding" value="utf-8"/>
<!--设置上传文件的总大小,单位是字节b-->
<property name="maxUploadSize" value="1048576"/>
<!--设置单个上传文件的大小,单位是字节b-->
<property name="maxUploadSizePerFile" value="1048576"/>
<!--设置内存缓冲区的大小,当超过该值的时候会写入到临时目录-->
<property name="maxInMemorySize" value="1048576"/>
<!--设置临时目录-->
<property name="uploadTempDir" value="tempupload"/>
<!--默认是false,如果设置为true的话,不会将文件路径去除,在IE浏览器下上传时会将路径名也作为文件名上传:D:\image\monkey.png-->
<property name="preserveFilename" value="false"/>
<!--是否使用懒加载,默认是false-->
<property name="resolveLazily" value="true"/>
</bean>
<!--使用servlet3.0实现文件上传-->
<multipart-config>
<!--临时文件路径-->
<location>/temp</location>
<!--单个上传文件的最大值,单位是byte-->
<max-file-size>100</max-file-size>
<!--总上传文件的最大值-->
<max-request-size>52428800</max-request-size>
<!--内存缓冲区的大小,当超过该值时,会写入到临时文件中,单位是byte-->
<file-size-threshold>1024</file-size-threshold>
</multipart-config>
在springmvc.xml添加以下内容<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
ps:文件上传名称相同时,需要将MultipartFile参数变为MultipartFile数组参数,并在之前添加@RequestParam注解package com.monkey1024.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器中的preHandle方法");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器中的postHandle方法");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("拦截器中的afterCompletion方法");
}
}
springmvc.xml文件中注册拦截器,/** 表示对所有controller拦截,可定义多个拦截器 <!--注册拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.monkey1024.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>