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;
    }

}


原文地址:https://www.cnblogs.com/kikyoqiang/p/11877068.html

时间: 2024-10-08 04:57:05

SpringMvc 视图解析器常见功能、类型转换、格式化的相关文章

SpringMVC视图解析器

AbstractController 先创建一个MyAbstorctController类,并且让他继承AbstractController父类,并实现该父类中的方法. public class MyAbstorctController extends AbstractController{ protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse

SpringMVC视图解析器 转

  前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这篇博客中将接着介绍一下SpringMVC视 图解析器.当我们对SpringMVC控制的资源发起请求时,这些请求都会被SpringMVC的DispatcherServlet处理,接着 Spring会分析看哪一个HandlerMapping定义的所有请求映射中存在对该请求的最合理的映射.然后通过该HandlerMapping取得 其对应的Handler,接着再通过相应的HandlerAdapter处理该Handler.H

springmvc 之 SpringMVC视图解析器

当我们对SpringMVC控制的资源发起请求时,这些请求都会被SpringMVC的DispatcherServlet处理,接着Spring会分析看哪一个HandlerMapping定义的所有请求映射中存在对该请求的最合理的映射.然后通过该HandlerMapping取得其对应的Handler,接着再通过相应的HandlerAdapter处理该Handler.HandlerAdapter在对Handler进行处理之后会返回一个ModelAndView对象.在获得了ModelAndView对象之后,

SpringMVC 视图解析器 InternalResourceViewResolver

我们在使用SpringMVC的时候,想必都知道,为了安全性考虑,我们的JSP文件都会放在WEB-INF下, 但是我们在外部是不可以直接访问/WEB-INF/目录下的资源对吧, 只能通过内部服务器进行转发的形式进行访问,那么InternalResourceViewResolver底层通过转发形式帮我们解决了这个问题! 为了使用InternalResourceViewResolver我们都会在SpringMVC的配置文件中进行如下配置 <!-- 自定义视图解析器 --> <bean id=&

SpringMVC视图解析器配置

<!--视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/"/> <!--后缀--> <property name="suffix" value=&q

SpringMVC视图解析器配置式开发

视图解析器分为: 默认方法名解析器 属性方法名解析器 参数方法名解析器 测试案例:创建类 package cn.happy.day03MultiAction; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; import javax.servlet.http.HttpServletRe

springmvc 视图解析器工作不正常

参考了如下 https://blog.csdn.net/typa01_kk/article/details/45902783 今天搭建了一个新的工程,从头开始搞的,处理完发现,能正常进入controller但是 报404 研究了一番,猜测应该是视图解析器没有正常工作 如果是返回地址写错了,那么应该提示 后边的错误是我故意改动的,很明显,正常的话,视图解析器可以解析到返回的地址,然后去文件夹下寻找页面 但是上边的明显没有解析到 比较奇怪的问题 我做了个小实验 把返回类型改为string 这时候可以

[转载]开发 Spring 自定义视图和视图解析器

原文出处 http://www.ibm.com/developerworks/cn/java/j-lo-springview/ 概述 Spring 3.0 默认包含了多种视图和视图解析器,比如 JSP.Velocity 视图等,但在某些情况下,我们需要开发自定义的视图及其解析器,以便显示特殊文件格式的视图,我们也可以使用自定义视图及解析器,针对特定的视图做相应的处理.本文将通过一个示例来介绍如何开发 Spring 自定义视图和视图解析器,来显示后缀名为 SWF 的视图,并提供一个简单的注册机制,

SpringMVC与Freemarker的集成以及多视图解析器配置

一.Spring MVC视图解析器 视图解析器的工作流程大致是这样的:Controller的某个方法执行完成以后,返回一个视图(比如:listUser),视图解析器要做的工作就是找到某个对象 来完成视图的渲染,或者跳转到其他的逻辑视图.这里的渲染对象通常就是我们的jsp文件或者我们下面用的Freemarker(例如listUser.jsp或者 listUser.ftl).渲染完成以后,将解析结果发送到客户端浏览器. 下面介绍一下本文需要用到的解析器(更多解析器资料,请参考 http://e-fr