SpringMVC补充编码,日期,与Json等

1 action方法返回值类型

@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * action返回值类型 1: ModelAndView 
	 * 设置request域属性+跳转资源的路径
	 **/
	@RequestMapping("/m1.action")
	public ModelAndView method_1() {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "method_1");
		mv.setViewName("jsp/test");
		return mv;
	}

	/**
	 * action返回值类型 2: String 
	 * 跳转的资源的路径->等价于mv.setViewName("test");
	 **/
	@RequestMapping("/m2.action")
	public String method_2(Model m) {
		m.addAttribute("a", "method_2");
		return "jsp/test";
	}

	/**
	 * action返回值类型 2: String 
	 * 跳转的资源的路径->等价于mv.setViewName("test");
	 **/
	@RequestMapping("/m3.action")
	public String method_3(Model m) {
		m.addAttribute("a", "method_3");
		return "forward:/jsp/test.jsp";
	}

	/**
	 * action返回值类型 3: void 
	 * 不需要指定跳转资源的路径(自己拼凑页面+ajax)
	 **/
	@RequestMapping("/m4.action")
	public void method_4(HttpServletResponse resp) throws Exception {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print("<a href='/springMVC/jsp/test.jsp'>跳转到jsp/test.jsp<a>");
		return;
	}

	/**
	 * action返回值类型 3: void 
	 * 不需要指定跳转资源的路径(自己拼凑页面+ajax)
	 **/
	@RequestMapping("/m5.action")
	public void method0_5(HttpServletResponse resp) throws Exception {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print("当前时间毫秒值:" + new Date().getTime());
		return;
	}
}
  • test.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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="<c:url value='/js/jquery-1.6.4.min.js'/>"></script>
        <title>Insert title here</title>
        <style type="text/css">
            table {
                border: 1px solid blue;
                width: 600px;
                margin: 100px auto;
                border-collapse: collapse;
            }

            th, td {
                border: 1px solid blue;
                padding: 10px;
            }

            #div1 {
                border: 1px solid blue;
                width: 200px;
                height: 200px;
            }
        </style>
    </head>
    <body>
        <c:if test="${not empty requestScope.a}">
            域属性a的值为:${requestScope.a}<br />
        </c:if>

        <a href="<c:url value='/test/m1.action'/>">请求m1.action:返回值是ModelAndView</a> <br />
        <a href="<c:url value='/test/m2.action'/>">请求m2.action:返回值是String</a> <br />
        <a href="<c:url value='/test/m3.action'/>">请求m3.action:返回值是String</a> <br />
        <a href="<c:url value='/test/m4.action'/>">请求m4.action:返回值是void</a> <br />
        <a href="javascript:testAjax();">请求m5.action:返回值是void</a> <br />

        <div id="div1"></div>

        <script type="text/javascript">
            function testAjax() {
                $.get("<c:url value='/test/m5.action'/>", "n=" + Math.random(),
                      function(data) {
                    $("#div1").html(data.fontcolor("red").bold());
                }, "text");
            }
        </script>
    </body>
</html>

2 全站编码

@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 不设置编码集乱码 req.setCharacterEncoding("utf-8"); 
	 * 无效:方法参数name接受请求参数 在设置编码集之前
	 **/
	@RequestMapping("/m1.action")
	public ModelAndView method_1(HttpServletRequest req, String name) throws Exception {
		req.setCharacterEncoding("utf-8");
		name = req.getParameter("name");
		String age = req.getParameter("age");
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_m1" + name + "、" + age);
		mv.setViewName("jsp/test");
		return mv;
	}

	/**
	 * 通过全站编码过滤器,解决乱码问题
	 * **/
	@RequestMapping("/m2.action")
	public ModelAndView method_2(String name, int age) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_m2" + name + "、" + age);
		mv.setViewName("jsp/test");
		return mv;
	}
}
  • 在Xml添加全站编码的过滤器 解决乱码问题
