(蔡庐总结)springMVC传相同属性
- 格式:pdf
- 大小:55.23 KB
- 文档页数:7
SpringMVC(⼗)--通过表单序列化传递参数通过表单序列化传递参数就是将表单数据转化成字符串传递到后台,序列化之后参数请求变成这种模式param1=value1&¶m2=value2,下⾯⽤代码实现。
1、创建表单<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><%String root = request.getContextPath();String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+ root + "/";%><script type="text/javascript"src="<%=basePath%>jslib/jquery-1.8.3.min.js"></script><script type="text/javascript" src="<%=basePath%>jslib/jquery.form.js"></script><script type="text/javascript" src="<%=basePath%>js/param.js"></script><link href="<%=basePath%>css/param.css" type="text/css" rel="stylesheet"><title>Insert title here</title></head><body><div class="param"><div class="simple public"><!--表单序列化传递参数 --><div class="public formSerial"><p style="text-align: center;">表单序列化传递参数</p><form id="formSerialForm"><table id="formSerialTable"><tr><td>id:</td><td><input type="text" name="id" value=""></td></tr><tr><td>名称:</td><td><input type="text" name="name" value=""></td></tr><tr><td></td><td style="text-align: right;"><input type="button"value="提交" id="setFormSerialParam"></td></tr></table></form></div></div></body></html>页⾯效果图如下:2、绑定提交请求事件$(function() {/* 表单序列化⽅式传递数据 */$("#setFormSerialParam").click(function() {$.ajax({url : "./formSerial",type : "POST",/* 将form数据序列化之后传给后台,数据将以id=**&&name=** 的⽅式传递 */data : $("#formSerialForm").serialize(),success : function(data) {(data.stringList);}});});});上⾯红⾊加粗的部分就是表单的序列化。
SpringMVC在对应绑定不同实体,但具有相同属性名的解决⽅案....在springmvc中,可以对前台传递过来的参数进⾏与后台实体绑定(第⼆种⽅式相对较好).⽐如:前台页⾯:1<form action="${pageContext.request.contextPath}/test/test" method="POST">2⽤户名:<input type="text" name="name"><br/>3<input type="submit" value="提交">4</form>实体类:1package com.yemaozi.rms.domain;23public class Student {4private Integer id;5private String name;6public Integer getId() {7return id;8 }9public void setId(Integer id) {10this.id = id;11 }12public String getName() {13return name;14 }15public void setName(String name) { = name;17 }18 }对应的Controller:1 @Controller2 @Scope(value="prototype")3 @RequestMapping("/test")4public class TestController {5 @RequestMapping("/test")6public String test(Student stu){7 System.out.println(stu.getName());8return "success";9 }10 }这样,在Controller是可以进⾏绑定的....但是,若是,要对多个实体数据进⾏绑定,⽽且这些实体有同名的属性....前台页⾯:<form action="${pageContext.request.contextPath}/test/test" method="POST">学⽣姓名:<input type="text" name="name"><br/>⽼师姓名:<input type="text" name="name"><br/><input type="submit" value="提交"></form>实体类:1public class Teacher {2private Integer id;3private String name;4public Integer getId() {5return id;6 }7public void setId(Integer id) {8this.id = id;9 }10public String getName() {11return name;12 }13public void setName(String name) { = name;15 }16 }Controller:1 @RequestMapping("/test")2public String test(Student stu, Teacher teacher){3 System.out.println(stu.getName() + teacher.getName());4return "success";5 }这样,就会明⽩,name并不是唯⼀标识了,所以,在后台不能精确的绑定,其实,若是将该表单进⾏提交,则会将这两个name属性分别都添加到stu 和teacher这两个对象中..因为springmvc中,是根据属性来进⾏数据绑定的,不像struts2是基于ognl的数据绑定机制.要解决现在这样问题的⽅案⼀:复合实体:即:1public class StuTeacher {2private Student stu;3private Teacher teacher;4public Student getStu() {5return stu;6 }7public void setStu(Student stu) {8this.stu = stu;9 }10public Teacher getTeacher() {11return teacher;12 }13public void setTeacher(Teacher teacher) {14this.teacher = teacher;15 }16 }创建⼀个拥有stu和teacher这两个实体对象的类StuTeacher.....这样我们就可以再前台这样书写.1<form action="${pageContext.request.contextPath}/test/test1" method="POST">2学⽣姓名:<input type="text" name=""><br/>3⽼师姓名:<input type="text" name=""><br/>4<input type="submit" value="提交">5</form>就可以根据复合实体中的属性通过.进⾏导航绑定数据在Controller中的代码:1 @RequestMapping("/test1")2public String test1(StuTeacher stuTeacher){3 System.out.println(stuTeacher);4return "success";5 }这种⽅法可以简单的处理这种数据绑定问题,好处是不需要添加任何插件代码,缺点是扩展性不好,后期可能使得代码臃肿.所以可以在springmvc中可以进⾏⾃定义ModelAttributeProcessor来进⾏数据绑定的扩展.1,⾃定义注解:1import ng.annotation.Documented;2import ng.annotation.ElementType;3import ng.annotation.Retention;4import ng.annotation.RetentionPolicy;5import ng.annotation.Target;678 @Target({ElementType.PARAMETER, ElementType.METHOD})9 @Retention(RetentionPolicy.RUNTIME)10 @Documented11public @interface ExtModelAttribute {12 String value() default "";13 }2,继承ServletModelAttributeMethodProcessor类,实现⾃⼰的数据绑定模式.1import javax.servlet.ServletRequest;23import org.springframework.core.MethodParameter;4import org.springframework.web.bind.ServletRequestDataBinder;5import org.springframework.web.bind.WebDataBinder;6import org.springframework.web.context.request.NativeWebRequest;7import org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor; 89public class ExtServletModelAttributeMethodProcessor extends10 ServletModelAttributeMethodProcessor {1112public ExtServletModelAttributeMethodProcessor() {13super(false);14 }1516public ExtServletModelAttributeMethodProcessor(boolean annotationNotRequired) {17super(annotationNotRequired);18 }1920 @Override21public boolean supportsParameter(MethodParameter parameter) {22if (parameter.hasParameterAnnotation(ExtModelAttribute.class)) {23return true;24 } else {25return false;26 }27 }2829 @Override30protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {31 ServletRequest servletRequest = request.getNativeRequest(ServletRequest.class);32 ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;33 servletBinder.setFieldDefaultPrefix(servletBinder.getObjectName() + ".");34 servletBinder.bind(servletRequest);35 }36 }3,在springmvc配置⽂件中添加相应的加载驱动配置1<mvc:annotation-driven>2<!--添加在此处-->3<mvc:argument-resolvers>4<bean class="com.yemaozi.springmvc.ext.databind.ExtServletModelAttributeMethodProcessor"/>5</mvc:argument-resolvers>6</mvc:annotation-driven>4,应⽤在前台页⾯中:<form action="${pageContext.request.contextPath}/test/test1" method="POST">学⽣姓名:<input type="text" name=""><br/>⽼师姓名:<input type="text" name=""><br/><input type="submit" value="提交"></form>在Controller中使⽤⽅式:1 @RequestMapping("/test2")2public String test2(@ExtModelAttribute("stu") Student stu, @ExtModelAttribute("teacher")Teacher teacher){ 3 System.out.println(stu.getName() + teacher.getName());4return "success";5 }使⽤刚才⾃定义的注解来标注对应的属性.。
springMVC中传递的参数对象中包含list的情况需要的jar包: 3.2.jar + jackson-all-1.8.5.jar。
写代码时碰到个需要将对象⾥的⼦明细⼀起传递到controller⾥去,当时就想直接将参数⼀起传递过来,贴下代码:controller:@RequestMapping(params="save")@ResponseBodypublic CustomForeignKey save(@RequestBody CustomForeignKey customForeignKey,Model model,ModelAndView mv,HttpServletRequest req){return customForeignKeyService.add(customForeignKey);}参数对象:public class CustomForeignKey {private Long id;private Long tableId;private Long foreignKeyTableId;private String foreignKeyTableName;private String name;private List<CustomForeignKeyRelation> customForeignKeyRelations;public Long getId() {return id;}对象下⼦明细:CustomForeignKeyRelation :public class CustomForeignKeyRelation {private Long id;private Long customForeignKeyId;private Long leftCustomColumnId;private String leftCustomColumnName;private String leftCustomColumnAlias;private Long rightCustomColumnId;private String rightCustomColumnName;private String rightCustomColumnAlias;public Long getId() {return id;}js传递的代码段:var relations = [];$.each(rows,function(i,obj){if(obj.leftCustomColumnId != 0 && obj.leftCustomColumnName && obj.leftCustomColumnName != '⽆')relations.push({leftCustomColumnId:obj.leftCustomColumnId,leftCustomColumnName:obj.leftCustomColumnName,rightCustomColumnId:obj.rightCustomColumnId,rightCustomColumnName:obj.rightCustomColumnName});})var dd = {tableId:selectRowOfTable.id,name:t_fk_name,foreignKeyTableId:$("#foreignKeyDialog_foreignTableId").combobox("getValue"),foreignKeyTableName:$("#foreignKeyDialog_foreignTableId").combobox("getText"),customForeignKeyRelations:relations};/*$.post("customForeignKey.htm?add",dd,function(){dgForeignKey.datagrid("reload");foreignKeyDialog.dialog("close");});*/$.ajax({url:"customForeignKey.htm?add",type:"post",dataType:"json",contentType:"application/json",data:JSON.stringify(dd),success:function(){alert("success");}});按照⽹上所说,我将 ajax的 contentType:"application/json",将json对象改成json字符,在参数前⾯加上@RequestBody,可是传递到add ⽅法⾥之后,却发现还是个空,不仅⾥⾯的list没值,连那些 long、String类型的也都没有值,后经过⼏个⼩时的研究发现,原来是配置spring 的json的类型⾥少写了“application/json;charset=UTF-8”,导致没有应⽤到json的类型转换。
springmvc页⾯传值的⽅法,有5种。
springmvc 传值,有5种⽅法,(这篇⽂章为转载),1.request获取值:@RequestMapping("/request.action")public String request(HttpServletRequest request){String value= (String) request.getAttribute("value");String val=request.getParameter("value");return "index";}request的getAttribute和getParameter有什么区别呢?getAttribute:取得是setAttribute设定的值,session范围的值,可以设置为object,对象,字符串;getAttribute获取的值是web容器内部的,是具有转发关系的web组件之间共享的值;⽤于服务端重定向getParameter:取得是从web的form表单的post/get,或者url传过来的值,只能是String字符串;getParameter获取的值是web端传到服务端的,是获取http提交过来的数据;⽤于客户端重定向。
2.使⽤路径变量@PathVariable绑定页⾯url路径的参数,⽤于进⾏页⾯跳转@Controllerpublic class BaseController {@RequestMapping("/goUrl/{folder}/{file}")public String goUrl(@PathVariable String folder,@PathVariable String file){return folder+"/"+file;}}3.通过@RequestParam绑定页⾯传来的参数,效果跟String id=request.getParameter(“id”)是⼀样的:@RequestMapping("/test.action")public void test(@RequestParam("id") String id){System.out.println("id:"+id);}4.⾃动注⼊,实体类属性有setter,getter⽅法,前端form表单的name对应实体的属性名,后台直接可以通过该实体类⾃动把参数绑定到类的属性。
SpringMVC参数传递和接收的⼏种⽅式普通传参测试项⽬:SpringBoot2.0。
不使⽤ form 表单传参,后端不需要指定 consumes 。
使⽤ Postman 进⾏测试。
@PathVariable只能接收 URL 路径⾥的参数。
@RequestParam只能接收 URL 问号后跟着的参数,不管是 GET 还是 POST,虽然⼀般只有 GET 请求才会在 URL 后边跟参数,问号?后⾯的部分,使⽤& 区分参数。
http://localhost:8080/api/user/login/test?username=2222222&pass=333333333@RequestParam("username")String username,@RequestParam("pass")String pass@RequestBody只能接收请求体中的参数,也就是只能是 POST 请求才有请求体,GET 请求没有请求体,请求体分两种情况参数(1)使⽤String接收⽐如前端参数在请求体中传的是 username=185********&pass=12345,Content type 为 text/plain;charset=UTF-8则后台接收到的 param 即为 username=185********&pass=12345 格式@RequestBody String param(2)使⽤封装的 bean 或者 JSONObject 接收(常⽤)前端必须使⽤ JSON 格式的数据,Content-Type 必须为 application/json,请求体中参数为 {"username":"185********","pass":"12345"} @RequestBody User user@RequestBody JSONObject jsonObject测试代码@PostMapping("/login/test")public ResultBuilder userLogin1(@RequestHeader(Constants.ACCEPT_VERSION)String version,@RequestHeader(Constants.ACCESS_TOKEN)String token,@RequestParam("username")String username,@RequestParam("pass")String pass,@RequestBody User user){logger.debug("username======" + username);logger.debug("pass======" + pass);logger.debug("user---username==" + user.getUsername());logger.debug("user---pass==" + user.getPass());return new ResultBuilder(StatusCode.SUCCESS);}FORM表单传参测试项⽬:SpringBoot2.0GET⽅式前端表单传参<form action="http://localhost:8080/test" method="get"><input type="text" name="username"/><input type="text" name="password"/><input type="submit" value="Submit"/></form>后端参数接收,因为 form 表单使⽤ get ⽅法的时候,Content type 的值默认为空。
SpringMvcController请求传参⽅式总结1. 请求的值绑定在request中⽅法参数中使⽤request,通过request.getParameter("参数名")的⽅式获取参数参数拼接在url后⾯,以Get⽅式传参GET url= http://localhost:8080/geturlp?name=zhangsan或者以POST的表单提交的⽅式 x-www-form-urlencodedPOST url=http://localhost:8080/geturlpcurl -d "name=zhangsan" http://localhost:8080/geturlp1 @RequestMapping(value = "/geturlp")2 @ResponseBody3public String getParameterOfBasic(HttpServletRequest request){4 String name = request.getParameter("name");5return name;6 }2.简单类型参数和RequestParam注解如果请求参数和Controller⽅法的形参同名,可以直接接收(这种⽅式包含2个⽅式,以get请求的参数形式和POST的表单类型[x-www-form-urlencoded])GET url=http://localhost:8080/getdefaultParam?username=zhangsan&password=1223或者POST url=http://localhost:8080/getdefaultParamcurl -d "username=zhangsan&password=1223"1 @RequestMapping(value = "/getdefaultParam")2 @ResponseBody3public String getdefaultParam(String username,String password){4return username +":" + password;5 }如果请求参数和Controller⽅法的形参不同名,可以使⽤@RequestParam注解贴在形参前,设置对应的参数名称@RequestParam不能传递空值,如果需要传递空值,可以设置默认值defaultValue或者required=falsGET url=http://localhost:8080/getParam?username=zhangsan&password=123123或者POST url=http://localhost:8080/getParamcurl -d "username=zhangsan&password=123123"1 @RequestMapping(value = "/getParam")2 @ResponseBody3public String getParam(@RequestParam(value = "username",required = false) String name,4 @RequestParam(value = "password",defaultValue = "12312312") String pwd){5return name +":" + pwd;6 }3. 对象传参此时能够⾃动把参数封装到形参的对象上注意:1. 请求参数必须和对象的属性同名2. 此时对象会直接放⼊request作⽤域中,名称为类型⾸字母⼩写3. @ModelAttribute设置请求参数绑定到对象中并传到视图页⾯,设置key值GET url=http://localhost:8080/getObj?name=zhangsan&age=12&score=12或者POST url=http://localhost:8090/mbank/test/param/getObjcurl -d "name=zhangsan&age=12&score=12" http://localhost:8090/mbank/test/param/getObj1 @RequestMapping(value = "/getObj")2 @ResponseBody3public String getObjBindObj(Student student){4return student.toString();5 }1 @RequestMapping(value = "/getObj")2 @ResponseBody3public String getObjBindObj(@ModelAttribute("stu") Student student){4return student.toString();5 }如果前端使⽤json的格式传递数据,则可以使⽤注解@RequestBody注意:1. header中content-type:application/json2. body中使⽤json传递数据1 @Data2 @ToString3class Student{4private String name;5private int age;6private String score;7 }89 @RequestMapping(value = "/getObj")10 @ResponseBody11public String getObjBindObj(@RequestBody Student student){12return student.toString();13 }4. 数组和List集合类型参数注意:直接摘抄,没有做实验当前台页⾯传来的参数是参数名相同,参数值不同的多个参数时,可以直接封装到⽅法的数组类型的形参中,也可以直接封装到对象的集合属性中。
springcontroller如何对不同对象中相同的属性名注入不同的值Spring MVC开发当中,有时候需要对不同对象中相同的属性名注入不同的值。
通过下面自定义注解代码可解决问题。
新建注解类[java] view plaincopypackage com.cdt.uums.spring.resolver; import ng.annotation.Documented; importng.annotation.ElementType; importng.annotation.Retention; importng.annotation.RetentionPolicy; importng.annotation.Target;@Target(ElementType.PARAMETER)@Retention(RetentionPolicy.RUNTIME) @Documented public @interface RequestBean { String value() default "_def_param_name"; } 自定义注解类[java] view plaincopypackage com.cdt.uums.spring.resolver; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; importorg.springframework.beans.BeanWrapper; importorg.springframework.beans.BeanWrapperImpl; importorg.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.core.MethodParameter; import org.springframework.web.bind.support.WebArgumentResolver; importorg.springframework.web.context.request.NativeWebRequest; public class BeanArgumentResolver implements WebArgumentResolver{ @SuppressWarnings("rawtypes") public Object resolveArgument(MethodParameter param, NativeWebRequest request) throws Exception{ RequestBean requestBean =param.getParameterAnnotation(RequestBean.class);if (requestBean != null) { String _param = requestBean.value(); if(_param.equals("_def_param_name")){ _param =param.getParameterName(); }Class clazz = param.getParameterType();Object object = clazz.newInstance();HashMap<String, String[]> paramsMap = newHashMap<String, String[]>();Iterator<String> itor = request.getParameterNames(); while (itor.hasNext()) { String webParam = (String) itor.next(); String[] webValue = request.getParameterValues(webParam); if (webParam.startsWith(_param)){ paramsMap.put(webParam, webValue); } } BeanWrapper obj = new BeanWrapperImpl(object);//obj.findCustomEditor(paramClass, paramString)obj.registerCustomEditor(Date.class, null, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); //WebDataBinder.System.out.println(obj.findCustomEditor(Date.class,null).getAsText()); for (String propName : paramsMap.keySet()){ String[] propVals =paramsMap.get(propName); String[] props = propName.split("\\."); if (props.length == 2){ obj.setPropertyValue(props[1], propVals); } else if (props.length == 3){ Object tmpObj =obj.getPropertyValue(props[1]); if (tmpObj == null)obj.setPropertyValue(props[1],obj.getPropertyType(props[1]).newInstance());obj.setPropertyValue(props[1] + "." + props[2], propVals); } }/* * Field[] fields = clazz.getDeclaredFields(); for(Field *field:fields){ obj.setPropertyValue(field.getName(),* paramsMap.get(_param +"."+field.getName())); }* * for(StringporpName:paramsMap.keySet()){ String[] params =* paramsMap.get(porpName); if (null != params) { Object*field=obj.getPropertyValue(porpName.replaceFirst(_param+".", * "")); Class *clz=obj.getPropertyType(porpName.replaceFirst(_param+".", "")); *System.out.println(porpName.replaceFirst(_param+".",* "")+":"+field+" "+clz); if(field==null){ *//field=obj.getPropertyType(porpName.replaceFirst(_param+".",* "")).newInstance(); } *obj.setPropertyValue(porpName.replaceFirst(_param+".", ""), * params); } } */ /** Method[] methods = clazz.getMethods(); for (Method m : methods) { * Class[] parClazzs =m.getParameterTypes(); String methodName =* m.getName(); if (parClazzs.length == 1 &&* methodName.startsWith("set")) { ** String[] params = paramsMap.get(_param + * methodName.toLowerCase().replace("set", "."));* * if (parClazzs[0].equals(String.class)) { if (null != params) { * m.invoke(object, new Object[] { params[0] }); } } else if * (parClazzs[0].equals(String[].class)) { if (null != params){ * m.invoke(object, new Object[]{ params }); } } } * * }*/ return object; } else{ returnWebArgumentResolver.UNRESOLVED; } } }JSP页面<input name="mitteeName"id="mitteeName" value=""/> Spring 控制器中可通过@RequestBean("committeeInfo") CommitteeInfo committeeInfo的方式接收值.。
springMVC学习五参数传递(包括restful风格)(⼀)SpringMVC Controller接受参数的⽅式(1)前端传递的参数,在springMVC的controller中使⽤基本数据类型或者String 类型进⾏接受在前端有⼀个form表单,需要传递姓名和年龄,在controller可以采⽤基本数据类型或者String进⾏接受,<form action="demo" method="post">名字:<input type="text" name="name"/><br/>年龄:<input type="text" name="age"/><br/><input type="submit" value="提交"/><br/></form>此时值需要接受参数的名称和传递的参数名称⼀致就⾏fun01(String name,int age)@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(String name,int age) {//字符串的返回值代表代表要跳转的页⾯System.out.println(name);System.out.println(age);System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"return "/main.jsp";}}(2)前端传递的参数,在springMVC的controller中使⽤类类型进⾏接受(⾛get/set⽅法)此时需要类类型的属性名称与前端传递参数的参数名称⼀致@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(People peo) {//字符串的返回值代表代表要跳转的页⾯System.out.println(peo.getName());System.out.println(peo.getAge());System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"return "/main.jsp";}}(3)前端传递的参数,在springMVC的controller中使⽤HttpServletRequest进⾏接受@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(HttpServletRequest req) {//字符串的返回值代表代表要跳转的页⾯System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"System.out.println(req.getParameter("name"));System.out.println(req.getParameter("age"));return "/main.jsp";}}(4)前端传递的参数,在springMVC的controller中同时使⽤上述三中⽅法进⾏接受@Controllerpublic class DemoController {@RequestMapping("/demo")public String fun01(People peo, String name,int age,HttpServletRequest req) {//字符串的返回值代表代表要跳转的页⾯System.out.println(name);System.out.println(age);System.out.println(peo.getName());System.out.println(peo.getAge());System.out.println("指定了demo");//返回值最好写全路径,全路径就是以"/"开头的路径,否则就是相对路径,//相对路径就是以相对当前⽅法的映射路径,例如如果返回值是"main.jsp",是相对路径,最后的绝对路径是//"demo/main.jsp"System.out.println(req.getParameter("name"));System.out.println(req.getParameter("age"));return "/main.jsp";}}(⼆)@RequestParam()注解(1)如果请求参数名和⽅法参数名不对,使⽤value属性@RequestMapping("demo")public String demo(@RequestParam(value="name1") String name,@RequestParam(value="age1")int age){System.out.println("执⾏ demo"+" "+name+""+age);return "main.jsp";}(2)如果接受参数是基本类型,且接受参数类型与null⽆法进⾏兼容,此时可以采⽤包装类型或者采⽤默认值,使⽤defaultValue属性@RequestMapping("page")public String page(@RequestParam(defaultValue="2")int pageSize,@RequestParam(defaultValue="1") int pageNumber){ System.out.println(pageSize+" "+pageNumber); return "main.jsp";}(3)如果强制要求必须有某个参数,使⽤required属性@RequestMapping("demo2")public String demo2(@RequestParam(required=true) String name){ System.out.println("name 是 SQL 的查询条件,必须要传递 name 参数"+name); return "main.jsp";}(4)传递List类型的参数使⽤value属性,因为在前端传递过来的list都会放⼊⼀个参数名称中,只要把这个参数名称和⼀个List类型变量进⾏绑定@RequestMapping("demo5")public String demo5(String name,int age,@RequestParam("hover")List<String> abc){ System.out.println(name+" "+age+" "+abc); return "main.jsp";}(5)请求参数中对象.属性格式jsp中的代码如下<input type="text" name=""/><input type="text" name="peo.age"/>此时需要创建⼀个类,类中要有⼀个属性是peo,且这个属性的类型必须是包含name,age这个两个属性的类,两个类都要有get/set⽅法,Demo类型public class Demo {private People peo;public People getPeo() {return peo;}public void setPeo(People peo) {this.peo = peo;}@Overridepublic String toString() {return "Demo [peo=" + peo + "]";}}People 类型public class People {private String name;private Integer age;public String getName() {return name;}public void setName(String name) { = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "People [name=" + name + ", age=" + age + "]";}}controller 的接受参数@RequestMapping("demo6")public String demo6(Demo demo){ System.out.println(demo); return "main.jsp";}(三) restful风格的参数⾸先请求参数的格式⼀定的要求,⽼的⽅式是<a href="demo8?name=张三&age=23">跳转</a>,⽽restful格式是:<a href="demo8/123/abc">跳转</a>在控制器中:在@RequestMapping 中⼀定要和请求格式对应{名称} 中名称⾃定义名称@PathVariable 获取@RequestMapping 中内容,默认按照⽅法参数名称去寻找. @RequestMapping("demo8/{id1}/{name}")public String demo8(@PathVariable String name,@PathVariable("id1") int age){ System.out.println(name +" "+age); return "/main.jsp";}。
SpringMVC向页面传递参数的4种方式1、使用HttpServletRequest和Session 然后setAttribute(),就和Servlet 中一样request.setAttribute(“user”,user_data);2、使用ModelAndView对象@RequestMapping("/login.do")publicModelAndView login(String name,String pass){User user = userService.login(name,pwd);Map<String,Object> data = new HashMap<String,Object>();data.put("user",user);return newModelAndView("success",data);}3、使用ModelMap对象ModelMap数据会利用HttpServletRequest的Attribute传值到success.jsp中@RequestMapping("/login.do")public String login(String name,String pass ,ModelMapmodelMap){User user =userService.login(name,pwd);modelMap.addAttribute("user",user);modelMap.put("name",name);return "success";}Session存储,可以利用HttpServletReequest的getSession()方法@RequestMapping("/login.do")Public String login (String name,Stringpwd,ModelMapmodel,HttpServletRequest request) {User user = serService.login(name,pwd);HttpSession session = request.getSession();session.setAttribute("user",user);model.addAttribute("user",user);return "success";}4、使用@ModelAttribute注解@ModelAttribute数据会利用HttpServletRequest的Attribute传值到success.jsp中@RequestMapping("/login.do")public String login(@ModelAttribute("user") User user){return "success";}@ModelAttribute("name")public String getName(){return name;}Spring MVC 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作A、使用RedirectViewpublicModelAndView login(){RedirectView view = new RedirectView("regirst.do");return newModelAndView(view);}B、使用redirect:前缀public String login(){return "redirect:regirst.do";}。
SpringMVC:前台jsp页⾯和后台传值前台jsp页⾯和后台传值的⼏种⽅式: 不⽤SpringMVC⾃带的标签前台---->后台,通过表单传递数据():1.jsp页⾯代码如下, modelattribute 有没有都⾏<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%><%@taglib prefix="sf" uri="/tags/form"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Insert title here</title></head><body><form method="post" enctype="multipart/form-data">Username:<input type="text" name="username"/><sf:errors path="username">Password:<input type="password" name="password"/><sf:errors path="password">Nickname:<input type="text" name="nickname"/></br>Email<input type="text" name="email"/></form></body></html>2.写Action,如下两种⽅式都可以: 第⼀种,表单的name属性值必须和接受的参数同名。