SpringMVC常用基础知识[转]

常用注解元素

@Controller

标注在Bean的类定义处

@RequestMapping

真正让Bean具备 Spring MVC Controller 功能的是 @RequestMapping 这个注解

@RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;

还可以标注在方法签名处,以便进一步对请求进行分流

配套的属性有:

value 需要跳转的地址

method 基于RestFul的跳转参数,有RequestMethod.get  post  put  delete等

params 符合某个参数的时候才调用该方法

Headers 符合头信息的时候才调用

@SessionAttributes

将结果放入session内

@ModelAttribute

存储在响应内容ModelMap或者ModelAndView进行保存值传到前台,当如果你需要保存值比较少

的时候可以采用这种方式进行保存值并且保存到前台显示

在默认情况下,ModelMap 中的属性作用域是 request 级别,相当于HttpServletRequest中的request.setAttribute() 一样,在 JSP 视图页面中通过 request.getAttribute(“attribute name”) 或者通过

${ attribute name } EL 表达式访问模型对象中的 属性对象

如果希望在ModelMap 的作用域范围为 session,可以有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现 如:

@Controller

@RequestMapping("/login.do")

@SessionAttributes("currUser")

public class BbtForumController {。。。。。}

@ResponseBody

标注后  返回String对象的结果为response内容体,不标注的话  作为dispatcher url使用

@PathVariable

允许将请求路径的制定内容当做求情的参数使用

返回类型

请求处理方法入参的可选类型                                                   说明

void                                       此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:

@RequestMapping("/welcome.do")

public void welcomeHandler() {

}

对应的逻辑视图名为“welcome”

String                                    此时逻辑视图名为返回的字符,如以下的方法:

@RequestMapping(method = RequestMethod.GET)

public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {

Owner owner = this.clinic.loadOwner(ownerId);

model.addAttribute(owner);

return "ownerForm";

}

对应的逻辑视图名为“ownerForm”

ModelMap                            和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL,

如下面的例子:

@RequestMapping("/vets.do")

public ModelMap vetsHandler() {

return new ModelMap(this.clinic.getVets());

}

对应的逻辑视图名为“vets”,返回的 ModelMap 将被作为请求对应的模型对象,

可以在 JSP 视图页面中访问到。

ModelAndView

返回方式

1 使用无返回方法跳转,如果使用返回方法进行跳转的话,则会通过视图解析器进行以

prefix(前缀)+方法名+suffix(后缀)组成的页面文件名称.

2 使用一个返回的字符串方法作为跳转,使用字符串跳转的话好处就是在return的时候可

以自己指定返回的名字,JSP组成是prefix(前缀)+返回的字符串+suffix(后缀)

3 返回一个ModelAndView类型,使用setViewName方法则可以跳转到指定的页面.

路径匹配形式

1、单一Controller   对应 单一的请求路径

2、单一Controller   对应多个请求路径

3、单一Controller  对应多个请求路径,且路径内可以含有参数的形式

Demo code and UseCase

@Controller

@RequestMapping("/login.do")

public class SinglePathWithController {}

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

public class AdapterMultiPathController {}

@Controller

@RequestMapping(value = "/rest")

public class RestWithController {}

无返回

//无返回值  无参数返回的是根据 prefix前缀+@RequestMapping value +suffix

后缀组成

@RequestMapping("/springmvc/common")

public voidnovoid(HttpServletRequest request) {

request.setAttribute("message", "novoid方法被调用");

}

返回字符串

1、  作为视图路径方式

//根据路径直接匹配

@RequestMapping("/springmvc/multiReqPath1.do")

public String multiReqPath1(HttpServletRequest request){

request.setAttribute("message", "multiReqPath1方法被调用");

return "springmvc/common";

}

@RequestMapping("/springmvc/multiReqPath2.do")

public String multiReqPath2(HttpServletRequest request){

request.setAttribute("message", "multiReqPath2方法被调用");

return "/springmvc/common";

}

//根据参数匹配

@RequestMapping(params = "m=method1",method = RequestMethod.GET)

public String method1(){

return "login/success";

}

//有参数  参数名和请求url内的变量名一致

@RequestMapping(params = "m=method2")

public String method2(String name,String pwd){

return name;

}

//有参数 参数名和请求url内的变量名不一致

