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


}

猜你喜欢

转载自www.cnblogs.com/kikyoqiang/p/11877068.html
今日推荐