学习SpringMVC(一-1-2-25)
来源:互联网 发布:矩阵力学的主要创立者 编辑:程序博客网 时间:2024/05/21 19:34
学习SpringMVC(一)之helloworld
首先,来一个入门案例,带你进入helloworld!
1.创建WEB工程,导入JAR包
2.在WEB.XML文件中配置一个DispatcherServlet
3.编写一个Controller类
- <strong><span style="font-size:18px;">import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- @Controller
- public class HelloWorld {
- @RequestMapping("/helloworld")
- public String hello(){
- System.out.println("hello cgf,welcome to springmvc again");
- return "hello";
- }
- }</span></strong>
- <strong><span style="font-size:18px;"><?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-4.0.xsd
- http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
- <!-- 配置自动扫描的包 -->
- <context:component-scan base-package="com.cgf.springmvc.handlers"></context:component-scan>
- <!-- 配置视图解析器 -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
- </beans></span></strong>
学习SpringMVC(二)之RequestMapping
1:@RequestMapping 除了修饰方法, 还可来修饰类
类定义处: 提供初步的请求映射信息。相对于 WEB 应用的根目录
方法处: 提供进一步的细分映射信息。 相对于类定义处的 URL。若类定义处未标注 @RequestMapping,则方法处标记的 URL相对于 WEB 应用的根目录
在前一讲中,是单单用来修饰方法,这一讲同时也用来修饰类,所以在index.jsp中加入了以下代码:
新写了一个controller
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- <span style="color:#ff0000;">@RequestMapping("/springmvc")</span>
- @Controller
- public class MyRequestMapping {
- <span style="color:#ff0000;">@RequestMapping("/RequestMapping")</span>
- public String myRequestMapping(){
- System.out.println("myRequestMapping");
- return "hello";
- }
- }</span>
2:RequestMapping 的value属性指定修饰的URL路径和method属性用来指定请求方式(GET,POST)
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- <span style="color:#ff0000;">@RequestMapping("/springmvc")</span>
- @Controller
- public class MyRequestMapping {
- @RequestMapping(value="/RequestMapping",method="RequestMethod.POST")
- public String myRequestMapping(){
- System.out.println("myRequestMapping");
- return "hello";
- }
- }</span>
3:RequestMapping的params属性和headers属性,用法简单,而且不太常用,这里就不会介绍了
4:@RequestMapping还支持ANT风格的URL映射
ANT风格支持3种通配符:
? ---匹配一个字符
* ---匹配任意多个字符
** ---匹配多层路径
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- <span style="color:#ff0000;">@RequestMapping("/springmvc")</span>
- @Controller
- public class MyRequestMapping {
- @RequestMapping(value="/RequestMapping/*/cgf")
- public String myRequestMapping(){
- System.out.println("myRequestMapping");
- return "hello";
- }
- }</span>
5:@PathVariable映射URL绑定的占位符,通过@PathVariable可以将URL中的占位符参数绑定到控制器处理方法的入参当中。如:
- @RequestMapping("/myPathVariable/{id}")
- public String myPathVariable(@PathVariable(value="id") int id){
- System.out.println("myPathVariable"+id);
- return "hello";
- }
- <a href="springmvc/myPathVariable/88888888">myPathVariable</a>
6:HiddenHttpMethodFilter 浏览器的FORM表单只支持GET,POST请求,而DELETE,PUT方法并不支持,Spring3.0增加了一个过滤器,可以将POST转化为PUT或DELETE。
首先在WEB.XML文件中配置一个Filter
- <filter>
- <filter-name>HiddenHttpMethodFilter</filter-name>
- <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>HiddenHttpMethodFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
然后在index.jsp中:
- <span style="font-family:SimSun;font-size:18px;"> <a href="springmvc/testRest/1">Get</a>
- <br>
- <form action="springmvc/testRest" method="post">
- <input type="submit" value="post">
- </form>
- <br>
- <form action="springmvc/testRest/1" method="post">
- <input type="hidden" name="_method" value="PUT">
- <input type="submit" value="put">
- </form>
- <br>
- <form action="springmvc/testRest/1" method="post">
- <input type="hidden" name="_method" value="DELETE">
- <input type="submit" value="delete">
- </form></span>
最后在controller中:
- <span style="font-family:SimSun;font-size:18px;"> @RequestMapping(value="/testRest",method=RequestMethod.POST)
- public String myTestRest(){
- System.out.println("myTestRest POST");
- return "hello";
- }
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
- public String myTestRestPut(@PathVariable(value="id") int id){
- System.out.println("myTestRest PUT"+id);
- return "hello";
- }
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
- public String myTestRestDelete(@PathVariable(value="id") int id){
- System.out.println("myTestRest Delete"+id);
- return "hello";
- }
- @RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
- public String myTestRestGet(@PathVariable(value="id") int id){
- System.out.println("myTestRest Get"+id);
- return "hello";
- }</span>
学习SpringMVC(三)之RequestParam
@RequestParam用来映射请求参数
value ---参数名
required---参数是否必须,默认true
defaultValue---默认值
在controller中:
- <span style="font-family:SimSun;font-size:18px;">@RequestMapping(value="springmvc")
- @Controller
- public class MyRequestParam {
- @RequestMapping(value="/testRequestParam")
- public String testRequestParam(@RequestParam(value="username",required=false) String username,
- @RequestParam(value="id",required=false,defaultValue="0") int id){
- System.out.println("testRequestParam:"+username+" "+id);
- return "hello";
- }
- }</span>
- <span style="font-family:SimSun;font-size:18px;"> <a href="springmvc/testRequestParam?username=cgf&&id=1413">testRequestParam</a></span>
学习SpringMVC(四)之使用pojo作为参数
spring MVC会按请求参数名和POJO对象的属性名进行自动匹配,自动为该对象填充属性值。支持级联属性。
在controller中:
- <span style="font-family:SimSun;font-size:18px;">import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import com.cgf.springmvc.entities.User;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyPojo {
- @RequestMapping(value="/testpojo")
- public String testPojo(User user){
- System.out.println("testPojo:"+user);
- return "hello";
- }
- }</span>
在index.jsp中:
- <span style="font-family:SimSun;font-size:18px;"> <form action="springmvc/testpojo" method="post">
- username:<input type="text" name="name" >
- password:<input type="password" name="password">
- province:<input type="text" name="address.province">
- city:<input type="text" name="address.city">
- <input type="submit" value="提交">
- </form></span>
- <span style="font-family:SimSun;font-size:18px;">public class User {
- private String name;
- private String password;
- private Address address;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public Address getAddress() {
- return address;
- }
- public void setAddress(Address address) {
- this.address = address;
- }
- @Override
- public String toString() {
- return "User [name=" + name + ", password=" + password + ", address="
- + address + "]";
- }
- }
- </span>
- <span style="font-family:SimSun;font-size:18px;">public class Address {
- private String city;
- private String province;
- public String getCity() {
- return city;
- }
- public void setCity(String city) {
- this.city = city;
- }
- public String getProvince() {
- return province;
- }
- public void setProvince(String province) {
- this.province = province;
- }
- @Override
- public String toString() {
- return "Address [city=" + city + ", province=" + province + "]";
- }
- }</span>
学习SpringMVC(五)之使用Servlet原生API
可以使用Servlet原生API作为目标方法的入参,具体类型有以下几种:
1.HttpServletRequest
2.HttpServletResponse
3.HttpSession
4.Writer
5.Reader
6.OutputStream
7.InputStream
8.Java.security.Principal
在controller中:
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyServletAPI {
- @RequestMapping(value="testServletAPI")
- public void testServletAPI(HttpServletRequest request,HttpServletResponse response,Writer out) throws IOException{
- System.out.println("testServletAPI"+request+response+out);
- out.write("springmvc testServletAPI");
- //return "hello";
- }
- }
- <a href="springmvc/testServletAPI">Test ServletAPI</a>
学习SpringMVC(六)之ModelAndView
控制器的方法返回值如果是ModelAndView,则其包含视图信息,也包含模型数据信息。
添加模型数据:
- model.addObject(attributeName, attributeValue);
- model.addAllObjects(modelMap)
设置视图:
- void setView(View view)
- void setView(String viewName)
在Controller中:
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyModelAndView {
- @RequestMapping(value="/testModelAndView")
- public ModelAndView testModelAndView(){
- String viewName="success";
- //ModelAndView model=new ModelAndView(viewName);
- ModelAndView model=new ModelAndView();
- model.setViewName(viewName);
- model.addObject("time", new Date());
- return model;
- }
- }
在success.jsp中:
- time:${requestScope.time }
- <br>
- time:${time}
学习SpringMVC(七)之处理模型数据
1.将Map,Model做为方法入参,将其放到请求域(request)
在controller中:
- <span style="font-family:SimSun;font-size:18px;">import java.util.Arrays;
- import java.util.Map;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.SessionAttributes;
- @RequestMapping(value="springmvc")
- @Controller
- public class MyMap {
- public final String viewname="success";
- @RequestMapping(value="testMap")
- public String testMap(Map<String,Object> map,Model model){
- map.put("names", Arrays.asList("CGF","WBJ","2016"));
- model.addAttribute("user", "cgf");
- return viewname;
- }
- }</span>
- <span style="font-family:SimSun;font-size:18px;"> names:${requestScope.names }<br>
- name:${requestScope.user}<br></span>
在index.jsp中:
- <span style="font-family:SimSun;font-size:18px;"> <a href="springmvc/testMap">Test Map</a><br></span>
2.将Map,Model做为方法入参,将其放到会话中(Session)
在Controller中:
- @SessionAttributes(value={"username"},types={String.class})
- @RequestMapping(value="/springmvc")
- @Controller
- public class MySessionAttributes {
- public final String viewname="success";
- @RequestMapping(value="/testSessionAttributes")
- public String testSessionAttributes(Map<String,Object> map){
- User user=new User("cgf", "cgf-2016.5.16");
- map.put("myuser", "myuser");
- map.put("username", user);
- return viewname;
- }
- }
在success.jsp中:
- request user:${requestScope.username }<br>
- session user:${sessionScope.username }<br>
- request user:${requestScope.myuser }<br>
- session user:${sessionScope.myuser }<br>
学习SpringMVC(八)之ModelAttribute
首先,介绍下ModelAttribute的作用:
1.用@ModelAttribute修饰的方法,将再目标方法被调用前进行调用
2.可以解决这样一个问题:用户在提交表单时候,要求可以对用户名进行修改,但是密码不允许修改,这样在提交之后,在目标方法中的入参对象,将自动对用户名进行填充修改,但是这时候发现密码变为NULL,因为没有对密码传值,但是要求密码为原来用户的密码不变。
2.1 可以通过查询数据库的信息,再密码传递过来
2.2 也可以使用@ModelAttribute来解决这个问题
3.下面来看个案例
在index.jsp中:
- <span style="font-family:SimSun;font-size:18px;"><form action="springmvc/testModelAttribute" method="post">
- <input type="hidden" name="id" value="1">
- username:<input type="text" name="name" value="CGF">
- <input type="submit" value="提交">
- </form></span>
在controller中:
- <span style="font-family:SimSun;font-size:18px;">import java.util.Map;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import com.cgf.springmvc.entities.User;
- import com.sun.org.glassfish.gmbal.ParameterNames;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyModelAttribute {
- public final String viewname="success";
- @ModelAttribute
- public void updateUser(@RequestParam(value="id",required=false)Integer id,
- Map<String,Object> map){
- if(id!=null){
- User user=new User(1,"cgf2016", "123456"); //模拟从数据库中获取数据
- System.out.println("模拟从数据库中获取数据:"+user);
- map.put("user", user);
- }
- }
- @RequestMapping(value="/testModelAttribute")
- public String testModelAttribute(User user1){
- System.out.println("testModelAttribute修改后:"+user1);
- return viewname;
- }
- }</span>
注意:map.put("user", user); 中的键user,应该为testModelAttribute(User user1)中的User的首字母小写
4.该案例的运行流程:
4.1 执行@ModelAttribute修饰的方法,把user,放到map当中
4.2 SpringMVC从map中取出User对象,然后把表单的请求参数附给User对象的属性值
4.3 SpringMVC将上述的对象传入目标方法当中
学习SpringMVC(九)之ModelAttribute源码分析
这里以前一章节的内容对ModelAttribute源码进行分析:
注:同学们可以去看下我的前一讲学习SpringMVC(八)之ModelAttribute
1.首先看下第一阶段的断点情况
还未调用ModelAttribute修饰方法前,map值为{}
调用它之后:map值为从数据库中
并将map键值对放到implicitModel中:
最后目标方法的参数数据如下:
2.如何解析目标方法的参数
- <span style="color:#ff0000;">Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel);</span>
因为resolveHandlerArguments方法的代码很多,不好具体找到,所以我在USER类中的setName()上加了一个断点,便于分析
源码分析流程:
1.调用@ModelAttribute修饰的方法,实际上是把map中的键值对放入到implicitModel当中
2.解析请求处理器的目标参数,实际上该目标参数来自于WebDataBinder对象的target属性
2.1 创建WebDataBinder对象时,需要先确定它的两个属性:target,objectName
下图中,name对应objectName,target对应bindObject
2.1.1 确定objectName属性:
若传入的attrName属性值为“ ”,则objectName为类名第一个字母小写,
若有属性值,则objectName为@modelAttribute的value属性值
2.1.2 确定target属性:
在implicitModel中查找attrName的键名,如果有,则取出返回。如果没有,则
验证当前的controller是否用了@sessionAttribute来修饰,若使用了,则尝试从
session中,获取attrName对应的属性值,若有,则取出,若无,则抛出异常;若
当前controller没有用@sessionAttribute修饰,则通过反射机制创建一个,
WebDataBinder对象。
返回WebDataBinder对象binder
在调用doBind(binder, webRequest, validate, validationHints, !assignBindingResult)之前,binder的
target属性为原来数据库的
在调用doBind(binder, webRequest, validate, validationHints, !assignBindingResult)之后,
binder的target属性为修改后的
学习SpringMVC(十)之确定目标方法POJO类型参数
1. 确定一个 key:
1). 若目标方法的 POJO 类型的参数木有使用 @ModelAttribute 作为修饰, 则 key 为 POJO 类名第一个字母的小写
2). 若使用了 @ModelAttribute 来修饰, 则key 为 @ModelAttribute 注解的 value 属性值.
2. 在 implicitModel 中查找 key 对应的对象, 若存在, 则作为入参传入
1). 若在 @ModelAttribute 标记的方法中在 Map 中保存过, 且 key 和 1 确定的 key 一致, 则会获取到.3. 若 implicitModel 中不存在 key 对应的对象, 则检查当前的 Handler 是否使用 @SessionAttributes 注解修饰,
若使用了该注解, 且 @SessionAttributes 注解的 value 属性值中包含了 key, 则会从 HttpSession 中来获取 key 所
对应的 value 值, 若存在则直接传入到目标方法的入参中. 若不存在则将抛出异常.
4. 若 Handler 没有标识 @SessionAttributes 注解或 @SessionAttributes 注解的 value 值中不包含 key, 则
会通过反射来创建 POJO 类型的参数, 传入为目标方法的参数
5. SpringMVC 会把 key 和 POJO 类型的对象保存到 implicitModel 中, 进而会保存到 request 中.
学习SpringMVC(十一)之视图和视图解析器
SpringMVC用于处理视图最重要的两个接口是ViewResolver和View。ViewResolver的主要作用是把一个逻辑上的视图名称解析为一个真正的视图,View接口的主要作用是用于处理视图,然后返回给客户端。
spring为我们提供了非常多的视图解析器,下面将列举一些视图解析器。
AbstractCachingViewResolver:这是一个抽象类,这种视图解析器会把它曾经解析过的视图保存起来,然后每次要解析视图的时候先从缓存里面找,如果找到了对应的视图就直接返回,如果没有就创建一个新的视图对象,然后把它放到一个用于缓存的map中,接着再把新建的视图返回。使用这种视图缓存的方式可以把解析视图的性能问题降到最低。
UrlBasedViewResolver:它继承了AbstractCachingViewResolver,主要就是提供的一种拼接URL的方式来解析视图,它可以让我们通过prefix属性指定一个指定的前缀,通过suffix属性指定一个指定的后缀,然后把返回的逻辑视图名称加上指定的前缀和后缀就是指定的视图URL了。如prefix=/WEB-INF/jsps/,suffix=.jsp,返回的视图名称viewName=test/indx,则UrlBasedViewResolver解析出来的视图URL就是/WEB-INF/jsps/test/index.jsp。默认的prefix和suffix都是空串。
URLBasedViewResolver支持返回的视图名称中包含redirect:前缀,这样就可以支持URL在客户端的跳转,如当返回的视图名称是”redirect:test.do”的时候,URLBasedViewResolver发现返回的视图名称包含”redirect:”前缀,于是把返回的视图名称前缀”redirect:”去掉,取后面的test.do组成一个RedirectView,RedirectView中将把请求返回的模型属性组合成查询参数的形式组合到redirect的URL后面,然后调用HttpServletResponse对象的sendRedirect方法进行重定向。
同样URLBasedViewResolver还支持forword:前缀,对于视图名称中包含forword:前缀的视图名称将会被封装成一个InternalResourceView对象,然后在服务器端利用RequestDispatcher的forword方式跳转到指定的地址。 使用UrlBasedViewResolver的时候必须指定属性viewClass,表示解析成哪种视图,一般使用较多的就是InternalResourceView,利用它来展现jsp,但是当我们使用JSTL的时候我们必须使用JstlView。
下面是一段UrlBasedViewResolver的定义,根据该定义,当返回的逻辑视图名称是test的时候,UrlBasedViewResolver将把逻辑视图名称加上定义好的前缀和后缀,即“/WEB-INF/test.jsp”,然后新建一个viewClass属性指定的视图类型予以返回,即返回一个url为“/WEB-INF/test.jsp”的InternalResourceView对象。
- <bean
- class="org.springframework.web.servlet.view.UrlBasedViewResolver">
- <property name="prefix" value="/WEB-INF/" />
- <property name="suffix" value=".jsp" />
- <property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
- </bean>
InternalResourceViewResolver:它是URLBasedViewResolver的子类,所以URLBasedViewResolver支持的特性它都支持。在实际应用中InternalResourceViewResolver也是使用的最广泛的一个视图解析器。那么InternalResourceViewResolver有什么自己独有的特性呢?单从字面意思来看,我们可以把InternalResourceViewResolver解释为内部资源视图解析器,这就是InternalResourceViewResolver的一个特性。InternalResourceViewResolver会把返回的视图名称都解析为InternalResourceView对象,InternalResourceView会把Controller处理器方法返回的模型属性都存放到对应的request属性中,然后通过RequestDispatcher在服务器端把请求forword重定向到目标URL。
我们都知道存放在/WEB-INF/下面的内容是不能直接通过request请求的方式请求到的,为了安全性考虑,我们通常会把jsp文件放在WEB-INF目录下,而InternalResourceView在服务器端跳转的方式可以很好的解决这个问题。
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/"/>
- <property name="suffix" value=".jsp"></property>
- </bean>
请求处理方法调用完成后,最终返回一个ModelAndView对象,对于那些返回String,View或ModelMap等类型的处理方法,SpirngMVC也会在内部将它们装配成一个ModelAndView对象,它包含了逻辑名和模型对象的视图。通过视图解析器(ViewResolver)得到真正的物理视图(View对象), 比如在InternalResourceViewResolver中定义了prefix=/WEB-INF/,suffix=.jsp,然后请求的Controller处理器方法返回的视图名称为test,InternalResourceViewResolver会给它加上定义好的前缀和后缀,组成“/WEB-INF/test.jsp”的形式,然后把它当做一个InternalResourceView的url新建一个InternalResourceView对象返回,先把返回的模型属性都存放到对应的HttpServletRequest属性中,然后利用RequestDispatcher在服务器端把请求forword到/WEB-INF/test.jsp
学习SpringMVC(十二)之mvc:view-controller标签
mvc:view-controller标签作用:
配置直接转发页面,可以直接相应转发的页面,而无须再经过Handler方法
例子:
在index.jsp中:
- <span style="font-family:SimSun;font-size:18px;"><a href="success">success</a></span>
在springmvc.xml中配置:
- <span style="font-family:SimSun;font-size:18px;"><mvc:view-controller path="/success" view-name="success"/></span>
- <span style="font-family:SimSun;font-size:18px;"><mvc:annotation-driven/></span>
学习SpringMVC(十三)之BeanNameViewResolver视图解析器
这里我将配置一个BeanNameViewResolver视图解析器,使用视图名称来解析视图
注意点:
在springmvc.xml文件中如果有多个视图解析器,可以进行优先级的设置,order 值越小优先级越高
- <span style="font-family:SimSun;font-size:18px;"><!-- 配置一个BeanNameViewResolver视图解析器,使用视图名称来解析视图 -->
- <bean class="org.springframework.web.servlet.view.BeanNameViewResolver">
- <property name="order" value="10" />
- </bean>
- <!-- 配置视图解析器 --><!--该视图解析器的order值为Integer.MAX_VALUE -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean></span>
- <span style="font-size:18px;">package com.cgf.springmvc.view;
- import java.util.Date;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.View;
- @Component
- public class HelloView implements View{
- public String getContentType() {
- // TODO Auto-generated method stub
- return "text/html";
- }
- public void render(Map<String, ?> model, HttpServletRequest request,
- HttpServletResponse response) throws Exception {
- // TODO Auto-generated method stub
- response.getWriter().print("Welcome to View:"+new Date());
- }
- }</span>
- <span style="font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyView {
- @RequestMapping(value="/testMyView")
- public String testView(){
- System.out.println("testView");
- <strong><span style="color:#000099;">return "helloView";</span></strong>
- }
- }</span>
3.在index.jsp中:
- <span style="font-size:18px;"><a href="springmvc/testMyView">Test MyView</a><br></span>
学习SpringMVC(十四)之关于重定向
一般情况下,contrller方法返回的字符串的值会被当成逻辑视图名处理。
但是如果返回的字符串中带forward:或redirect:前缀时,SpringMVC会对他们进行特殊处理,将forward:和redirect:当成指示符,其后字符串作为URL来处理
例如:
forward:/index.jsp 将会完成一个到index.jsp页面的转发操作
redirect:/index.jsp 将会完成一个到index.jsp页面的重定向操作
在controller中:
- package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyRedirect {
- @RequestMapping(value="/testMyRedirect")
- public String testMyRedirect(){
- System.out.println("testMyRedirect");
- return "redirect:/index.jsp";
- }
- }
- <a href="springmvc/testMyRedirect">Test MyRedirect</a><br>
学习SpringMVC(十五)之CRUD操作
使用SpringMVC完成相应的CRUD操作,静态数据来模仿从数据库中取数据。
下面从创建的类说起,一共定义了5个类,分类是DepartmentDao,EmployeeDao,Department,Employee,EmployeeHandler
代码如下:
- package com.cgf.springmvc.crud.dao;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Repository;
- import com.cgf.springmvc.crud.entities.Department;
- import com.cgf.springmvc.crud.entities.Employee;
- @Repository
- public class EmployeeDao {
- private static Map<Integer, Employee> employees = null;
- @Autowired
- private DepartmentDao departmentDao;
- static{
- employees = new HashMap<Integer, Employee>();
- employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
- employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
- employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
- employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
- employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
- }
- private static Integer initId = 1006;
- public void save(Employee employee){
- if(employee.getId() == null){
- employee.setId(initId++);
- }
- employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
- employees.put(employee.getId(), employee);
- }
- public Collection<Employee> getAll(){
- return employees.values();
- }
- public Employee get(Integer id){
- return employees.get(id);
- }
- public void delete(Integer id){
- employees.remove(id);
- }
- }
- package com.cgf.springmvc.crud.dao;
- import java.util.Collection;
- import java.util.HashMap;
- import java.util.Map;
- import org.springframework.stereotype.Repository;
- import com.cgf.springmvc.crud.entities.Department;
- @Repository
- public class DepartmentDao {
- private static Map<Integer, Department> departments = null;
- static{
- departments = new HashMap<Integer, Department>();
- departments.put(101, new Department(101, "D-AA"));
- departments.put(102, new Department(102, "D-BB"));
- departments.put(103, new Department(103, "D-CC"));
- departments.put(104, new Department(104, "D-DD"));
- departments.put(105, new Department(105, "D-EE"));
- }
- public Collection<Department> getDepartments(){
- return departments.values();
- }
- public Department getDepartment(Integer id){
- return departments.get(id);
- }
- }
- package com.cgf.springmvc.crud.entities;
- public class Department {
- private Integer id;
- private String departmentName;
- public Department() {
- // TODO Auto-generated constructor stub
- }
- public Department(int i, String string) {
- this.id = i;
- this.departmentName = string;
- }
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getDepartmentName() {
- return departmentName;
- }
- public void setDepartmentName(String departmentName) {
- this.departmentName = departmentName;
- }
- @Override
- public String toString() {
- return "Department [id=" + id + ", departmentName=" + departmentName
- + "]";
- }
- }
- package com.cgf.springmvc.crud.entities;
- import java.util.Date;
- import javax.validation.constraints.NotNull;
- import org.hibernate.validator.constraints.Email;
- import org.hibernate.validator.constraints.NotEmpty;
- import org.springframework.format.annotation.DateTimeFormat;
- import org.springframework.format.annotation.NumberFormat;
- public class Employee {
- private Integer id;
- @NotNull
- private String lastName;
- private String email;
- //1 male, 0 female
- private Integer gender;
- private Department department;
- @DateTimeFormat(pattern="yyyy-MM-dd")
- private Date birth;
- @NumberFormat(pattern="#,###,###.#")
- private Float salary;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getLastName() {
- return lastName;
- }
- public void setLastName(String lastName) {
- this.lastName = lastName;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public Integer getGender() {
- return gender;
- }
- public void setGender(Integer gender) {
- this.gender = gender;
- }
- public Department getDepartment() {
- return department;
- }
- public void setDepartment(Department department) {
- this.department = department;
- }
- public Date getBirth() {
- return birth;
- }
- public void setBirth(Date birth) {
- this.birth = birth;
- }
- public Float getSalary() {
- return salary;
- }
- public void setSalary(Float salary) {
- this.salary = salary;
- }
- @Override
- public String toString() {
- return "Employee [id=" + id + ", lastName=" + lastName + ", email="
- + email + ", gender=" + gender + ", department=" + department
- + ", birth=" + birth + ", salary=" + salary + "]";
- }
- public Employee(Integer id, String lastName, String email, Integer gender,
- Department department) {
- super();
- this.id = id;
- this.lastName = lastName;
- this.email = email;
- this.gender = gender;
- this.department = department;
- }
- public Employee() {
- // TODO Auto-generated constructor stub
- }
- }
- package com.cgf.springmvc.crud.handlers;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import com.cgf.springmvc.crud.dao.DepartmentDao;
- import com.cgf.springmvc.crud.dao.EmployeeDao;
- import com.cgf.springmvc.crud.entities.Employee;
- @RequestMapping(value="/springmvc")
- @Controller
- public class EmployeeHandler {
- @Autowired
- private EmployeeDao employeeDao;
- @Autowired
- private DepartmentDao departmentDao;
- @RequestMapping(value="/list")
- public String emps(Map<String,Object> map){
- map.put("emplists", employeeDao.getAll());
- return "list";
- }
- @RequestMapping(value="/addUi",method=RequestMethod.GET)
- public String empsAddUI(Map<String,Object> map){
- map.put("department", departmentDao.getDepartments());
- map.put("employee", new Employee());
- return "input";
- }
- @RequestMapping(value="/add",method=RequestMethod.POST)
- public String empsAdd(Employee employee,Map<String,Object> map){
- employeeDao.save(employee);
- //map.put("emplists", employeeDao.getAll());
- return "redirect:list";
- }
- @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
- public String empsDelete(@PathVariable("id")Integer id,Map<String,Object> map){
- employeeDao.delete(id);
- map.put("emplists", employeeDao.getAll());
- return "list";
- }
- @RequestMapping(value="/EditUi/{id}",method=RequestMethod.GET)
- public String empsEditUI(@PathVariable("id")Integer id,Map<String,Object> map){
- map.put("department", departmentDao.getDepartments());
- map.put("employee", employeeDao.get(id));
- return "input";
- }
- @ModelAttribute
- public void emps(@RequestParam(value="id",required=false)Integer id,Map<String,Object> map){
- if(id!=null){
- map.put("employee", employeeDao.get(id));
- }
- }
- @RequestMapping(value="/add",method=RequestMethod.PUT)
- public String empsEdit(Employee employee,Map<String,Object> map){
- employeeDao.save(employee);
- map.put("emplists", employeeDao.getAll());
- return "list";
- }
- }
- <h2>SpringMVC CRUD</h2>
- <a href="springmvc/list">显示所有员工信息</a>
- <form:form action="springmvc/add" method="POST" modelAttribute="employee">
- <c:if test="${employee.id==null }">
- LastName:<form:input path="lastName"/> <br>
- </c:if>
- <c:if test="${employee.id!=null }">
- <form:hidden path="id"/>
- <input type="hidden" name="_method" value="PUT">
- </c:if>
- Email:<form:input path="email"/>
- <form:errors path="email"></form:errors><br>
- <%
- Map<String,String> genders=new HashMap();
- genders.put("1", "Male");
- genders.put("0","Female");
- request.setAttribute("genders", genders);
- %>
- Gender:<form:radiobuttons path="gender" items="${genders }"/><br>
- Department:<form:select path="department.id"
- items="${department}" itemLabel="departmentName" itemValue="id"></form:select>
- <input type="submit" value="Submit" />
- </form:form>
- <span style="font-family:SimSun;"><span style="font-size:18px;"><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'list.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
- <script type="text/javascript">
- $(function(){
- $(".delete").click(function(){
- var href=$(this).attr("href");
- $("form").attr("action",href).submit();
- return false;
- });
- })
- </script>
- </head>
- <body>
- <form action="" method="post">
- <input type="hidden" name="_method" value="DELETE">
- </form>
- <c:if test="${empty requestScope.emplists }">
- 没有任何员工信息
- </c:if>
- <c:if test="${!empty requestScope.emplists }">
- <table border="1">
- <tr>
- <th>ID</th>
- <th>LastName</th>
- <th>Email</th>
- <th>Gender</th>
- <th>Department</th>
- <th>Edit</th>
- <th>Delete</th>
- </tr>
- <c:forEach items="${requestScope.emplists}" var="emps">
- <tr>
- <td>${emps.id }</td>
- <td>${emps.lastName}</td>
- <td>${emps.email }</td>
- <td>${emps.gender==0 ? 'Female':'male'}</td>
- <td>${emps.department.departmentName }</td>
- <td><a href="springmvc/EditUi/${emps.id}">Edit</a></td>
- <td><a class="delete" href="springmvc/delete/${emps.id}">Delete</a></td>
- </tr>
- </c:forEach>
- </table>
- </c:if>
- <a href="springmvc/addUi">添加员工信息</a>
- </body>
- </html></span>
- </span>
对静态资源的处理,需要在spring.xml文件中配置<mvc:default-servlet-handler/>default-servlet-handler将在 SpringMVC 上下文中定义一个 DefaultServletHttpRequestHandler,它会对进入DispatcherServlet的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由WEB应用服务器默认的Servlet 处理. 如果不是静态资源的请求,才由 DispatcherServlet 继续处理
学习SpringMVC(十六)之数据绑定流程
1.SpringMVC主框架将ServletRequest对象及目标方法的入参实例传递给WebDataBinderFactory实例,以创建DataBinder实例对象
2.DataBinder调用装配在SpringMVC上下文中的ConversionService组件进行数据类型转换、数据格式化工作。将Servlet中的请求信息填充到入参对象中
3.调用Validator组件对已经绑定了请求消息的入参对象进行数据合法性校验,并最终生成数据绑定结果。
4.SpringMVC抽取BindingResult中的入参对象和校验错误对象,将它们赋给处理方法的响应入参。
我在38行打了一个断点,来看数据绑定流程
学习SpringMVC(十七)之自定义类型转换器
本节的主要内容就是将表单提交的字符串转化为对象
在index.jsp中:
- <span style="font-size:18px;"><h2>SpringMVC 自定义转换器</h2>
- <form action="springmvc/testConversion">
- Employee:<input type="text" name="employee">
- <input type="submit" value="提交">
- </form></span>
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import java.util.Map;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import com.cgf.springmvc.crud.dao.EmployeeDao;
- import com.cgf.springmvc.crud.entities.Employee;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyConversion {
- @Autowired
- private EmployeeDao employeeDao;
- @RequestMapping(value="/testConversion")
- public String testConversion(@RequestParam(value="employee")Employee employee,
- Map<String,Object> map){
- employeeDao.save(employee);
- //map.put("emplists", employeeDao.getAll());
- return "redirect:list";
- }
- }</span>
- package com.cgf.springmvc.conversion;
- import org.springframework.core.convert.converter.Converter;
- import org.springframework.stereotype.Component;
- import com.cgf.springmvc.crud.entities.Department;
- import com.cgf.springmvc.crud.entities.Employee;
- @Component
- public class MyConversionService implements Converter<String,Employee>{
- public Employee convert(String source) {
- // TODO Auto-generated method stub
- //cgf-cgf@sina.com-0-105
- if(source!=null){
- String []args=source.split("-");
- if(args!=null&&args.length==4){
- String lastName=args[0];
- String email=args[1];
- int gender=Integer.parseInt(args[2]);
- Department department=new Department();
- department.setId(Integer.parseInt(args[3]));
- Employee e=new Employee(null, lastName, email, gender, department);
- System.out.println(source+"--conversion--"+e);
- return e;
- }
- }
- return null;
- }
- }
- <bean name="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
- <property name="converters">
- <set>
- <ref bean="myConversionService"></ref>
- </set>
- </property>
- <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
学习SpringMVC(十八)之JSR303数据校验
JSR303是Java为Bean数据合法性校验提供的标准框架
hibernate Validator是JSR 303的一个参考实现,除支持所有标准的校验注解外,它
还支持以下的扩展注解
@Email @Length @NotEmpty @Range
校验步骤:
①.使用 JSR 303 验证标准
②.加入 hibernate validator 验证框架的 jar 包③.在 SpringMVC 配置文件中添加 <mvc:annotation-driven />,它会默认装配好一个
LocalValidatorFactoryBean,通过在处理方法的入参上标注@Valid注解,就可以未完成数据绑定后执行数据校验的工作
④.需要在 bean 的属性上添加对应的注解⑤.在目标方法 bean 类型的前面添加 @Valid 注解
2).验证出错转向到哪一个页面 ?
注意: 需校验的 Bean 对象和其绑定结果对象或错误对象时成对出现的,它们之间不允许声明其他的入参
- <span style="color:#009900;">@RequestMapping(value="/add",method=RequestMethod.POST)
- public String empsAdd(</span><span style="background-color: rgb(255, 255, 255);"><span style="color:#ff0000;">@Valid Employee employee,Errors result</span></span><span style="color:#ff0000;">,Map<String,Object> map</span><span style="color:#009900;">){
- //map.put("emplists", employeeDao.getAll());
- if(result.getErrorCount()>0){
- System.out.println("出错啦");
- for(FieldError error:result.getFieldErrors()){
- System.out.println(error.getField()+error.getDefaultMessage());
- }
- map.put("department", departmentDao.getDepartments());
- return "input";
- }
- employeeDao.save(employee);
- return "redirect:list";
- }</span>
学习SpringMVC(十九)之显示错误消息和国际化
一.在页面显示错误消息:如要显示email的错误或显示全部的错误
- <span style="font-family:SimSun;font-size:24px;"><form:errors path="email"></form:errors></span>
- <span style="font-family:SimSun;font-size:24px;"><form:errors path="*"></form:errors>
- </span>
1.配置国际化资源文件i18n.properties
2.在springmvc.xml中配置ResourceBundleMessageSource
- <!-- 配置国际资源化文件 -->
- <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basename" value="i18n"></property>
- </bean>
学习SpringMVC(二十)之返回JSON
首先要加入三个JAR包:
其次在Controller中:
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import java.util.Collection;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- import com.cgf.springmvc.crud.dao.EmployeeDao;
- import com.cgf.springmvc.crud.entities.Employee;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyJson {
- @Autowired
- private EmployeeDao employeeDao;
- <span style="color:#ff0000;">@ResponseBody</span>
- @RequestMapping(value="/testJSON")
- public Collection<Employee> testJson(){
- return employeeDao.getAll();
- }
- }</span>
- <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
- <script type="text/javascript">
- $(function(){
- $("#test_json").click(function(){
- var url=this.href;
- var args={};
- $.post(url,args,function(data){
- for(var i=0;i<data.length;i++){
- var id=data[i].id;
- var lastName=data[i].lastName;
- alert(id+"---"+lastName);
- }
- });
- return false;
- });
- })
- </script>
- <h2>SpringMVC JSON</h2>
- <a href="springmvc/testJSON" id="test_json">Test Json</a><br>
学习SpringMVC(二十一)之通过超链接切换Locale
1.配置国际化文件
2.在springmvc.xml中:
- <span style="font-family:SimSun;font-size:18px;"><!-- 配置国际资源化文件 -->
- <bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basename" value="i18n"></property>
- </bean>
- <bean name="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
- <!-- 装配拦截器 -->
- <mvc:interceptors>
- <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
- </mvc:interceptors></span>
- <!-- 配置直接转发页面 -->
- <!-- 可以直接相应转发的页面,而无须再经过Handler方法 -->
- <mvc:view-controller path="/i18n" view-name="i18n1"/>
- <mvc:view-controller path="/i18n1" view-name="i18n2"/>
- <span style="font-family:SimSun;font-size:18px;"> <fmt:message key="i18n.password"></fmt:message>
- <a href="i18n">I18N1 PAGE</a>
- <br><br>
- <a href="i18n1?locale=zh_CH">中文</a>
- <br><br>
- <a href="i18n1?locale=en_US">英文</a></span>
学习SpringMVC(二十二)之文件上传
文件上传的步骤:
1.在index.jsp中写一个表单:
- <span style="font-family:SimSun;font-size:24px;"> <form action="springmvc/testFileUpload" method="POST" <span style="color:#ff0000;">enctype="multipart/form-data"></span>
- File: <input type="file" name="file"/>
- Desc: <input type="text" name="desc"/>
- <input type="submit" value="Submit"/>
- </form></span>
2.写一个controller:
- <span style="font-family:SimSun;font-size:24px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyTestFileUpload {
- @RequestMapping(value="/testFileUpload")
- public String testFileUpload(<span style="color:#ff0000;">@RequestParam(value="file")MultipartFile file,</span>
- @RequestParam(value="desc")String desc){
- System.out.println(desc);
- System.out.println("file name:"+file.getOriginalFilename());
- return "success";
- }
- }</span>
- <span style="font-family:SimSun;font-size:24px;"><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="UTF-8"></property>
- <property name="maxUploadSize" value="1024000"></property>
- </bean></span>
学习SpringMVC(二十三)之拦截器相关
1.自定义一个拦截器的步骤:
第一步,创建一个类实现HandlerInterceptor接口
- <span style="font-size:24px;">package com.cgf.springmvc.interceptors;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.web.servlet.HandlerInterceptor;
- import org.springframework.web.servlet.ModelAndView;
- public class MySecondInterceptors implements HandlerInterceptor{
- <span style="color:#ff0000;">/**
- * 在渲染视图之后被调用;
- * 可以用来释放资源
- */</span>
- public void afterCompletion(HttpServletRequest arg0,
- HttpServletResponse arg1, Object arg2, Exception arg3)
- throws Exception {
- // TODO Auto-generated method stub
- System.out.println("MySecondInterceptors afterCompletion");
- }
- <span style="color:#ff0000;">/**
- * 该方法在目标方法调用之后,渲染视图之前被调用;
- * 可以对请求域中的属性或视图做出修改
- *
- */</span>
- public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
- Object arg2, ModelAndView arg3) throws Exception {
- // TODO Auto-generated method stub
- System.out.println("MySecondInterceptors postHandle");
- }
- <span style="color:#ff0000;">/**
- * 可以考虑作权限,日志,事务等等
- * 该方法在目标方法调用之前被调用;
- * 若返回TURE,则继续调用后续的拦截器和目标方法
- * 若返回FALSE,则不会调用后续的拦截器和目标方法
- *
- */</span>
- public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
- Object arg2) throws Exception {
- // TODO Auto-generated method stub
- System.out.println("MySecondInterceptors preHandle");
- return true;
- }
- }
- </span>
<mvc:interceptors>,如果在其中配置了<mvc:interceptor>,则可以指定拦截器的路径
- <span style="font-size:24px;"><!-- 装配拦截器 -->
- <mvc:interceptors>
- <bean class="com.cgf.springmvc.interceptors.MyInterceptors"></bean>
- <mvc:interceptor>
- <mvc:mapping path="/springmvc/testFileUpload"/>
- <bean class="com.cgf.springmvc.interceptors.MySecondInterceptors"></bean>
- </mvc:interceptor>
- <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
- </mvc:interceptors></span>
多个拦截器的执行顺序
学习SpringMVC(二十四)之异常处理
SpringMVC通过HandlerExceptionResolver处理程序的异常,包括Handler映射,数据绑定以及目标方法执行时发生的异常。
1.在@ExceptionHandler 方法的入参中可以加入 Exception 类型的参数, 该参数即对应发生的异常对象
2.@ExceptionHandler方法的入参中不能传入 Map.若希望把异常信息传导页面上,需要使用 ModelAndView作为返回值3.@ExceptionHandler 方法标记的异常有优先级的问题.会先处理匹配度高的异常
直接上实例:
在Controller中:
- <span style="font-size:18px;"><span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.servlet.ModelAndView;
- @RequestMapping(value="/springmvc")
- @Controller
- public class MyException {
- <span style="color:#ff0000;">@ExceptionHandler(value={Exception.class})</span>
- public ModelAndView myException(Exception ex){
- ModelAndView mv=new ModelAndView("error");
- mv.addObject("exception", ex);
- return mv;
- }
- @RequestMapping(value="/testException")
- public String testException(@RequestParam(value="id")int id){
- System.out.println("id=:"+10/id);
- return "success";
- }
- }</span></span>
在index.jsp中;
- <span style="font-size:18px;"><span style="font-family:SimSun;"> <h1>异常处理</h1>
- <a href="springmvc/testException?id=1">Test Exception</a>
- <br></span></span>
则将去@ControllerAdvice 标记的类中查找 @ExceptionHandler 标记的方法来处理异常.
- <span style="font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.servlet.ModelAndView;
- <span style="background-color: rgb(255, 255, 255);"><span style="color:#ff0000;">@ControllerAdvice</span></span>
- public class MyArithmeticException {
- @ExceptionHandler(value={ArithmeticException.class})
- public ModelAndView myException(Exception ex){
- System.out.println("MyArithmeticException");
- ModelAndView mv=new ModelAndView("error");
- mv.addObject("exception", ex);
- return mv;
- }
- }</span>
5.ResponseStatusExceptionResolver处理用@ResponseStatus标识的异常类或异常方法
- <span style="font-family:SimSun;font-size:18px;">package com.cgf.springmvc.handlers;
- import org.springframework.http.HttpStatus;
- import org.springframework.web.bind.annotation.ResponseStatus;
- @ResponseStatus(reason="用户名与密码不匹配",value=HttpStatus.FORBIDDEN)
- public class UserNameNotMatchPasswordException extends RuntimeException{
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- }</span>
6.配置SimpleMappingExceptionResolver来映射异常
- <bean id="simpleMappingExceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionAttribute" value="exception"></property>
- <property name="exceptionMappings">
- <props>
- <!-- 全限定名、视图名 -->
- <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
- </props>
- </property>
- </bean>
学习SpringMVC(二十五)之SpringMVC运行流程
1.请求发送给在WEB.XML中配置的DispatcherServlet
2.查找SpringMVC中是否存在相应的映射
2.1如果不存在,则看配置文件中是否配置了<mvc:default-servlet-handler/>。若配置了,则去调用相应的目标资源;若无,则返回404页面,控制台打印:
2.2如果存在,则通过HandlerMapping,获取HandlerExcecutionChain对象
3.获取HandlerAdapter对象
4.之后通过HandlerExcecutionChain对象调用拦截器的preHandle方法,再由HandlerAdapter对象,调用目标方法得到ModelAndView对象,之后调用postHandle方法,如果有异常,则通过异常解析器,处理异常,获取新的ModelAndView对象
5.再由视图解析器得到View,渲染视图,最后调用afterCompletion方法
- 学习SpringMVC(一-1-2-25)
- SpringMVC学习笔记一
- springMVC学习(一)
- SpringMVC学习总结(一)
- SpringMVC学习(一)
- SpringMvc学习笔记一
- SpringMVC学习(一)
- springmvc 学习(一)
- SpringMVC学习(一)
- SpringMVC学习(一)
- SpringMVC学习(一)
- springmvc学习(一)
- SpringMVC学习笔记一
- springmvc学习(一) 图解SpringMVC整体流程
- springMVC学习(一)springMVC简介
- springMVC学习笔记(一)-----springMVC原理
- SpringMVC架构---SpringMVC学习笔记(一)
- SpringMVC学习总结(一).初探SpringMVC
- 第十五周项目一 阅读下面程序,解释运行结果(5)
- 11.1节练习
- Gensee移动SDK之(一)结构组成
- Implement Queue using Stacks
- 第十五周项目-阅读程序-4
- 学习SpringMVC(一-1-2-25)
- 运动目标检测--三种方法比较
- 机器视觉开源代码集合-2
- 解决spark缺少winutils.exe的问题
- 非3D Touch的设备上模拟Peek Preview效果
- stm32中GPIO端口的输出配置例子
- Codeforces Beta Round #3
- JAVA反射机制
- C++第7次作业