SpringMvc 视图解析器常见功能、类型转换、格式化
springmvc.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:aop="http://www.springframework.org/schema/aop"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
- 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.3.xsd
- http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
- <!-- 扫描 有注解的包 -->
- <context:component-scan base-package="handler"></context:component-scan>
- <!--配置视图解析器(InternalResourceViewResolver) -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/views/"></property>
- <property name="suffix" value=".jsp"></property>
- </bean>
- <!--view-name会被视图解析器 加上前缀、后缀 -->
- <mvc:view-controller path="handler/testMvcViewController" view-name="success"/>
- <!-- 该注解 会让 springmvc: 接收一个请求,并且该请求 没有对应的@requestmapping时,将该请求 交给服务器默认的servlet去处理(直接访问) -->
- <mvc:default-servlet-handler></mvc:default-servlet-handler>
- <!-- 1将 自定义转换器 纳入SpringIOC容器 -->
- <bean id="myConverter" class="converter.MyConverter"></bean>
- <!-- 2将myConverter再纳入 SpringMVC提供的转换器Bean
- <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
- <property name="converters">
- <set>
- <ref bean="myConverter"/>
- </set>
- </property>
- </bean>
- -->
- <!-- 3将conversionService注册到annotation-driven中 -->
- <!--此配置是SpringMVC的基础配置,很功能都需要通过该注解来协调 -->
- <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
- <!-- 配置 数据格式化 注解 所依赖的bean FormattingConversionServiceFactoryBean:既可以实现格式化、又可以实现类型转换 -->
- <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
- <property name="converters">
- <set>
- <ref bean="myConverter"/>
- </set>
- </property>
- </bean>
- </beans>
web.xml
- <?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_3_1.xsd"
- version="3.1">
- <servlet>
- <servlet-name>springDispatcherServlet</servlet-name>
- <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>springDispatcherServlet</servlet-name>
- <url-pattern>/</url-pattern>
- </servlet-mapping>
- <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>
- </web-app>
SpringMvcHandler
- package handler;
- import java.util.Map;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import entity.Address;
- import entity.Student;
- import org.springframework.stereotype.Controller;
- import org.springframework.ui.Model;
- import org.springframework.ui.ModelMap;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.FieldError;
- import org.springframework.web.bind.annotation.CookieValue;
- import org.springframework.web.bind.annotation.ModelAttribute;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestHeader;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.SessionAttributes;
- import org.springframework.web.servlet.ModelAndView;
- //接口/类 注解 配置
- //@SessionAttributes(value="student4") //如果要在request中存放student4对象,则同时将该对象 放入session域中
- //@SessionAttributes(types= {Student.class,Address.class}) //如果要在request中存放Student类型的对象,则同时将该类型对象 放入session域中
- @Controller
- @RequestMapping(value = "handler") //映射
- public class SpringMVCHandler {
- @RequestMapping(value = "welcome", method = RequestMethod.POST, params = {"name=zs", "age!=23", "!height"})//映射
- public String welcome() {
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "welcome2", headers = {"Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Encoding=gzip, deflate"})
- public String welcome2() {
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "welcome3/**/test")
- public String welcome3() {
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "welcome4/a?c/test")
- public String welcome4() {
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "welcome5/{name}")
- public String welcome5(@PathVariable("name") String name) {
- System.out.println(name);
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testRest/{id}", method = RequestMethod.POST)
- public String testPost(@PathVariable("id") Integer id) {
- System.out.println("post:增 " + id);
- //Service层实现 真正的增
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testRest/{id}", method = RequestMethod.GET)
- public String testGet(@PathVariable("id") Integer id) {
- System.out.println("get:查 " + id);
- //Service层实现 真正的增
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testRest/{id}", method = RequestMethod.DELETE)
- public String testDelete(@PathVariable("id") String id) {
- System.out.println("delete:删 " + id);
- //Service层实现 真正的增
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testRest/{id}", method = RequestMethod.PUT)
- public String testPut(@PathVariable("id") Integer id) {
- System.out.println("put:改 " + id);
- //Service层实现 真正的增
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testParam")
- public String testParam(@RequestParam("uname") String name, @RequestParam(value = "uage", required = false, defaultValue = "23") Integer age) {
- // String name = request.getParameter("uname");
- System.out.println(name);
- System.out.println(age);
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testRequestHeader")
- public String testRequestHeader(@RequestHeader("Accept-Language") String al) {
- System.out.println(al);
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testCookieValue")
- public String testCookieValue(@CookieValue("JSESSIONID") String jsessionId) {
- System.out.println(jsessionId);
- return "success";// views/success.jsp,默认使用了 请求转发的 跳转方式
- }
- @RequestMapping(value = "testObjectProperties")
- public String testObjectProperties(Student student) {//student属性 必须 和 form表单中的属性Name值一致(支持级联属性)
- /*
- String name = request.getParameter("name");
- int age= Integer.parseInt(request.getParameter("age")s) ;
- String haddrss = request.getParameter("homeaddress");
- String saddress = request.getParameter("schooladdress");
- Address address = new Address();
- address.setHomeAddress(haddrss);
- address.setSchoolAddress(saddress);
- Student student = new Student();
- student.setName(name);
- student.setAddress(address);
- */
- System.out.println(student.getId() + "," + student.getName() + "," + student.getAddress().getHomeAddress() + "," + student.getAddress().getSchoolAddress());
- return "success";
- }
- @RequestMapping(value = "testServletAPI")
- public String testServletAPI(HttpServletRequest request, HttpServletResponse response) {
- // request.getParameter("uname") ;
- System.out.println(request);
- return "success";//succes.jsp
- }
- @RequestMapping(value = "testModelAndView")
- public ModelAndView testModelAndView() {//ModelAndView:既有数据,又有视图
- //ModelAndView:Model -M View-V
- ModelAndView mv = new ModelAndView("success");//view: views/success.jsp
- Student student = new Student();
- student.setId(2);
- student.setName("zs");
- mv.addObject("student", student);//相当于request.setAttribute("student", student);
- return mv;
- }
- @RequestMapping(value = "testModelMap")
- public String testModelMap(ModelMap mm) {//success
- Student student = new Student();
- student.setId(2);
- student.setName("zs");
- mm.put("student2", student);//request域
- //forward: redirect:
- //
- return "redirect:/views/success.jsp";
- }
- @RequestMapping(value = "testMap")
- public String testMap(Map<String, Object> m) {
- Student student = new Student();
- student.setId(2);
- student.setName("zs");
- m.put("student3", student);//request域
- return "success";
- }
- @RequestMapping(value = "testModel")
- public String testModel(Model model) {
- Student student = new Student();
- student.setId(2);
- student.setName("zs");
- model.addAttribute("student4", student);//request域
- return "success";
- }
- @ModelAttribute//在任何一次请求前,都会先执行@ModelAttribute修饰的方法
- //@ModelAttribute 在请求 该类的各个方法前 均被执行的设计是基于一个思想:一个控制器 只做一个功能
- public void queryStudentById(Map<String, Object> map) {
- //StuentService stuService = new StudentServiceImpl();
- //Student student = stuService.queryStudentById(31);
- //模拟调用三层查询数据库的操作
- Student student = new Student();
- student.setId(31);
- student.setName("zs");
- student.setAge(23);
- // map.put("student", student) ;//约定:map的key 就是方法参数 类型的首字母小写
- map.put("stu", student);//约定:map的key 就是方法参数 类型的首字母小写
- }
- //修改:Zs-ls
- @RequestMapping(value = "testModelAttribute")
- public String testModelAttribute(@ModelAttribute("stu") Student student) {
- student.setName(student.getName());//将名字修改为ls
- System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
- return "success";
- }
- @RequestMapping(value = "testI18n")
- public String testI18n() {
- return "success";
- }
- @RequestMapping(value = "testConverter")
- public String testConverter(@RequestParam("studentInfo") Student student) {// 前端:2-zs-23
- System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
- return "success";
- }
- @RequestMapping(value = "testDateTimeFormat")//如果Student格式化出错,会将错误信息 传入result中
- public String testDateTimeFormat(Student student, BindingResult result) {
- System.out.println(student.getId() + "," + student.getName() + "," + student.getBirthday());
- if (result.getErrorCount() > 0) {
- for (FieldError error : result.getFieldErrors()) {
- System.out.println(error.getDefaultMessage());
- }
- }
- return "success";
- }
- }
Myconvert
- package converter;
- import entity.Student;
- import org.springframework.core.convert.converter.Converter;
- public class MyConverter implements Converter<String, Student> {
- @Override
- public Student convert(String source) {//source:2-zs-23
- String[] studentStrArr = source.split("-");
- Student student = new Student();
- student.setId(Integer.parseInt(studentStrArr[0]));
- student.setName(studentStrArr[1]);
- student.setAge(Integer.parseInt(studentStrArr[2]));
- return student;
- }
- }
index.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- <!-- 如果web.xml中的配置是
- <servlet-mapping>
- <servlet-name>springDispatcherServlet</servlet-name>
- <url-pattern>.action</url-pattern>
- </servlet-mapping>
- <a href="user/welcome.action">first springmvc - welcome</a> 交由springmvc处理 找 @RuestMapping映射
- <a href="user/welcome.action">first springmvc - welcome</a>交由springmvc处理 找 @RuestMapping映射
- <a href="xxx/welcome">first springmvc - welcome</a> 交由servlet处理 找url-parttern /@WebServlet()
- -->
- <a href="handler/welcome3/xyz/abcz/asb/test">33333333get - welcome</a>
- <br/>
- <a href="handler/welcome4/abc/test">4444444get - welcome</a>
- <br/>
- <a href="handler/welcome5/zs">555welcome</a>
- <form action="handler/welcome" method="post">
- name:<input name="name" ><br/>
- age:<input name="age" >
- height:<input name="height" >
- <input type="submit" value="post">
- </form>
- <br/>======<br/>
- <form action="handler/testRest/1234" method="post">
- <input type="submit" value="增">
- </form>
- <form action="handler/testRest/1234" method="post">
- <input type="hidden" name="_method" value="DELETE"/>
- <input type="submit" value="删">
- </form>
- <form action="handler/testRest/1234" method="post">
- <input type="hidden" name="_method" value="PUT"/>
- <input type="submit" value="改">
- </form>
- <form action="handler/testRest/1234" method="get">
- <input type="submit" value="查">
- </form>
- ------------<br/>
- <form action="handler/testParam" method="get">
- name:<input name="uname" type="text" />
- <input type="submit" value="查">
- </form>
- <br/>
- <a href="handler/testRequestHeader">testRequestHeader</a>
- <br/>
- <br/>
- <a href="handler/testCookieValue">testCookieValue</a><br/>
- <a href="handler/testServletAPI">testServletAPI</a>
- <br/>
- <form action="handler/testObjectProperties" method="post">
- id:<input name="id" type="text" />
- name:<input name="name" type="text" />
- 家庭地址:<input name="address.homeAddress" type="text" />
- 学校地址:<input name="address.schoolAddress" type="text" />
- <input type="submit" value="查">
- </form>
- <br/>
- <a href="handler/testModelAndView">testModelAndView</a>
- <br/>
- <br/>
- <a href="handler/testModelMap">testModelMap</a>
- <br/>
- <br/>
- <a href="handler/testMap">testMap</a>
- <br/>
- <br/>
- <a href="handler/testModel">testModel</a>
- <br/>
- <br/>
- <a href="handler/testI18n">testI18n</a>
- <br/>
- <form action="handler/testModelAttribute" method="post">
- 编号:<input name="id" type="hidden" value="31" />
- 姓名:<input name="name" type="text" />
- <input type="submit" value="修改">
- </form>
- <br/>
- <a href="handler/testMvcViewController">testMvcViewController</a>
- <br/>
- <form action="handler/testConverter" method="post">
- 学生信息:<input name="studentInfo" type="text" /><!-- 2-zs-23 -->
- <input type="submit" value="转换">
- </form>
- <form action="handler/testDateTimeFormat" method="post">
- 编号:<input name="id" type="text" value="31" />
- 姓名:<input name="name" type="text" />
- 出生日期:<input name="birthday" type="text" />
- <input type="submit" value="修改">
- </form>
- </body>
- </html>
success.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
- welcome to spring mvc success<br/>
- ==== request:<br/>
- ${requestScope.student.id } -${requestScope.student.name } <br/>
- ${requestScope.student2.id } -${requestScope.student2.name } <br/>
- ${requestScope.student3.id } -${requestScope.student3.name } <br/>
- ${requestScope.student4.id } -${requestScope.student4.name } <br/>
- ==== session:<br/>
- ${sessionScope.student.id } -${sessionScope.student.name } <br/>
- ${sessionScope.student2.id } -${sessionScope.student2.name } <br/>
- ${sessionScope.student3.id } -${sessionScope.student3.name } <br/>
- ${sessionScope.student4.id } -${sessionScope.student4.name } <br/>
- </body>
- </html>
Student
- package entity;
- import org.springframework.format.annotation.DateTimeFormat;
- public class Student {
- private int id;
- private String name;
- private Address address;
- public String getBirthday() {
- return birthday;
- }
- public void setBirthday(String birthday) {
- this.birthday = birthday;
- }
- @DateTimeFormat(pattern="yyyy-MM-dd")//格式化:前台传递来的数据,将前台传递来到数据 固定为yyyy-MM-dd
- private String birthday;
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- private int age;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Address getAddress() {
- return address;
- }
- public void setAddress(Address address) {
- this.address = address;
- }
- }
SpringMvc 视图解析器常见功能、类型转换、格式化的更多相关文章
- SpringMVC 视图解析器
SpringMVC 视图解析器 还记得SpringMVC 快速入门中,dispatcher-servlet.xml 配置的视图解析器么.它是SpringMVC 的核心知识点.本章节比较简单,明白视图解 ...
- SpringMVC视图解析器
SpringMVC视图解析器 前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这篇博客中将接着介绍一下SpringMVC视 图解析器.当我们对SpringMVC控制的资源发起 ...
- SpringMVC视图解析器(转)
前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这篇博客中将接着介绍一下SpringMVC视图解析器.当我们对SpringMVC控制的资源发起请求时,这些请求都会被Sprin ...
- SpringMVC视图解析器概述
不论控制器返回一个String,ModelAndView,View都会转换为ModelAndView对象,由视图解析器解析视图,然后,进行页面的跳转. 控制器处理方法---->ModelAndV ...
- springmvc 之 SpringMVC视图解析器
当我们对SpringMVC控制的资源发起请求时,这些请求都会被SpringMVC的DispatcherServlet处理,接着Spring会分析看哪一个HandlerMapping定义的所有请求映射中 ...
- springMVC视图解析器——InternalResourceViewResolver(转)
springmvc在处理器方法中通常返回的是逻辑视图,如何定位到真正的页面,就需要通过视图解析器. springmvc里提供了多个视图解析器,InternalResourceViewResolver就 ...
- 深入SpringMVC视图解析器
ViewResolver的主要职责是根据Controller所返回的ModelAndView中的逻辑视图名,为DispatcherServlet返回一个可用的View实例.SpringMVC中用于把V ...
- SpringMVC 视图解析器 InternalResourceViewResolver
我们在使用SpringMVC的时候,想必都知道,为了安全性考虑,我们的JSP文件都会放在WEB-INF下, 但是我们在外部是不可以直接访问/WEB-INF/目录下的资源对吧, 只能通过内部服务器进行转 ...
- SSM-SpringMVC-05:SpringMVC视图解析器InternalResourceViewResolver配置
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 视图解析器------默认就有配置,但是默认的在实际使用过程中有很多不方便的地方,所以我们配置一道视图解析器 ...
随机推荐
- 一文搞懂vim复制粘贴
转载自本人独立博客https://liushiming.cn/2020/01/18/copy-and-paste-in-vim/ 概述 复制粘贴是文本编辑最常用的功能,但是在vim中复制粘贴还是有点麻 ...
- java篇 之 ==与equals
==是一个比较运算符,基本数据类型比较的是值,引用数据类型比较的是地址值. "=="比"equals"运行速度快,因为"=="只是比较引用. ...
- Python学习(三)——Python的运算符和数值、字符的类中方法
Python开发IDE PyCharm,eclipse PyCharm的基础用法 全部选中后 Ctrl+?全部变为注释 运算符 结果为值的运算符 算术运算符: + - * / % // ** 赋值运算 ...
- Android学习09
SharedPreferences SharedPreferences,是一种轻量级的数据存储方式,采用Key/value的方式 进行映射,Sp通常用于记录一些参数配置.行为标记等! 1.获得mSha ...
- markdown区块
Markdown 区块 Markdown 区块引用是在段落开头使用 > 符号 ,然后后面紧跟一个空格符号: > 区块引用 > 菜鸟教程 > 学的不仅是技术更是梦想 显示结果如下 ...
- iframe onload事件触发两次
标准参考 关于 HTML 4.01 规范中 onload 内在事件说明:http://www.w3.org/TR/html401/interact/scripts.html#adef-onload 关 ...
- vue项目打包后运行报错400如何解决
昨天一个Vue项目打包后,今天测试,发现无论localhost还是服务器上都运行不了,报错如下: Failed to load resource: the server responded with ...
- 使用PIE.htc 进行IE兼容CSS3
步骤: 1.引入文件.注意PIE.htc文件和css文件要放在同一个目录下: 2.在css元素中加上 behavior:url(pie.htc); 3.可以愉快的写css hack啦 ,这时需要的圆 ...
- coturn服务器配置中英对比
coturn服务器配置中英对比 默认配置位置 /etc/turnserver.conf # RFC5766-TURN-SERVER configuration file # RFC5766-TURN- ...
- 从QC到QA
QC遇到了什么无法逾越的障碍 我们公司的主要业务是项目外包,一般的项目都在2-3个月的周期,采用瀑布模式.这种模式本身是相对简单,且十分成熟的模式.但是在实际的工作中,我们还是遇到了前所未有的挑战. ...