一:写入控制器方法
1.通过ServletAPI向Request域对象进行共享
@RequestMapping("/testRequestByServletAPI")
public String testRequestByServletAPI(HttpServletRequest request){//调用ServletAPI请求作为形参
request.setAttribute("testRequestScope","Hello ServletAPI!!");//传递参数(第一个对应参数名,第二个是传递的参数内容)
return "success"; //跳转到对应的前端页面
}
2.通过ModelAndView向Request域对象进行共享
public ModelAndView testModelAndView(ModelAndView modelAndView){
modelAndView.addObject("testAndView","hello,ModelAndView");
modelAndView.setViewName("success");
return modelAndView;
}
3.通过Model向Request域对象进行共享
@RequestMapping("/testModel")
public String testModel(Model model){
model.addAttribute("testModel","Hello,Model");
return "success";
}
4.通过Map向Request域对象进行共享
@RequestMapping("/testMap")
public String testMap(Map<String,Object> map){
map.put("testMap","hello,Map!");
return "success";
}
5.通过ModelMap向Request域对象进行共享
@RequestMapping("/testModelMap")
public String testMap(ModelMap modelMap){
modelMap.addAttribute("modelMap","hello,modelMap!");
return "success";
}
二:编写对应的前端页面(JSP为例)
1.index.jsp
<%@ taglib prefix="th" uri="http://www.springframework.org/tags" %>
<%--
Created by IntelliJ IDEA.
User: 86159
Date: 2022/4/16
Time: 15:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<a href="/testRequestByServletAPI.do">ServletAPI方法</a><br>
<a href="/testModelAndView.do">ModeAndView方法</a><br>
<a href="/testModel.do">Model方法</a><br>
<a href="/testMap.do">Map方法</a><br>
<a href="/testModelMap.do">ModelMap方法</a><br>
</body>
</html>
2.success.jsp
<%--@elvariable id="testRequestScope" type="com.zhan.HelloController.ContextController"--%>
<%@ taglib prefix="th" uri="http://www.springframework.org/tags" %>
<%--
Created by IntelliJ IDEA.
User: 86159
Date: 2022/4/16
Time: 15:34
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试域对象共享</title>
</head>
<body>
<h1>域对象共享成功!</h1>
<%-- 获取request请求中参数 --%>
<%=request.getAttribute("testRequestScope")%><br>
<%=request.getAttribute("testAndView")%><br>
<%=request.getAttribute("testModel")%><br>
<%=request.getAttribute("testMap")%><br>
<%=request.getAttribute("testModelMap")%>
</body>
</html>
三:结果
点击对应的方法(即不同的地址映射请求),就会在对应请求中出现参数, 如: