SpringMVC后台传递数据到页面(Model来传参和域对象传参)

SpringMVC后台传递参数到页面

控制器中的参数传递到页面,常见的有两种方式:

方式一: 通过Model来传参(model对象来传递)

 

 


 
 
  1. @Controller
  2. @RequestMapping( “mfc”)
  3. public class FirstController {
  4. @RequestMapping(value= “fr”)
  5. public String secondRequest(Model model){
  6. String key = “hello world”;
  7. model.addAttribute( “key”, key);
  8. //此时没有定义变量的名字,默认就用这个参数的类型的名字做为变量的名字,不过首字母大写变小写
  9. model.addAttribute( “xxxxxxx”);
  10. return “show”;
  11. }
  12. }



model中有两个方法可以使用:model.addAttribute(object)和model.addAttribute(“名字”,object)。


传递后,在页面上通过EL表达式来获取,show页面代码如下:



 
 
  1. <%@ page language=“java” contentType=“text/html; charset=utf-8” pageEncoding=“utf-8”%>
  2. <!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
  3. <html>
  4. <head>
  5. <meta http-equiv=“Content-Type” content=“text/html; charset=utf-8”>
  6. <title>Insert title here </title>
  7. </head>
  8. <body>
  9. <h2>这里是show.jsp页面 </h2>
  10. 通过model传递到页面的参数key: KaTeX parse error: Expected 'EOF', got '&' at position 30: …ass="hljs-tag">&̲lt;<span class=…{string } <br/>
  11. </body>
  12. </html>



方式二: 通过内置对象来传递

除了model传递参数以外,我们还可以通过request,session来传递,代码如下:

 

 
 
  1. @Controller
  2. @RequestMapping( “mfc”)
  3. public class FirstController {
  4. @RequestMapping(value= “fr”)
  5. public String secondRequest(HttpServletRequest request,HttpSession session){
  6. request.setAttribute( “req”, “通过request存放的参数”);
  7. session.setAttribute( “ses”, “session中的数据”);
  8. return “show”;
  9. }
  10. }

页面上,还是通过EL表达式来获取,show页面内容如下:


 
 
  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. <title>Insert title here </title>
  7. </head>
  8. <body>
  9. <h2>这里是show.jsp页面 </h2>
  10. 获取request中的参数:${req } <br/>
  11. 获取session中的参数:${ses }
  12. </body>
  13. </html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值