@RequestMapping(params = "m=method3",method = RequestMethod.GET)

public String method3(@RequestParam("loginName")Stringname,@RequestParam("loginPwd")String pwd,HttpServletRequest request){

request.setAttribute("message",(name + " " + pwd));

return "login/"+name;

}

2、  作为Response内容方式

//无参数

@ResponseBody

@RequestMapping(params = "m=method4")

public String method4(){

return "hello,guys";

}

//处理方法入参如何绑定 URL 参数

@ResponseBody

@RequestMapping(params = "m=method5",method = RequestMethod.GET)

public String method5(String name,String pwd,int delay){

return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay;

}

@ResponseBody

@RequestMapping(params = "m=method6",method = RequestMethod.GET)

public String method6(@RequestParam("userName")String name,DnTest test){

return "DnTest:"+test.toString();

}

URL 参数: userName参数将绑定到name上  其他与DnTest类内属性名称一致的参数将绑定到test的对应的属性上,如果参数不全  也不会报错

返回ModelAndView

@RequestMapping("/springmvc/modelAndView")

public ModelAndView modelAndView(){

ModelAndView mav = new ModelAndView();

mav.setViewName("/springmvc/common");

mav.addObject("message", "modelAndView 方法被调用");

return mav;

}

返回ModelMap

@RequestMapping("/springmvc/modelMap")

public ModelMap modelMap(ModelMap modMap){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("names", names);

modMap.put("message", "hello guys");

modMap.put("comment", "hello guys");

return modMap;

}

返回ModelMap

@RequestMapping("/springmvc/modelMap")

public ModelMap modelAndView(ModelMap modMap){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("hello", "hello guys");

modMap.put("names", names);

return modMap;

}

@SessionAttribute & ModMap

//注解方式

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

public class AdapterMultiPathController {}

//方法体

@RequestMapping("/springmvc/modelMap2")

public ModelMap modelMapWithSession(ModelMap modMap,HttpServletRequest request){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("names",names);

modMap.put("message", "hello guys");

modMap.put("comment", "hello guys");

UserBean user = new UserBean();

user.setName("Rick");

user.setMobile("[1**********]");

user.setTelephone(request.getParameter("userPhone"));

user.setNumber(request.getParameter("userNumber"));

modMap.put("currentUser", user);

return modMap;

}

//初次请求

spring mvc & reverse ajax

@ResponseBody

@RequestMapping(params = "m=method7",method = RequestMethod.GET)

public String method7(String name,String pwd,int delay,HttpServletRequest req){

req.startAsync();

Date startTime = new Date();

try {

Thread.currentThread().sleep(delay);

} catch (InterruptedException e) {

e.printStackTrace();

}

Date entTime = new Date();

return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay+",startTime:"+

DateUtils.formatDate(startTime, "yyyy-MM-dd HH:mm:ss:SSS")+",endTime:"+

DateUtils.formatDate(entTime, "yyyy-MM-dd HH:mm:ss:SSS");

}

RestFull

@Controller

@RequestMapping(value = "/rest")

public class RestWithController {}

@ResponseBody

@RequestMapping(value = "/{msg}", method = RequestMethod.GET)

public String restString(@PathVariable String msg) {

return msg;

}

@ResponseBody

@RequestMapping(value = "/{path}/{value}", method = RequestMethod.GET)

public String restXml(@PathVariable String path,@PathVariable String value) {

return "path:"+path+",value:"+value;

}

@ResponseBody

@RequestMapping(value = "/xml/{filename}", method = RequestMethod.GET)

public String restFile(@PathVariable String filename) {

if (filename!=null) {

ProjectInits init = ProjectInits.getInstance();

String dir = init.get("resource.dir", "C:/Projects/VoyagerWeb/resources");

FileUtility fUtil = new FileUtility();

String content = fUtil.readFile(dir+"/"+filename+".xml");

return content;

}

else

return "Invalid xml file name ["+filename+"]";

}

验证 是否支持Overload

方式一

//验证 是否支持Overload

@ResponseBody

@RequestMapping(value = "/validate/overload1", method = RequestMethod.GET)

public String overloadMethod(String name){

return name;

}

@ResponseBody

@RequestMapping(value = "/validate/overload2", method = RequestMethod.GET)

public String overloadMethod(String name,DnTest test){

return "DnTest:"+test.toString();

}

