SpringMVC基础知识
作者:互联网
1,注解
@Controller
负责注册一个bean到spring context中
@Controller("tmpController")
类名称开头字母必须小写
@RequestMapping("/register")
@RequestMapping(value="",method ={"",""},headers={},params={"",""})
method 请求方法 method=RequestMethod.POST GET,HEAD,POST,PUT,DELETE
headers一般结合method = RequestMethod.POST使用
value 请求URL ? * **
params 请求参数 {"param1 !=value1","param2"}
@RequestMapping("/{userId}")
Public ModelAndView showDetail(@PathVariable("userId") String userId){}
将URL中的占位符参数绑定到控制器处理方法的参数中
@RequestParam(value="",required=true,defaultValue="")
value 参数名
required 默认true,必须包含此参数,不包含则抛出异常
defaultValue默认参数
@ResponseBody
方法声明了注解@ResponseBody ,则会直接将返回值输出到页面
@ModelAttribute("xxx")
应用于方法参数,参数可以在页面直接获取
@SessionAttributes
只能声明在类上,指定 ModelMap中的哪些属性需要转存到 session中
@CookieValue
获取cookie信息
@RequestHeader
获取请求的头部信息
2,返回模型和视图
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView mv = new ModelAndView("/user/index");
mv.addObject("xxx",xxx);
return mv;
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView mv = new ModelAndView();
mv.addObject("xxx",xxx);
mv.setViewName("/user/index");
return mv;
}
@RequestMapping(method=RequestMethod.GET)
public Map<String,String> index(){
Map<String,String> map = new HashMap<String,String>();
map.put("name",lsf);
return map;
}
@RequestMapping(method=RequestMethod.GET)
public String index(Model model){
String retVal="user/index";
List users=userService.getUsers();
model.addAttribute("users",users);
return retVal;
}
对于String类型的返回值,常配合Model一起使用
@RequestMapping(value="/valid",method=RequestMethod.GET)
public @ResponseBody String valid(@RequestParam(value="userId",required=false) Integer userId,
@RequestParam(value="logName") String strLogName){
return String.valueOf(!userService.isLogNameExist(strLogName,userId));
}
String返回类型配合@ResponseBody将内容或对象作为HTTP相应正文返回(适合做验证)
@RequestMapping("/welcome")
public void index(){
ModelAndView mv = new ModelAndView();
mv.addObject("xxx",xxx);
}
返回的视图页面对应为访问地址,本例是welcome
使用void,map,Model时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成
3,增删改查
@RequestMapping(value="/persion",method=RequestMethod.POST)
public String post(Model model){
//新增逻辑
return "/result.jsp";
}
@RequestMapping(value="/person/{name}",method=RequestMethod.GET)
public String get(@PathVariable("name") String name,Model model){
//根据名称查找逻辑
return "/result.jsp";
}
@RequestMapping(value="/person/{name}",method=RequestMethod.DELETE)
public String delete(@PathVariable("name") String name,Model model){
//删除逻辑
return "/result.jsp";
}
@RequestMapping(value="/person/{name}",method=RequestMethod.PUT)
public String put(@PathVariable("name") String name,Model model){
//更新逻辑
return "/result.jsp";
}
4,转发重定向
return "redirect:/index.jsp";
return "forward:/index.jsp";
标签:return,RequestMapping,SpringMVC,value,基础知识,RequestMethod,method,String 来源: https://www.cnblogs.com/wang1018-kuiying/p/14169285.html