<!-- 配置springmvc的全站编码集过滤器 -->
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!-- 通过过滤器的初始化参数指定编码集 -->
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>*.action</url-pattern>
    <dispatcher>ERROR</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>
  • test.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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="<c:url value='/js/jquery-1.6.4.min.js'/>"></script>
        <title>Insert title here</title>
    </head>
    <body>
        <c:if test="${not empty requestScope.a}">
            域属性a的值为:${requestScope.a}<br />
        </c:if>

        <a href="<c:url value='/test/m1.action?name=韩雪&age=28'/>">get请求m1.action</a> <br />
        <form action="<c:url value='/test/m1.action'/>" method="post">
            name:<input type="text" name="name" /> 
            age:<input type="text" name="age" /> <input type="submit" value="post请求" />
        </form>
        <br />
        <a href="<c:url value='/test/m2.action?name=韩雪&age=25'/>">get请求m2.action</a> <br />
        <form action="<c:url value='/test/m2.action'/>" method="post">
            name:<input type="text" name="name" /> 
            age:<input type="text" name="age" /> <input type="submit" value="post请求" />
        </form>
    </body>
</html>

3 mvc标签引入适配器和映射器

3.1 核心配置文件

*** 在核心配置文件中引入mvc的ns和xsd文件 ***
<beans 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

3.2 核心配置文件

*** 通过mvc标签自动注册注解形式的处理器映射器和处理器适配器 ***
<mvc:annotation-driven conversion-service="myDateConverBean"/>

4 参数是日期类型

4.0 字符串不正确,用Date接收:响应状态码400

	/**
	 * 参数是日期类型
	 * 参数值是:2021-11-11 11:11:11->接收失败 
	 * 响应状态码400:请求参数类型错误
	 * **/ 
	@RequestMapping("/m1.action")
	public ModelAndView method_1(Date date) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_1->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}

4.1 参数字符串格式为yyyy/MM/dd HH:mm:ss

	/**
	 * 参数是日期类型
	 * 参数值是:2021/12/12 12:12:12->接收成功
	 * 参数值是:2021-12-12 12:12:12->接收失败
	 * 方案1:需要客户端提交的字符串格式:yyyy/MM/dd HH:mm:ss
	 * **/
	@RequestMapping("/m2.action")
	public ModelAndView method_2(Date date) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_2->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}

4.2 参数字符串接收用simpledateformat解析

	/**
	 * 参数是日期类型
	 * 参数值是:2021-13-13 13:13:13->接收成功
	 * 方案2:使用字符串接收然后通过SimpleDateFormat对字符串解析为日期
	 * **/
	@RequestMapping("/m3.action")
	public ModelAndView method_3(String dateStr) throws Exception {
		Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_3->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}

4.3 action参数使用注解:@DateTimeFormat

	/**
	 * 参数是日期类型
	 * 参数值是:2021-14-14 14:14:14->接收失败
	 * 方案3:使用@DateTimeFormat 适用于spring版本4.3+
	 * **/
	@RequestMapping("/m4.action")
	public ModelAndView method_4(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date date) 
        throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_4->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}

4.4 用注解@InitBinder设置自定义参数解析器

	/**
	 * 参数是日期类型
	 * 参数值是:2021-15-15 15:15:15->接收成功
	 * 方案4: 使用@InitBinder来自定义date参数解析器
	 * 注意: 一旦使用@InitBinder默认格式 yyyy/MM/dd HH:mm:ss 将没法使用
	 * **/
	@RequestMapping("/m5.action")
	public ModelAndView method_5(Date date) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_5->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}
	/**
	 * 作用范围是当前整个页面
	 * 并且其他日期格式都将失效
	 * **/
	@InitBinder
	public void setDateBinder(HttpServletRequest req, ServletRequestDataBinder binder) throws Exception {
		req.setCharacterEncoding("UTF-8");
		CustomDateEditor cde = new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false);
		binder.registerCustomEditor(java.util.Date.class, cde);
	}

4.5 使用统一的自定义解析器

  • 创建一个解析器类实现接口Converter<String, Date>