方式二

/验证 是否支持Overload

@ResponseBody

@RequestMapping(params = "m=method11")

public String method11(String name){

return name;

}

@ResponseBody

@RequestMapping(params = "m=method11")

public String method11(int age,DnTest test){

return "DnTest:"+test.toString();

}

常用注解元素

@Controller

标注在Bean的类定义处

@RequestMapping

真正让Bean具备 Spring MVC Controller 功能的是 @RequestMapping 这个注解

@RequestMapping 可以标注在类定义处,将 Controller 和特定请求关联起来;

还可以标注在方法签名处,以便进一步对请求进行分流

配套的属性有:

value 需要跳转的地址

method 基于RestFul的跳转参数,有RequestMethod.get  post  put  delete等

params 符合某个参数的时候才调用该方法

Headers 符合头信息的时候才调用

@SessionAttributes

将结果放入session内

@ModelAttribute

存储在响应内容ModelMap或者ModelAndView进行保存值传到前台,当如果你需要保存值比较少

的时候可以采用这种方式进行保存值并且保存到前台显示

在默认情况下,ModelMap 中的属性作用域是 request 级别,相当于HttpServletRequest中的request.setAttribute() 一样,在 JSP 视图页面中通过 request.getAttribute(“attribute name”) 或者通过

${ attribute name } EL 表达式访问模型对象中的 属性对象

如果希望在ModelMap 的作用域范围为 session,可以有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现 如:

@Controller

@RequestMapping("/login.do")

@SessionAttributes("currUser")

public class BbtForumController {。。。。。}

@ResponseBody

标注后  返回String对象的结果为response内容体,不标注的话  作为dispatcher url使用

@PathVariable

允许将请求路径的制定内容当做求情的参数使用

返回类型

请求处理方法入参的可选类型                                                   说明

void                                       此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:

@RequestMapping("/welcome.do")

public void welcomeHandler() {

}

对应的逻辑视图名为“welcome”

String                                    此时逻辑视图名为返回的字符,如以下的方法:

@RequestMapping(method = RequestMethod.GET)

public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {

Owner owner = this.clinic.loadOwner(ownerId);

model.addAttribute(owner);

return "ownerForm";

}

对应的逻辑视图名为“ownerForm”

ModelMap                            和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL,

如下面的例子:

@RequestMapping("/vets.do")

public ModelMap vetsHandler() {

return new ModelMap(this.clinic.getVets());

}

对应的逻辑视图名为“vets”,返回的 ModelMap 将被作为请求对应的模型对象,

可以在 JSP 视图页面中访问到。

ModelAndView

返回方式

1 使用无返回方法跳转,如果使用返回方法进行跳转的话,则会通过视图解析器进行以

prefix(前缀)+方法名+suffix(后缀)组成的页面文件名称.

2 使用一个返回的字符串方法作为跳转,使用字符串跳转的话好处就是在return的时候可

以自己指定返回的名字,JSP组成是prefix(前缀)+返回的字符串+suffix(后缀)

3 返回一个ModelAndView类型,使用setViewName方法则可以跳转到指定的页面.

路径匹配形式

1、单一Controller   对应 单一的请求路径

2、单一Controller   对应多个请求路径

3、单一Controller  对应多个请求路径,且路径内可以含有参数的形式

Demo code and UseCase

@Controller

@RequestMapping("/login.do")

public class SinglePathWithController {}

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

public class AdapterMultiPathController {}

@Controller

@RequestMapping(value = "/rest")

public class RestWithController {}

无返回

//无返回值  无参数返回的是根据 prefix前缀+@RequestMapping value +suffix

后缀组成

@RequestMapping("/springmvc/common")

public voidnovoid(HttpServletRequest request) {

request.setAttribute("message", "novoid方法被调用");

}

返回字符串

1、  作为视图路径方式

//根据路径直接匹配

@RequestMapping("/springmvc/multiReqPath1.do")

public String multiReqPath1(HttpServletRequest request){

request.setAttribute("message", "multiReqPath1方法被调用");

return "springmvc/common";

}

@RequestMapping("/springmvc/multiReqPath2.do")

public String multiReqPath2(HttpServletRequest request){

request.setAttribute("message", "multiReqPath2方法被调用");

return "/springmvc/common";

}

//根据参数匹配

