您的位置:首页 > 编程语言 > Java开发

Spring MVC

2015-10-29 00:00 483 查看

基于注解驱动的 Spring MVC 3.0

工作机制

配置方式

Web.xml

<!-- Spring Context初始化的配置文件 -->

<context-param>

<param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/spring/*-config.xml

</param-value>

</context-param>

<!-- Spring 容器启动监听器 -->

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

<!--

Servlet 配置与之对应的要有一个配置文件:

{servletname}-servlet.xml

此例应为:WEB-INF/flex-servlet.xml

-->

<servlet>

<servlet-name>flex</servlet-name>

<servlet-class>

org.springframework.web.servlet.DispatcherServlet

</servlet-class>

<async-supported>true</async-supported>

<load-on-startup>2</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>flex</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

{servlet name}-servlet.xml

<!—

对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能

-->

<!--Supporting Spring MVC Infrastructure for RESTful @Controllers -->

<context:component-scanbase-package="com.dn" use-default-filters="false">

<context:include-filter

expression="org.springframework.stereotype.Controller"

type="annotation"/>

</context:component-scan>

<!—注解驱动方式 -->

<mvc:annotation-driven/>

<mvc:default-servlet-handler/>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<propertyname="mediaTypes">
<map>
<entrykey="amf" value="application/x-amf"/>
</map>
</property>
<propertyname="defaultViews">
<list>
<beanclass="org.springframework.flex.http.AmfView" />
</list>
</property>
</bean>

<beanid="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"></property>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
</bean>
prefix:则为前缀,也就是目录的地址, 一般以"WEB-INF/xx"为主,若为"/" 则为全局使用
suffix:则为后缀,也就是文件名的后缀.使用InternalResourceViewResolver类是只支持jsp,不支持html等其他后缀,如果强制加入其他后缀的话会出现死循环

基本知识

常用注解元素

@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 StringsetupForm(@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 ModelMapvetsHandler() {

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")

publicclassSinglePathWithController {}

@Controller

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

publicclassAdapterMultiPathController {}

@Controller

@RequestMapping(value = "/rest")

publicclassRestWithController {}

无返回

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

后缀组成

@RequestMapping("/springmvc/common")

publicvoidnovoid(HttpServletRequest request) {

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

}

http://localhost:8088/framework-web/springmvc/common

返回字符串

1、 作为视图路径方式

//根据路径直接匹配

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

publicString multiReqPath1(HttpServletRequest request){

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

return"springmvc/common";

}

http://localhost:8088/framework-web/springmvc/multiReqPath1.do

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

publicString multiReqPath2(HttpServletRequest request){

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

return"/springmvc/common";

}

http://localhost:8088/framework-web/springmvc/multiReqPath2.do

//根据参数匹配

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

publicString method1(){

return"login/success";

}

http://localhost:8088/framework-web/login.do?m=method1&name=test

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

@RequestMapping(params = "m=method2")

publicString method2(String name,String pwd){

return name;

}

http://localhost:8088/framework-web/login.do?m=method2&name=success

http://localhost:8088/framework-web/login.do?m=method2&name=test

//测试下不存在的jsp时的情况

http://localhost:8088/framework-web/login.do?m=method2&name=testunexist

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

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

publicString method3(@RequestParam("loginName")String name,@RequestParam("loginPwd")String pwd,HttpServletRequest request){

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

return"login/"+name;

}

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&loginPwd=123456

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&loginPwd=123456789

//如果参数名与@RequestParam(参数名) 不一致时会报错

http://localhost:8088/framework-web/login.do?m=method3&loginName=test&pwd=123456

2、 作为Response内容方式

//无参数

@ResponseBody

@RequestMapping(params = "m=method4")

publicString method4(){

return"hello,guys";

}

http://localhost:8088/framework-web/login.do?m=method4

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

@ResponseBody

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

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

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

}

http://localhost:8088/framework-web/login.do?m=method5&name=rick&pwd=123&delay=10000

@ResponseBody

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

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

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

}

http://localhost:8088/framework-web/login.do?m=method6&userName=rick&type=DnType&name=rick&value=rick&id=10000

http://localhost:8088/framework-web/login.do?m=method6&userName=rick&type=DnType&name=austin&value=austin&id=10001

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

返回ModelAndView

@RequestMapping("/springmvc/modelAndView")

publicModelAndView modelAndView(){

ModelAndView mav = newModelAndView();

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

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

return mav;

}

http://localhost:8088/framework-web/springmvc/modelAndView

返回ModelMap

@RequestMapping("/springmvc/modelMap")

publicModelMap modelMap(ModelMap modMap){

List<String> names = newArrayList<String>();

names.add("Rick");

names.add("Austin");

modMap.put("names", names);

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

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

return modMap;

}

http://localhost:8088/framework-web/springmvc/modelMap

返回ModelMap

@RequestMapping("/springmvc/modelMap")

publicModelMap modelAndView(ModelMap modMap){

List<String> names = newArrayList<String>();

names.add("Rick");

names.add("Austin");

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

modMap.put("names", names);

return modMap;

}

http://localhost:8088/framework-web/springmvc/modelMap

@SessionAttribute &ModMap

//注解方式

@Controller

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

publicclassAdapterMultiPathController {}

//方法体

@RequestMapping("/springmvc/modelMap2")

publicModelMap modelMapWithSession(ModelMap modMap,HttpServletRequest request){

List<String> names = newArrayList<String>();

names.add("Rick");

names.add("Austin");

modMap.put("names",names);

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

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

UserBean user = newUserBean();

user.setName("Rick");

user.setMobile("18938900256");

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

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

modMap.put("currentUser", user);

return modMap;

}

//初次请求

http://localhost:8088/framework-web/springmvc/modelMap2

spring mvc & reverse ajax

@ResponseBody

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

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

req.startAsync();

Date startTime = newDate();

try {

Thread.currentThread().sleep(delay);

} catch (InterruptedException e) {

e.printStackTrace();

}

Date entTime = newDate();

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");

}

http://localhost:8088/framework-web/login.do?m=method7&name=rick&pwd=1234566&delay=10000

RestFull

@Controller

@RequestMapping(value = "/rest")

publicclassRestWithController {}

@ResponseBody

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

publicString restString(@PathVariableString msg) {

return msg;

}

http://localhost:8088/framework-web/rest/messageone

@ResponseBody

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

publicString restXml(@PathVariableString path,@PathVariableString value) {

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

}

http://localhost:8088/framework-web/rest/xmlresources/assestlist

@ResponseBody

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

publicString restFile(@PathVariableString filename) {

if (filename!=null) {

ProjectInits init = ProjectInits.getInstance();

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

FileUtility fUtil = newFileUtility();

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

return content;

}

else

return"Invalid xmlfile name ["+filename+"]";

}

http://localhost:8088/framework-web/rest/xml/AddOnSelection

验证 是否支持Overload

方式一

//验证是否支持Overload

@ResponseBody

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

publicString overloadMethod(String name){

return name;

}

http://localhost:8088/framework-web/validate/overload1?name=rick
@ResponseBody

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

publicString overloadMethod(String name,DnTest test){

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

}

http://localhost:8088/framework-web/validate/overload2?name=rick

方式二

/验证是否支持Overload

@ResponseBody

@RequestMapping(params = "m=method11")

publicString method11(String name){

return name;

}

@ResponseBody

@RequestMapping(params = "m=method11")

publicString method11(int age,DnTest test){

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

}

http://localhost:8088/framework-web/login.do?m=method11&name=rick

参考资料

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/

http://blog.springsource.org/2009/03/08/rest-in-spring-3-mvc/

http://www.congci.com/item/spring,mvc,restful,url

http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

http://hi.baidu.com/sunnysunshien/blog/item/6d5cbd536e18a5521138c27b.html

http://www.ibm.com/developerworks/cn/java/j-lo-spring25-mvc/

版权声明:本文为博主原创文章,未经博主允许不得转载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SpringMVC