public class MyDateConver implements Converter<String, Date> {
	@Override
	public Date convert(String arg0) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(arg0);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
}
  • 在核心配置文件中配置此解析器
<!-- 配置日期的自定义转换器bean -->
<bean id="myDateConverBean"
      class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="action.MyDateConver" />
        </set>
    </property>
</bean>
  • 客户端参数字符串格式必须与解析器中模式一致
	/**
	 * 参数是日期类型
	 * 参数值是:2021-16-16 16:16:16->接收成功
	 * 方案5: 设置统一的日期参数解析器bean
	 * 指定日期固定格式:yyyy-MM-dd HH:mm:ss
	 * **/
	@RequestMapping("/m6.action")
	public ModelAndView method_6(Date date) throws Exception {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_6->" + date.toLocaleString());
		mv.setViewName("jsp/test");
		return mv;
	}
  • test.jap
<body>
    <c:if test="${not empty requestScope.a}">
        域属性a的值为:${requestScope.a}<br />
    </c:if>

    <a   href="<c:url value='/test/m1.action?date=2021-11-11 11:11:11'/>">2021-11-11 11:11:11</a><br/>
    <a   href="<c:url value='/test/m1.action?date=2021-11-11'/>">2021-11-11</a><br/>
    <a   href="<c:url value='/test/m2.action?date=2021/12/12'/>">2021/12/12</a><br/>
    <a   href="<c:url value='/test/m2.action?date=2021/12/12 12:12:12'/>">2021/12/12 12:12:12</a><br/>

    <a   href="<c:url value='/test/m3.action?dateStr=2021-13-13 13:13:13'/>">参数是字符串</a><br/>
    <a   href="<c:url value='/test/m4.action?date=2021-14-14 14:14:14'/>">使用注解@DateTimeFormat</a><br/>
    <a   href="<c:url value='/test/m5.action?date=2021-15-15 15:15:15'/>">使用自定义日期参数解析器</a><br/>
    <a   href="<c:url value='/test/m6.action?date=2021-16-16 16:16:16'/>">统一的日期参数解析器bean</a><br/>
</body>

5 url模板映射

  • 把参数伪装成url的一部分
public class Test {
	@RequestMapping("/m1/{name}/{age}.action")
	public ModelAndView method_1(@PathVariable("name") String sname, @PathVariable("age") int sage, boolean dy) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("a", "a_value_1->" + sname + ":" + sage + ":" + dy);
		mv.setViewName("jsp/test");
		return mv;
	}
}
  • test.jsp
<body>
	<c:if test="${not empty requestScope.a}">
       	域属性a的值为:${requestScope.a}<br />
	</c:if>

	<a href="<c:url value='/test/m1/韩雪/28.action?dy=true'/>">test/m1/韩雪/28</a> <br />
	<a href="<c:url value='/test/m1/寒冰/22.action?dy=true'/>">test/m1/寒冰/22</a> <br />
</body>

6 传递的是json

  • json概念
js可以直接解析一种数据格式:{属性名=属性值,属性名=属性值} 
<a href="javascript:test();">json概念</a> <br />
<script type="text/javascript">
    function test() {
        var json = {
            "name" : "韩雪",
            "age" : 28,
            "score" : 66.6,
            "dy" : true,
            "arr" : [ 1, 3, 5, 6, 7 ],
            "teacher" : {
                "tname" : "张雪崩",
                "tsex" : "男"
            }
        };
        alert(json);//[object Object]
        alert(json.name+":"+json.age+":"+json.teacher.tname);//韩雪:28:张雪崩
    }
</script>

6.1 响应数据是json

  • test.jsp
<body>
	<a href="javascript:test();">响应数据是json</a> <br />
	<script type="text/javascript">
		function test() {
			$.ajax({
				async:true, /*是否异步*/
				cache:false, /*是否使用缓存*/
				data:null, /*请求参数*/
				dateType:"json", /*响应的数据类型*/
				type:"GET", /*请求方式*/
				url:"<c:url value='/test/m1.action'/>",
				success:function(data){
					alert(data+":"+data.name+":"+data.teacher.tname);
				}
			});
		}
	</script>