@RequestMapping(params = "m=method1",method = RequestMethod.GET)

public String method1(){

return "login/success";

}

//有参数  参数名和请求url内的变量名一致

@RequestMapping(params = "m=method2")

public String method2(String name,String pwd){

return name;

}

//有参数 参数名和请求url内的变量名不一致

@RequestMapping(params = "m=method3",method = RequestMethod.GET)

public String method3(@RequestParam("loginName")Stringname,@RequestParam("loginPwd")String pwd,HttpServletRequest request){

request.setAttribute("message",(name + " " + pwd));

return "login/"+name;

}

2、  作为Response内容方式

//无参数

@ResponseBody

@RequestMapping(params = "m=method4")

public String method4(){

return "hello,guys";

}

//处理方法入参如何绑定 URL 参数

@ResponseBody

@RequestMapping(params = "m=method5",method = RequestMethod.GET)

public String method5(String name,String pwd,int delay){

return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay;

}

@ResponseBody

@RequestMapping(params = "m=method6",method = RequestMethod.GET)

public String method6(@RequestParam("userName")String name,DnTest test){

return "DnTest:"+test.toString();

}

URL 参数: userName参数将绑定到name上  其他与DnTest类内属性名称一致的参数将绑定到test的对应的属性上,如果参数不全  也不会报错

返回ModelAndView

@RequestMapping("/springmvc/modelAndView")

public ModelAndView modelAndView(){

ModelAndView mav = new ModelAndView();

mav.setViewName("/springmvc/common");

mav.addObject("message", "modelAndView 方法被调用");

return mav;

}

返回ModelMap

@RequestMapping("/springmvc/modelMap")

public ModelMap modelMap(ModelMap modMap){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("names", names);

modMap.put("message", "hello guys");

modMap.put("comment", "hello guys");

return modMap;

}

返回ModelMap

@RequestMapping("/springmvc/modelMap")

public ModelMap modelAndView(ModelMap modMap){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("hello", "hello guys");

modMap.put("names", names);

return modMap;

}

@SessionAttribute & ModMap

//注解方式

@Controller

@SessionAttributes(types = {UserBean.class,String.class},value={"currentUser","message"})

public class AdapterMultiPathController {}

//方法体

@RequestMapping("/springmvc/modelMap2")

public ModelMap modelMapWithSession(ModelMap modMap,HttpServletRequest request){

List names = new ArrayList();

names.add("Rick");

names.add("Austin");

modMap.put("names",names);

modMap.put("message", "hello guys");

modMap.put("comment", "hello guys");

UserBean user = new UserBean();

user.setName("Rick");

user.setMobile("[1**********]");

user.setTelephone(request.getParameter("userPhone"));

user.setNumber(request.getParameter("userNumber"));

modMap.put("currentUser", user);

return modMap;

}

//初次请求

spring mvc & reverse ajax

@ResponseBody

@RequestMapping(params = "m=method7",method = RequestMethod.GET)

public String method7(String name,String pwd,int delay,HttpServletRequest req){

req.startAsync();

Date startTime = new Date();

try {

Thread.currentThread().sleep(delay);

} catch (InterruptedException e) {

e.printStackTrace();

}

Date entTime = new Date();

return "name:"+name+","+"pwd:"+pwd+","+"delay:"+delay+",startTime:"+

DateUtils.formatDate(startTime, "yyyy-MM-dd HH:mm:ss:SSS")+",endTime:"+

DateUtils.formatDate(entTime, "yyyy-MM-dd HH:mm:ss:SSS");

}

RestFull

@Controller

@RequestMapping(value = "/rest")

public class RestWithController {}

@ResponseBody

@RequestMapping(value = "/{msg}", method = RequestMethod.GET)

public String restString(@PathVariable String msg) {

return msg;

}

@ResponseBody

@RequestMapping(value = "/{path}/{value}", method = RequestMethod.GET)

public String restXml(@PathVariable String path,@PathVariable String value) {

return "path:"+path+",value:"+value;

}

@ResponseBody

@RequestMapping(value = "/xml/{filename}", method = RequestMethod.GET)

public String restFile(@PathVariable String filename) {

if (filename!=null) {

ProjectInits init = ProjectInits.getInstance();

String dir = init.get("resource.dir", "C:/Projects/VoyagerWeb/resources");

FileUtility fUtil = new FileUtility();

String content = fUtil.readFile(dir+"/"+filename+".xml");

return content;

}

else

return "Invalid xml file name ["+filename+"]";

}

