controller层中,参数的获取方式以及作用域的问题

时间:2023-03-08 21:29:43
 package com.krry.web;

 import javax.servlet.http.HttpServletRequest;

 import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import bean.User; @Controller
@RequestMapping("/model")
public class ModelMapController extends BaseController {
/********参数获取的方式**************************/ //http://localhost/krryxa/model/hanlder/1.html
@RequestMapping("/handler/{id}")
public String handler(@PathVariable("id")Integer id){
//获得参数id为1
return "redirect:/success.jsp";
} //http://localhost/krryxa/model/handler2.html?id=5
@RequestMapping("/handler2")
public String handler2(Integer id){
//获得参数id为5
System.out.println(id);
return "redirect:/success.jsp";
} //通过对象的的注入方式最好
//http://localhost/krryxa/model/handler3.html?username=1351
@RequestMapping("/handler3")
public String handler3(User user){
//获得参数username为1351
System.out.println(user.getUsername());
return "redirect:/success.jsp";
} //http://localhost/krryxa/model/handler4.html?id=5
@RequestMapping("/handler4")
public String handler4(@ModelAttribute("teacher")User user){//若sessiong域中teacher改变了,这里也会改变
//获得参数id为5
System.out.println(request.getParameter("id"));
return "redirect:/success.jsp";
} /**作用域的问题reuqest session application 以下作用域的范围都是:request**/ //在index页面直接用${message}获取
@RequestMapping("/handler7")
public String handler7(ModelMap map){
//这里是map的addAttribute设置
map.addAttribute("message", "我爱你吗。你们爱我我吗");
return "model/index";
} //在index页面直接用${message}获取
@RequestMapping("/handler5")
public String handler5(){
request.setAttribute("message", "我爱你吗。你们爱我我吗");
return "model/index";
} //在index页面直接用${message}获取
@RequestMapping("/handler6")
public ModelAndView handler6(){
//视图和作用域融合体
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("model/index"); //跳转到这个页面
modelAndView.addObject("message", "是打发是大法师的发送到发士大夫阿什顿");
return modelAndView;
}
//在index页面直接用${user.username}获取
@RequestMapping("/handler8")
public String handler8(@ModelAttribute("user")User user){
user.setUsername("ModelAttribute 我爱你吗。你们爱我吗");
return "model/index";
} }