</body>
  • action:添加@ResponseBody注解
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 响应的是json,java不识别json,只能响应json格式的字符串
	 * @Component:组件
	 * @Controller:控制器
	 * @ResponseBody:
	 * 1: 返回值如果是对象->返回的是对象对应的json串
	 * 2: 返回值是字符串->返回的是字符串数据(不是路径)
	 * **/
	@RequestMapping("/m1.action")
	@ResponseBody
	public Student method_1() {
		// 响应一个student对象对应的json串
		Student s = new Student(18, "韩雪", true, "女", 99f, new Teacher(1001, "张雪崩", "男"));
		return s;
	}
}

6.2 请求参数是json字符串

  • jsp必须是post请求

  • 必须设置ContextType=text/json;charset=utf-8

  • 请求参数是json字符串,不是json对象

  • test.jsp

<body>
    <a href="javascript:test_1();">参数是json字符串</a> <br />

    <script type="text/javascript">
        function test_1() {
            var jsonStr='{"name":"韩雪","age":28,"dy":true,"sex":"女","score":99,
            			  "teacher":{"tname":"张雪崩","tsex":"男"}}' 
            $.ajax({
                async:true, /*是否异步*/
                cache:false, /*是否使用缓存*/
                data:jsonStr, /*请求参数是json格式的字符串*/
                dateType:"text", /*响应的数据类型*/
                /*请求参数是json,必须加请求头contentType,指定请求参数的类型*/
                contentType:"application/json;charset=utf-8",
                type:"POST", /*请求参数是json:请求方式必须是post*/
                url:"<c:url value='/test/m1.action'/>",
                success:function(data){
                    alert(data);
                }
            });
        }
    </script>
</body>
  • action
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 请求参数的是json格式的字符串
	 * @RequestBod:用参数引用接受请求的json格式字符串的数据
	 * **/
	@RequestMapping("/m1.action")
	public void method_1(@RequestBody Student s, HttpServletResponse resp) throws Exception {
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print(s.toString());
		System.out.println(s);
		return;
	}
}
  • test.jsp
<body>
    <a href="javascript:test_1();">请求数据是json</a> <br />

    <script type="text/javascript">
        function test_1() {
            var jsonStr='{"name":"韩雪","age":28,"dy":true,"sex":"女","score":99,
                          "teacher":{"tname":"张雪崩","tsex":"男"}}' 
            $.ajax({
                async:true, /*是否异步*/
                cache:false, /*是否使用缓存*/
                data:jsonStr, /*请求参数是json格式的字符串*/
                dateType:"test", /*响应的数据类型*/
                /*请求参数是json,必须加请求头contentType,指定请求参数的类型*/
                contentType:"application/json;charset=utf-8",
                type:"POST", /*请求参数是json:请求方式必须是post*/
                url:"<c:url value='/test/m1.action'/>",
                success:function(data){
                    alert(data);
                }
            });
        }
    </script>
</body>
  • action: 通过@RequestBody注解用对象引用来接受json串
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 请求的参数是json格式的字符串
	 * produces="text/plain; charset=UTF-8": 
	 * 防止响应的字符串是乱码
	 * @RequestBod:
	 * 用参数引用接受请求的json格式字符串的数据
	 * 1: 返回值如果是对象->返回的是对象对应的json对象
	 * 2: 返回值是字符串->返回的是字符串数据(不是路径)
	 * **/
	@RequestMapping(value = "/m1.action", produces = "text/plain; charset=UTF-8")
	@ResponseBody
	public String method_2(@RequestBody Student s, HttpServletResponse resp) throws Exception {
		s.setName("叶晨");
		s.setSex("魔");
		s.setScore(999f);
		return s.toString();
	}
}

6.3 请求json串、响应json串

  • test.jsp
