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配置
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 视图解析器------默认就有配置,但是默认的在实际使用过程中有很多不方便的地方,所以我们配置一道视图解析器 ...
随机推荐
- 普通的javaweb项目和用maven管理的javaweb project的目录结构的区别
图一,图二 这种就是单独的建立普通的(也就是没有用maven管理包)javaweb项目的结构目录,这种需要将普通的jar依赖放到lib目录下,之后通过bulid 图一
- npm报错This is probably not a problem with npm. There is likely additional logging
使用webstorm开发时,遇到npm 报错,于是尝试了如下所有的方法,不完全统计. https://blog.csdn.net/liu305088020/article/details/791823 ...
- 接口测试,如何构建json类型的参数值
1.json类型参数传入,实际传输的时候是转化为一中字符串类型的格式,所以如data=”{}”,该参数用引号包含传入,“{}”里面的key都应该为双引号,value为字符串的也应该是双引号,最后一个v ...
- "exit"未定义标签 问题
找了两个多小时,最后才发现是版本问题.因为是网上下的代码,可能用的版本比较高,而我自己的是2.4.10版本的opencv,所以正确的代码应该是如下: CV_Error(CV_StsBadArg,&qu ...
- 后端——框架——容器框架——spring_core——《官网》阅读笔记——初篇
1.知识体系 spring-core的知识点大概分为以下几个部分 IOC容器 Bean的配置,XML方式和注解方式 Bean的管理,bean的生命周期,bean的作用域等等 与Bean相关联的接口和对 ...
- win10中,vscode安装go插件排雷指南
最近学习go,想着使用强大的vscode编写go,在安装go插件过程中,遇到了很多问题.下面记录解决方案. 1)win10环境,安装go,vscode,git 配置GOPATH环境变量,在我的电脑-& ...
- 如何把web项目部署到Linux云服务器(详细流程)
转自: https://blog.csdn.net/M_Kerry/article/details/81664548
- 【模板】凸包向内推进求不严格的半平面交——poj3384
想不明白这题写严格的半平面交为什么会错 /* 凸包所有边向内推进r */ #include<iostream> #include<cstring> #include<cs ...
- ZOJ1008 Gnome Tetravex
DFS+剪枝~ #include<bits/stdc++.h> using namespace std; ][]; int N; int cnt; ]; ]; unordered_map& ...
- vs2017 vs2019配置sqlite3连接引擎(驱动)指南(二)vs2019续集
在写完上一篇博客后,一觉醒来,又又又又不行了,介绍一个终极大招,如果你的fuck vs又提示无法打开sqlite3.h的问题 环境win10 vs2019 debug x86 实在没心情写文字了,直 ...