/**\
* SpringMVC自动注入
* @author Administrator
*
*/
@Controller
public class DemoController {
/**
* SpringMVC很厉害,有自动注入的功能,当form表单中值的name与实体类的
* 属性名一样时,会自动注入实体类,如果不一样,会设为实体类里的属性设
* 置一个null值,如果实体类里有基本数据类型,不能设置为null,则报错400
* @param product
*/
@RequestMapping("demo1"
)
public void demo1(Product product) {
System.out.println(product);
}
/**
* 如果前端传过来的值的名称与参数的名称相同,SpringMVC会自动注入
* 如果名称不相同,可以通过注解来解决
* RequestParam("value") value 为前端传过来值的名称
* @param name
* @param price
*/
@RequestMapping("demo2"
)
public void demo2(@RequestParam("name") String name1,@RequestParam("price")
int price1) {
System.out.println(name1+" "+
price1);
}
/**
* 加上required后代表该属性一定要被赋值,否则报错
* @param name
* @param price
*/
@RequestMapping("demo3"
)
public void demo3(@RequestParam(required=
true)String name,@RequestParam()
int price) {
System.out.println(name+" "+
price);
}
}
/**
* 当浏览器传过来有多个同名参数时,用一个集合来接收,并且使用@RequestParam
*/
@RequestMapping("demo4"
)
public String demo4(@RequestParam("hover")List<String>
list) {
System.out.println(list);
//跳转到login.jsp
return "/login.jsp"
;
}
当浏览器传的值要赋给类里面的类属性时:
<a href="demo5?teacher.name=teacherName">show!!</a>
控制器方法:
/**
* 浏览器传来的值要赋给一个类里的对象属性时
*/
@RequestMapping("demo5"
)
public String demo5(Student studnet) {
System.out.println(studnet);
return "/login.jsp"
;
}
Student class:
public class Student {
private String name;
private Teacher teacher;
当浏览器传的值要赋给类里面的集合时:
表单:
<form action="demo6" method="get">
<input type="text" name="teacherList[0].name">
<input type="text" name="teacherList[1].name">
<input type="submit" value="add" />
</form>
控制器类:
/**
* 浏览器传来的值要赋给一个类里的对象属性时
*/
@RequestMapping("demo5"
)
public String demo5(Student studnet) {
System.out.println(studnet);
return "/login.jsp"
;
}
@RequestMapping("demo6"
)
public String demo6(Student student) {
System.out.println(student);
return "/login.jsp"
;
}
实体类Student:
public class Student {
private List<Teacher> teacherList;
新新技术 使用restful传值:
<a href="demo7/requestName/999">restful</a>
/**
* restful传值方式,比传统的书写更方便,新项目都会采用
* 使用{}来取值,{}里的名字自定义
* 在参数里使用@PathVariable注解
*/
@RequestMapping("demo7/{name}/{level}"
)
public String demo7(@PathVariable("name")String name,@PathVariable("level")
int level) {
System.out.println(name+" "+
level);
return "/login.jsp"
;
}
转载于:https://www.cnblogs.com/lastingjava/p/10013705.html
相关资源:springmvc框架已做service注入