<body>
	<a href="javascript:test_1();">请求数据是json、响应数据是json</a> <br />
	
	<script type="text/javascript">
		function test_1() {
			var jsonStr='{"name":"韩雪","age":28,"dy":true,"sex":"女","score":99,
                          "teacher":{"tname":"张雪崩","tsex":"男"}}' 
			$.ajax({
				async:true, /*是否异步*/
				cache:false, /*是否使用缓存*/
				data:jsonStr, /*请求参数是json格式的字符串*/
				dateType:"json", /*响应的数据类型*/
				/*请求参数是json,必须加请求头contentType,指定请求参数的类型*/
				contentType:"application/json;charset=utf-8",
				type:"POST", /*请求参数是json:请求方式必须是post*/
				url:"<c:url value='/test/m1.action'/>",
				success:function(data){
					alert(data+":"+data.name+":"+data.score);
				}
			});
		}
	</script>
</body>
  • action:@RequestBody+@ResponseBody
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 请求的参数是json格式的字符串
	 * @RequestBod:
	 * 用参数引用接受请求的json格式字符串的数据
	 * 1: 返回值如果是对象->返回的是对象对应的json串
	 * 2: 返回值是字符串->返回的是字符串数据(不是路径)
	 * **/
	@RequestMapping(value = "/m1.action")
	@ResponseBody
	public Student method_2(@RequestBody Student s) throws Exception {
		s.setName("叶晨");
		s.setSex("魔");
		s.setScore(999f);
		return s;
	}
}

6.4 注意

@ResponseBody,响应的是对象,中文不乱码,响应的是字符串中文乱码  
需要在@RequestMapping中加属性produces
  • jsp:请求是json串,响应是字符串
<body>
    <a href="javascript:test_1();">请求数据是json</a> <br />

    <script type="text/javascript">
        function test_1() {
            var jsonStr='{"name":"韩雪","age":28,"dy":true,"sex":"女","score":99,
                          "teacher":{"tname":"张雪崩","tsex":"男"}}' 
            $.ajax({
                async:true, /*是否异步*/
                cache:false, /*是否使用缓存*/
                data:jsonStr, /*请求参数是json格式的字符串*/
                dateType:"test", /*响应的数据类型*/
                /*请求参数是json,必须加请求头contentType,指定请求参数的类型*/
                contentType:"application/json;charset=utf-8",
                type:"POST", /*请求参数是json:请求方式必须是post*/
                url:"<c:url value='/test/m1.action'/>",
                success:function(data){
                    alert(data);
                }
            });
        }
    </script>
</body>
  • action: /test/m1.action
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 请求的参数是json格式的字符串
	 * produces="text/plain; charset=UTF-8": 
	 * 防止响应的字符串是乱码
	 * @RequestBod:
	 * 用参数引用接受请求的json格式字符串的数据
	 * 1: 返回值如果是对象->返回的是对象对应的json串
	 * 2: 返回值是字符串->返回的是字符串数据(不是路径)
	 * **/
	@RequestMapping(value = "/m1.action", produces = "text/plain; charset=UTF-8")
	@ResponseBody
	public String method_2(@RequestBody Student s, HttpServletResponse resp) throws Exception {
		s.setName("叶晨");
		s.setSex("魔");
		s.setScore(999f);
		return s.toString();
	}
}

7 数据回显

为了提高客户的体验性,当数据提交失败时,跳转到原来的页面,表单保留原值

