spring bootspring mvc前后端传值怎么传值

前端页面通过thymeleaf渲染
    &dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-starter-thymeleaf&/artifactId&
&/dependency&
前后端的传递关键在html上面,请看代码:
&!DOCTYPE html&
&html xmlns:th="http://www.thymeleaf.org"&
&meta charset="UTF-8" /&
&title&Insert title here&/title&
&link rel="stylesheet" href="/bootstrap/3.3.4/css/bootstrap.min.css" /&
&div class="container"&
&div class="row clearfix"&
&div class="col-md-3 column"&
&form role="form" method="POST" th:action="@{/userLogin}" th:object="${user}"&
&label for="username"&Name&/label&&input type="text" class="form-control" id="username" th:field="*{name}" /&
&label for="password"&Password&/label&&input type="password" class="form-control" id="password" th:field="*{password}" /&
&button type="submit" class="btn btn-default"&Sign in&/button&
&ul class="nav nav-pills"&
&li role="presentation"&&a href="register.html" class="href" target="_blank"&Sign up&/a&&/li&
th:action="@{/userLogin}" 表示这个form表单的action会指向/userLogin
th:object="${user}" 表示form表单的内容会以user的形式传递
th:field:"*{name}" 表示该input输入的值,也就是前端的值存储在name中
如果你在前端输入name=jwen,password=1234,当这个表单提交的时候,就会把name=jwen,password=1234存放在user中传递给/userLogin
那么看看controller层怎么接接收这个的&
@RequestMapping(value = "/userLogin", method = RequestMethod.POST)
String userLogin(User user, Model model) {
boolean verify = userService.verifyUser(user);
if (verify) {
model.addAttribute("name", user.getName());
model.addAttribute("password", user.getPassword());
return "result";
return "redirect:/notVerify";
requestMapping将/userLogin绑定给userLogin方法,该方法的入参是一个User的实例,一个Model的实例
而这个User的实例,就是我们从前端传递的,就是说你在userLogin方法,可以得到前端传递的东西;
阅读(...) 评论()spring boot 如何实现controller和html的分离?
我想分模块把部分html提取到maven的另一个模块中,那么springboot会根据不同的application映射到不同模块的html吗?
你走了弯路哈
一般前后端分开,那么后端提供restful接口,前端就不会用tomcat等java服务器了,就使用nginx,node.js等服务器了,同时使用cdn等技术进行加速;
然后在应用部署,实行容器化部署,根据版本来进行部署
你两个模块最终是打包成一个项目部署的吗,如果不是,只能说不行。
其实我觉得你可以把业务Controller+(控制跳转Controller+Page 一个工程)这样处理。&
--- 共有 1 条评论 ---
最终肯定是打包成一个的,但是开发的时候希望分模块开发,所以尽量分开业务
we used to separate front-end & back-end.
here is an example :
angular : controller & business logical
spring mvc : rest service&
spring boot : integration all component into one application .
--- 共有 1 条评论 ---
看上去前端无论如何也要在一个模块中是吧?Spring MVC 前后端传值方式心得笔记_Linux编程_Linux公社-Linux系统门户网站
你好,游客
Spring MVC 前后端传值方式心得笔记
来源:Linux社区&
作者:cnn237111
前端传到Controller:
通过HttpServletRequest 。写法如下:
@Controller
public class MyTestController {
@RequestMapping("/print")
public String PrintInfo(HttpServletRequest request) {
System.out.println("name:" +request.getParameter("name"));
System.out.println("age:" + request.getParameter("age"));
return "testpage";
HttpServletRequest类是Servlet中的类型,代表了一个Servlet请求。无论Post还是Get请求,都能通过这种方式获取到。
比如上面的代码,通过Get方法,如下地址
http://127.0.0.1:8080/WebApp/print?name=zhangsan&age=30
也可以通过Post方法,使用Postman工具模拟一个post请求,都可以将值传到Controller。
这招可以获得Cookie以及Session数据。
还可以通过注解@Autowired,将HttpServletRequest 自动的注入进来,不必担心多线程下的并发问题,因为这里HttpServletRequest注入的是一个AOP proxy ,而不是一个普通bean 。每次请求过来,都会检查线程本地属性,来获取真正的Request对象。这些都是Spring自动配置的默认场景。可以参阅https://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-scopes-other-injection
但是不推荐使用这个方法,因为这种方法破坏了对一个注入对象的常规理解,造成混乱。
代码如下:
@Controller
public class MyTestController {
@Autowired
private HttpServletR
@RequestMapping(value="/print")
public String PrintInfo() {
System.out.println("name:" +request.getParameter("name"));
System.out.println("age:" + request.getParameter("age"));
return "testpage";
使用路径变量。写法如下:
@Controller
public class MyTestController {
@RequestMapping("/print/{name}/{age}")
public String PrintInfo(@PathVariable String name, @PathVariable int age) {
System.out.println("name:" + name);
System.out.println("age:" + age);
return "testpage";
@RequestMapping中的{}中即为路径变量,该变量还需要在方法的参数值出现,并且标记@PathVariable。
通过URL匹配的方式既可以实现传值,这是REST风格的一种传值方式。
上面的例子,只需输入URL:
http://127.0.0.1:8080/WebApp/print/ZhangSan/30
controller接收到传值,输出:
name:ZhangSan
@RequestMapping("/print/{name}/{age}")是@RequestMapping(Value="/print/{name}/{age}")的缩写形式,本质上是一样的。
参数名匹配的方式:
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(String name, int age) {
System.out.println("name:" +name);
System.out.println("age:" + age);
return "testpage";
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(@RequestParam("name") String name,@RequestParam("age") int age) {
System.out.println("name:" +name);
System.out.println("age:" + age);
return "testpage";
当请求传入的参数名字和controller
中代码的名字一样的时候,两种方式都可以,区别在于使用了注解@RequestParam,可以设置一个默认值来处理到null值。
@RequestParam(value="name", defaultValue="John")
但是如果请求中参数的名字和变量名不一样的时候,就只能使用@RequestParam注解。例如请求的参数为如下的时候:
http://localhost:8080/WebApp/print?user_name=somename&user_age=30
Controller代码只能如下的写法
@RequestMapping(value="/print")
public String PrintInfo(@RequestParam("user_name") String name, @RequestParam("user_age")int age) {
尽量使用@RequestParam注解,因为这样可以清晰的知道该参数来自Request,可读性高。
传递请求头中的参数,需要用到@RequestHeader注解,该注解将Header中的值绑定到参数上,可以获取一个,多个或者所有的参数。例如
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(@RequestHeader Map&String, String& headers) {
for (String elem: headers.keySet()) {
System.out.println(elem + " : " + headers.get(elem));
return "testpage";
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(@RequestHeader("User-Agent") String userAgent) {
System.out.println("12");
System.out.println("name:" +userAgent);
//System.out.println("age:" + age);
return "testpage";
使用到@RequestBody注解,得到整个RequestBody的信息
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(@RequestBody String body) {
System.out.println("body:" +body);
return "testpage";
@RequestBody可以将Json数据直接映射程Java对象。例如:
采用@ModelAttribute注解,命名匹配,Post中的参数值和Model中的参数值一致的话,会自动绑定到该值。
@Controller
public class MyTestController {
@RequestMapping(value="/print")
public String PrintInfo(@ModelAttribute User user) {
System.out.println("6");
System.out.println("Name:" +user.getName());
System.out.println("Age:" +user.getAge());
return "testpage";
public class User {
public String getName() {
public void setName(String name) {
this.name =
public int getAge() {
public void setAge(int age) {
this.age =
然后当Post的值中有name和age时,Controller中的user对象会自动附上值。
Controller传递到JSP
使用ModelAndView类,代码如下:
@RequestMapping("/hello")
public ModelAndView showMessage() {
ModelAndView mv = new ModelAndView("helloworld");
mv.addObject("userList", GetUserList());
public List&User& GetUserList()
List&User& lst=new ArrayList&User&();
User user1=new User();
user1.setName("zhangsan");
user1.setAge(20);
lst.add(user1);
User user2=new User();
user2.setName("lisi");
user2.setAge(30);
lst.add(user2);
JSP页面中:
&%@ page language="java" contentType="text/ charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%&
&%@ taglib prefix="c" uri="/jsp/jstl/core" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&
&meta http-equiv="Content-Type" content="text/ charset=ISO-8859-1"&
&title&Spring 4 MVC -HelloWorld&/title&
&c:forEach items="${userList}" var="user"&
${user.name} ${user.age}
&/c:forEach&
ModelAndView 初始化的时候,设置了view的名字,同时也把对象存起来,直接传给view。简单实用。
使用Model或者ModelMap
(Model是一个接口,ModelMap实现了Model接口)
该方法和ModelAndView方法相似,只是Model和View分开来了,通过返回一个String来找到View,Model是注入到Controller的一个参数,通过对它添加属性,在jsp端读取值。代码如下:
@Controller
public class HelloWorldController {
String message = "Welcome to Spring MVC!";
@RequestMapping("/hello")
public String showMessage(Model model) {
model.addAttribute("userList", GetUserList());
return "helloworld";
public List&User& GetUserList()
List&User& lst=new ArrayList&User&();
User user1=new User();
user1.setName("zhangsan");
user1.setAge(10);
lst.add(user1);
User user2=new User();
user2.setName("lisi");
user2.setAge(33);
lst.add(user2);
JSP页面中:
&%@ page language="java" contentType="text/ charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%&
&%@ taglib prefix="c" uri="/jsp/jstl/core" %&
&!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&
&meta http-equiv="Content-Type" content="text/ charset=ISO-8859-1"&
&title&Spring 4 MVC -HelloWorld&/title&
&c:forEach items="${userList}" var="user"&
${user.name} ${user.age}
&/c:forEach&
SpringMVC总结篇&
Spring+SpringMVC企业快速开发架构搭建&
SpringMVC的乱码处理&
Spring MVC整合Freemarker基于注解方式 &
SpringMVC详细示例实战教程
SpringMVC 异常处理&
Spring + Spring MVC + Ibatis + Velocity 框架搭建&
本文永久更新链接地址:
相关资讯 & & &
& (05月06日)
& (02月15日)
& (06月21日)
& (05月06日)
& (01月22日)
   同意评论声明
   发表
尊重网上道德,遵守中华人民共和国的各项有关法律法规
承担一切因您的行为而直接或间接导致的民事或刑事法律责任
本站管理人员有权保留或删除其管辖留言中的任意内容
本站有权在网站内转载或引用您的评论
参与本评论即表明您已经阅读并接受上述条款springMVC 前后台传值与接收值 -
- ITeye博客
博客分类:
@Controller@RequestMapping("/user")@SessionAttributes("loginUser")public class UserController {
@RequestMapping(value={"/","/hello"})
public String hello(int id,Map&String,Object& map) {
map.put("hellokey", "world");
return "hello";
// hello.jsp页面取值 用 $("hellokey") 就可以取到值 world
@RequestMapping(value="/say")
public String say(@RequestParam int id,Model model) {
model.addAttribute("hello", "value");
//使用Object的类型作为key,String--&string
model.addAttribute("ok");
return "hello";// hello.jsp页面取值 用 $("String") 就可以取到值 world
@RequestMapping("/req")
public String req(HttpServletRequest req) {
System.out.println(req.getParameter("username"));
return "hello";
@RequestMapping({"/users","/"})
public String list(Model model) {
model.addAttribute("users",users);//map
return "user/list";
@RequestMapping(value="/{username}/update",method=RequestMethod.POST)
public String update(@PathVariable String username,@Valid User user,BindingResult br,Model model) {
if(br.hasErrors()) {
return "user/update";
// 会找到user文件夹下的update.jsp页面
users.put(username, user);
return "redirect:/user/users";
//相当于跳转另外一个链接
总结:@PathVariable 当 @RequestMapping(value="/{username}/update",method=RequestMethod.POST)
时使用,rest风格
@RequestParam
接收一个简单类型的参数 当@RequestMapping(value="/say")时使用,普通风格
接收一个对象类型的参数,例如@Valid User user
对应前台页面如下:
&%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %&&!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/ charset=UTF-8"&&title&Insert title here&/title&&/head&&body&&sf:form method="post" modelAttribute="user"&UserName:&sf:input path="username"/&&sf:errors path="username"/&&br/&Password:&sf:password path="password"/&&sf:errors path="password"/&&br/&Nickname:&sf:input path="nickname"/&&sf:errors path="nickname"/&&br/&Email: &sf:input path="email"/&&sf:errors path="email"/&&br/&&input type="submit"/&&/sf:form&
浏览: 49268 次
来自: 西安
AND EMPNAME LIKE '%${empname}%' ...详解Spring Boot Web项目之参数绑定
作者:nicekk
字体:[ ] 类型:转载 时间:
本篇文章主要介绍了详解Spring Boot Web项目之参数绑定,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
一、@RequestParam
这个注解用来绑定单个请求数据,既可以是url中的参数,也可以是表单提交的参数和上传的文件
它有三个属性,value用于设置参数名,defaultValue用于对参数设置默认值,required为true时,如果参数为空,会报错
好,下面展示具体例子:
首先是vm:
&h1&param1:${param1}&/h1&
&h1&param2:${param2}&/h1&
好吧,就为了展示两个参数
第一种情况:
@RequestMapping(value = "/hello1.htm")
public String hello1(ModelMap modelMap,Integer param1, int param2) {
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
这里前面的参数时包装型,后面的参数时原始类型
直接用url请求:
http://localhost:8080/hello1.htm?param1=1&param2=2
如果不传param2:  
http://localhost:8080/hello1.htm?param1=1
直接就报错了
因为无法将null转换为原始类型
所以:建议所有的参数都用包装类型,别用原始类型
第二种情况:
仍然是上面的那个controller,地址改为
http://localhost:8080/hello1.htm?param2=1&param1=2
就是让param2=1,param1=2,想试验下,参数绑定是和顺序有关,还是只和参数名称有关,结果:
所以,springMvc参数绑定只和参数名字有关系
第三种情况:
如果页面上表单里的参数和代码里的参数名不一样怎么办,这时候就可以用注解了:&
@RequestMapping(value = "/hello1.htm")
public String hello1(ModelMap modelMap, @RequestParam(value = "paramTest") Integer param1, Integer param2) {
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
在param1前面加上了注解,这时候第一个参数只接受paramTest名字的参数,param1此时无效了。
如果此时我们这么请求:
http://localhost:8080/hello1.htm?param1=1&param2=2
spring直接报错,必须要这么请求了:
http://localhost:8080/hello1.htm?paramTest=1&param2=2
&第四种情况:
有时候页面上的表单客户不填任何值,但是在控制器里希望它有默认值
可以这样:
@RequestMapping(value = "/hello1.htm")
public String hello1(ModelMap modelMap, @RequestParam(defaultValue = "5") Integer param1, Integer param2) {
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
这里用了RequestParam的defaultValue属性,如果url参数中没传param1,也不会报错,使用默认值,比如我们这么请求:
http://localhost:8080/hello1.htm?param2=2
但是,如果url中对param1赋值了:
http://localhost:8080/hello1.htm?param1=3&param2=2
也就是说,我们赋的值会修改默认值
第五种情况:
RequestParam还有个属性:required
意思是必须传值,否则报错,就是这么任性
@RequestMapping(value = "/hello1.htm")
public String hello1(ModelMap modelMap, @RequestParam(required = true) Integer param1, Integer param2) {
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
但是当required=true,和defaultValue= 同时出现时,required失效,可传可不传
简单类型参数绑定小结:
springMVC默认根据参数名字来绑定,而不是参数位置
使用包装类型,否则如果不传值,会报错
使用@RequestParam(value="")来改变参数名字
使用@RequestParam(defaultValue=""),不传参时,使用默认值
使用@RequestParam(required=true),强制必须传参数
&二、@PathVariable
用这个注解可以将URL中的占位符参数绑定到控制器处理方法的入参中,可以这样用:
@RequestMapping("/hello2.htm/{param1}/{param2}")
public String hello2(ModelMap modelMap, @PathVariable Integer param1, @PathVariable Integer param2) {
System.out.println("进入了hello2控制器");
System.out.println(param1 + "," + param2);
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
http://localhost:8080/hello2.htm/1/2
如果不加PathVariable注解,是无法绑定的
@RequestMapping("/hello2.htm/{param1}/{param2}")
public String hello2(ModelMap modelMap,Integer param1, @PathVariable Integer param2) {
System.out.println("进入了hello2控制器");
System.out.println(param1 + "," + param2);
modelMap.addAttribute("param1", param1);
modelMap.addAttribute("param2", param2);
return "hello";
去掉了第一个参数的注解:
http://localhost:8080/hello2.htm/1/2
传了空值到页面,无法绑定
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 spring boot开源后端 的文章

 

随机推荐