------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------
本案例是上面的异常和日期类型转换结合的一个小小的Demo
案例开始
1.自定义处理器和处理方法:
package cn.dawn.day19typeconverter; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * Created by Dawn on 2018/3/28. */ @Controller public class TypeConverterController { /*作用于这俩个*/ @ExceptionHandler public ModelAndView resolveException(Exception ex, HttpServletRequest request) { ModelAndView modelAndView=new ModelAndView(); /*给username回显*/ modelAndView.addObject("username",request.getParameter("username")); /*返回的异常对象*/ modelAndView.addObject("ex",ex); /*发生异常返回登陆页*/ modelAndView.setViewName("login"); return modelAndView; } /*做日期类型*/ @RequestMapping("/dateconverter1") public String dateconverter1(String username, Integer userage, Date birthday) throws Exception { System.out.println(username); System.out.println(userage); System.out.println(birthday); return "success"; } }
2.自己的xml大配置文件:
<?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:mvc="http://www.springframework.org/schema/mvc" 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/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"> <!--包扫描器--> <context:component-scan base-package="cn.dawn.day19typeconverter"></context:component-scan> <!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/day19/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
3.修改web.xml中央调度器的上下文配置位置为上面那个xml
4.jsp页面:
4.1login.jsp
<%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h2>登录</h2> <form action="${pageContext.request.contextPath}/dateconverter1" method="post"> 用户名:<input name="username" value="${username}"> 年龄:<input name="userage"> 生日:<input name="birthday"> <input type="submit" value="登录"/> </form> </body> </html>
4.2success.jsp
<%@ page language="java" pageEncoding="utf-8" isELIgnored="false" %> <html> <body> <%--<img src="image/1.jpg">--%> <h2>Success!</h2> </body> </html>
结论:什么时候跳到成功页面?就是日期格式不出错,日期格式必须为yyyy/MM/dd,SpringMVC默认的自动转换日期格式必须传入的是这个
下篇博客就做自定义类型转换器