7.1 单值参数

  • 需要手动把方法参数装入request域中

  • 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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript"
                src="<c:url value='/js/jquery-1.6.4.min.js'/>"></script>
        <title>Insert title here</title>
        <style type="text/css">
            table {
                border: 1px solid blue;
                width: 600px;
                margin: 10px auto;
                border-collapse: collapse;
            }

            th, td {
                border: 1px solid blue;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <c:if test="${not empty message }">
            错误提示信息:${message}<br />
        </c:if>

        <form action="<c:url value='/test/m1.action'/>" method="post" id="form1">
            <table>
                <tr>
                    <th>学生名字:</th>
                    <td><input type="text" name="name" value="${requestScope.name}" /></td>
                </tr>
                <tr>
                    <th>学生密码:</th>
                    <td><input type="text" name="pwd" value="${requestScope.pwd}" /></td>
                </tr>
                <tr>
                    <th>学生年龄:</th>
                    <td><input type="text" name="age" value="${requestScope.age}" /></td>
                </tr>
                <tr>
                    <th>学生性别:</th>
                    <td>
                        男:<input type="radio" name="sex" value="男" /> 
                       		| 
                        女:<input type="radio" name="sex" value="女" />
                    </td>
                </tr>
                <tr>
                    <th colspan="2"><input type="submit" value="注册" /></th>
                </tr>
            </table>
        </form>

        <script type="text/javascript">
            $(function() {
                var requestSex = "${requestScope.sex}";
                $.each($("#form1 input[name='sex']"), function(i, n) {
                    if ($(n).val() == requestSex) {
                        $(n).attr("checked", "checked");
                    }
                })
            });
        </script>
    </body>
</html>
  • action
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 数据回显1: 单值数据 
	 * 需要把数据添加到request域中
	 * **/ 
	@RequestMapping("/m1.action")
	public String method01(int age, String name, String sex, String pwd, Model model) {
		model.addAttribute("message", "服务器繁忙,请稍等!name=" + name + ",age=" + age + ",sex=" + sex);
		model.addAttribute("name", name);
		model.addAttribute("sex", sex);
		model.addAttribute("pwd", pwd);
		model.addAttribute("age", age);
		return "jsp/test";
	}
}

7.2 对象类型参数

  • springmvc自动把参数作为属性值,类名首字母作为属性名存储到request域中

  • 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">
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript"
                src="<c:url value='/js/jquery-1.6.4.min.js'/>"></script>
        <title>Insert title here</title>
        <style type="text/css">
            table {
                border: 1px solid blue;
                width: 600px;
                margin: 10px auto;
                border-collapse: collapse;
            }

            th, td {
                border: 1px solid blue;
                padding: 10px;
            }
        </style>
    </head>
    <body>
        <c:if test="${not empty message }">
            错误提示信息:${message}<br />
        </c:if>

        学生->${requestScope.stu}<br/>

        <form action="<c:url value='/test/m1.action'/>" method="post"
              id="form_1">
            <table>
                <tr>
                    <th>学生名字:</th>
                    <td><input type="text" name="name" value="${requestScope.stu.name}" /></td>
                </tr>
                <tr>
                    <th>学生密码:</th>
                    <td><input type="text" name="pwd" value="${requestScope.stu.pwd}" /></td>
                </tr>
                <tr>
                    <th>学生年龄:</th>
                    <td><input type="text" name="age" value="${requestScope.stu.age}" /></td>
                </tr>
                <tr>
                    <th>学生性别:</th>
                    <td>
                        男:<input type="radio" name="sex" value="男" /> 
                        | 
                        女:<input type="radio" name="sex" value="女" />
                    </td>
                </tr>
                <tr>
                    <th colspan="2"><input type="submit" value="注册" /></th>
                </tr>
            </table>
        </form>

        <script type="text/javascript">
            $(function() {
                var requestSex = "${requestScope.stu.sex}";
                $.each($("#form_1 input[name='sex']"), function(i, n) {
                    if ($(n).val() == requestSex) {
                        $(n).attr("checked", "checked");
                    }
                })
            });
        </script>
    </body>
</html>
  • action:可以通过@ModelAttribute注解来指定域属性名
@Component
@Controller
@RequestMapping("/test")
public class Test {
	/**
	 * 数据回显2: 对象类型的数据 
	 * springmvc会自动把对象装入request域中,但是属性名为类名首字母小写
	 * @ModelAttribute("stu")Student stu->此注解作用指定域属性名为stu
	 **/
	@RequestMapping("/m1.action")
	public String method(@ModelAttribute("stu") Student stu, Model model) {
		model.addAttribute("message","服务器繁忙,请稍等! stu=" + stu);
		return "jsp/test";
	}
}
posted @ 2021-11-11 22:09  RenVei  阅读(35)  评论(0编辑  收藏  举报