验证 是否支持Overload

方式一

//验证 是否支持Overload

@ResponseBody

@RequestMapping(value = "/validate/overload1", method = RequestMethod.GET)

public String overloadMethod(String name){

return name;

}

@ResponseBody

@RequestMapping(value = "/validate/overload2", method = RequestMethod.GET)

public String overloadMethod(String name,DnTest test){

return "DnTest:"+test.toString();

}

方式二

/验证 是否支持Overload

@ResponseBody

@RequestMapping(params = "m=method11")

public String method11(String name){

return name;

}

@ResponseBody

@RequestMapping(params = "m=method11")

public String method11(int age,DnTest test){

return "DnTest:"+test.toString();

}


相关内容

  • 高级JAVA工程师需要掌握哪些技术
  • 我把它分为了五大专题 工程化专题 工程化专题 git git安装使用 git日常使用:fetch/pull/push/revert/rebase git分支管理git flow Jenkins多套环境(test/pre/production)系统自动化发布 Jenkins自动发布到远程主机 Mave ...

  • 大数据平台项目方案
  • 大数据平台建设方案 (项目需求与技术方案) 一.项目背景 "十三五"期间,随着我国现代信息技术的蓬勃发展,信息化建设模式发生根本性转变, 一场以云计算.大数据.物联网.移动应用等技术为核心的"新 IT"浪潮风起云涌,信息化应用进入一个"新常态&quo ...

  • 模块化建立项目流程(Maven聚合模块)
  • 先说项目使用Maven的好处 1.项目构建.Maven定义了软件开发的整套流程体系,并进行了封装,开发人员只需要指定项目的构建流程,无需针对每个流程编写自己的构建脚本. 2.依赖管理.除了项目构建,Maven最核心的功能是软件包的依赖管理,能够自动分析项目所需要的依赖软件包,并到Maven中心仓库去 ...

  • BAT及各大互联网公司2014前端笔试面试题
  • #2.JavaScript的数据类型都有什么?基本数据类型:String,boolean,Number,Undefined, Null引用数据类型:Object(Array,Date,RegExp,Function)那么问题来了,如何判断某变量是否为数组数据类型?方法一.判断其是否具有"数 ...

  • 自我介绍大学公司训练
  • 自我介绍 各位面试官: 大家好! 我是XX ,毕业于XXXXX ,主修计算机软件开发专业 我曾经参与了生态文明工程管理系统.中国移动合作招募系统等几个项目的开发,经过这几个项目,我对目前比较主流的框架如:struts .hibernate .spring 有了深入的了解,对oracle .mysql ...

  • 网上订餐系统
  • 网上订餐系统 摘要 二十一世纪是一个集数字化,网络化,信息化的,以网络为核心的社会.中国的网民充分领略到"畅游天地间,网络无极限" 所带来的畅快.随着Internet 的飞速发展,使得网络的应用日益的广泛.如电子商务,电子政务,网上医疗,网上娱乐,网络游戏,网络教学等.本次毕业设 ...

  • 酒店管理系统需求调研报告
  • 中软国际 酒店管理系统 需求调研报告 文件信息 修改历史 目录 文件信息 ................................................................... 1 修改历史 ...................................... ...

  • 孟莉附件7[1].22新入职护士规范化培训大纲
  • 附件 新入职护士规范化培训大纲(征求意见稿) 一.适用范围 各级各类综合医院,其他医疗卫生机构参照执行. 二.培训目标 根据<护士条例>等,结合推进优质护理服务工作要求,开展新入职护士的规范化培训.通过培训,使新入职护士掌握从事临床护理工作的基础理论.基本知识和基本技能:具备良好的职业道 ...

  • 中医护理基础知识手册
  • 中医护理基础知识手册 一.中医基础知识问答题. 1.中医学的基本特点是什么? 答:是整体观念和辨证论治. 2.何谓五脏六腑? 答:心.肝.脾.肺.肾称五脏.胆.胃.小肠.大肠.膀胱.焦合称六腑. 3.心的主要生理功能是什么? 答.心主血脉.主神志.主汗液.其华在面,开窍于舌. 4.肝的主要生理功能是 ...