springweb30MVC注解附实例Word文档格式.docx
《springweb30MVC注解附实例Word文档格式.docx》由会员分享,可在线阅读,更多相关《springweb30MVC注解附实例Word文档格式.docx(53页珍藏版)》请在冰点文库上搜索。
![springweb30MVC注解附实例Word文档格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/4/a7e31297-2739-4c20-b284-29b7ce4939d7/a7e31297-2739-4c20-b284-29b7ce4939d71.gif)
//www.springframework.org/schema/beans
http:
//www.springframework.org/schema/beans/spring-beans-2.5.xsd"
beanclass="
org.springframework.web.servlet.mvc.
DefaultAnnotationHandlerMapping"
/>
AnnotationMethodHandlerAdapter"
...(controllerbeandefinitions)...
/beans>
例1:
雁联zfpt-servlet.xml
配置DefaultAnnotationHandlerMapping和/或AnnotationMethodHandlerAdapter
context:
component-scanbase-package="
com.ylink.zfpt.web.spring"
beanid="
annotationHandlerMapping"
class="
org.springframework.web.servlet.mvc.annotation.
<
propertyname="
order"
value>
1<
/value>
/property>
interceptors"
<
list>
<
refbean="
sessionInterceptor"
superUserInterceptor"
/list>
/bean>
webBindingInitializer"
com.ylink.zfpt.web.spring.ZfptBindingInitializer"
com.ylink.zfpt.web.intercepor.SessionInterceptor"
class="
com.ylink.zfpt.web.intercepor.SuperUserAccessInterceptor"
例2:
web.xml
ISO-8859-1"
web-appversion="
2.4"
xmlns=xmlns:
xsi:
display-name>
SpringPetClinic<
/display-name>
<
description>
SpringPetClinicsampleapplication<
/description>
2.1webAppRootKey
!
--
Keyofthesystempropertythatshouldspecifytherootdirectoryofthis
webapp.AppliedbyWebAppRootListenerorLog4jConfigListener.
-->
context-param>
param-name>
webAppRootKey<
/param-name>
param-value>
petclinic.root<
/param-value>
/context-param>
2.3log4jConfigLocation
LocationoftheLog4Jconfigfile,forinitializationandrefreshchecks.
AppliedbyLog4jConfigListener.
log4jConfigLocation<
/WEB-INF/classes/log4j.properties<
2.4contextConfigLocation
-LocationoftheXMLfilethatdefinestherootapplicationcontext.
-AppliedbyContextLoaderServlet.
-
-Canbesetto:
-"
/WEB-INF/applicationContext-hibernate.xml"
fortheHibernateimplementation,
/WEB-INF/applicationContext-jpa.xml"
fortheJPAone,or
/WEB-INF/applicationContext-jdbc.xml"
fortheJDBCone.
contextConfigLocation<
/WEB-INF/spring/applicationContext-jdbc.xml
/WEB-INF/applicationContext-security.xml
/WEB-INF/spring/applicationContext-hibernate.xml<
/WEB-INF/spring/applicationContext-jpa.xml<
-->
TousetheJPAvariantabove,youwillneedtoenableSpringload-time
weavinginyourserverenvironment.Outofthebox,Springwilltryto
detecttherunningenvironmentandusetheappropriateweaverbutifthat
fails,onemustenableonebyhandorusetheVM-wideweaver.
SeePetClinic'
sreadmeand/orSpring'
sJPAdocumentationformoreinformation.
2.5springSecurityFilterChain
filter>
filter-name>
springSecurityFilterChain<
/filter-name>
filter-class>
org.springframework.web.filter.DelegatingFilterProxy
/filter-class>
/filter>
filter-mapping>
url-pattern>
/*<
/url-pattern>
/filter-mapping>
2.6Log4jConfigListener
-ConfiguresLog4Jforthiswebapp.
-Asthiscontextspecifiesacontext-param"
log4jConfigLocation"
itsfilepath
-isusedtoloadtheLog4Jconfiguration,includingperiodicrefreshchecks.
-WouldfallbacktodefaultLog4Jinitialization(non-refreshing)ifnospecial
-context-paramsaregiven.
-Exportsa"
webapprootkey"
i.e.asystempropertythatspecifiestheroot
-directoryofthiswebapp,forusageinlogfilepaths.
-Thiswebappspecifies"
petclinic.root"
(seelog4j.propertiesfile).
--Leavethelistenercommented-outifusingJBoss-->
listener>
listener-class>
org.springframework.web.util.Log4jConfigListener<
/listener-class>
/listener>
2.7ContextLoaderListener
-Loadstherootapplicationcontextofthiswebappatstartup,
-bydefaultfrom"
/WEB-INF/applicationContext.xml"
.
-NotethatyouneedtofallbacktoSpring'
sContextLoaderServletfor
-J2EEserversthatdonotfollowtheServlet2.4initializationorder.
-UseWebApplicationContextUtils.getWebApplicationContext(servletContext)
-toaccessitanywhereinthewebapplication,outsideoftheframework.
-Therootcontextistheparentofallservlet-specificcontexts.
-Thismeansthatitsbeansareautomaticallyavailableinthesechildcontexts,
-bothforgetBean(name)callsand(external)beanreferences.
org.springframework.web.context.ContextLoaderListener
2.8DispatcherServlet
-Servletthatdispatchesrequesttoregisteredhandlers(Controllerimplementations).
-Hasitsownapplicationcontext,bydefaultdefinedin"
{servlet-name}-servlet.xml"
-i.e."
petclinic-servlet.xml"
-
-Awebappcancontainanynumberofsuchservlets.
-Notethatthiswebapphasasharedrootapplicationcontext,servingasparent
-ofallDispatcherServletcontexts.
-->
servlet>
servlet-name>
petclinic<
/servlet-name>
servlet-class>
org.springframework.web.servlet.DispatcherServlet
/servlet-class>
load-on-startup>
2<
/load-on-startup>
/servlet>
-Mapsthepetclinicdispatcherto"
*.do"
.Allhandlermappingsin
-petclinic-servlet.xmlwillbydefaultbeappliedtothissubpath.
-Ifamappingisn'
ta/*subpath,thehandlermappingsareconsidered
-relativetothewebapproot.
-NOTE:
Asingledispatchercanbemappedtomultiplepaths,likeanyservlet.
servlet-mapping>
/<
/servlet-mapping>
2.9exception.java
error-page>
exception-type>
java.lang.Exception<
/exception-type>
--Displaysastacktrace-->
location>
/WEB-INF/jsp/uncaughtException.jsp<
/location>
/error-page>
例3:
雁联web.xml
如果你想要自定义映射策略,显式的定义一个DefaultAnnotationHandlerMapping和/或AnnotationMethodHandlerAdapter也有实际意义。
例如,指定一个自定义的PathMatcher或者WebBindingInitializer
1.一个简单的基于注解的Controller
使用过低版本SpringMVC的读者都知道:
1.当创建一个Controller时,我们需要直接或间接地实现org.springframework.web.servlet.mvc.Controller接口。
一般情况下,我们是通过继承SimpleFormController或MultiActionController来定义自己的Controller的。
2.在定义Controller后,一个重要的事件是在SpringMVC的配置文件中通过HandlerMapping定义请求和控制器的映射关系,以便将两者关联起来。
3.来看一下基于注解的Controller是如何定义做到这一点的,下面是使用注解的BbtForumController:
实现效果:
启动Tomcat,发送http:
//localhost/forum.doURL请求,BbtForumController的listAllBoard()方法将响应这个请求,并转向WEB-INF/jsp/listBoard.jsp的视图页面。
清单1.BbtForumController.java
packagecom.baobaotao.web;
importcom.baobaotao.service.BbtForumService;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.ModelAttribute;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importjava.util.Collection;
@Controller//<
——①
@RequestMapping("
/forum.do"
)
publicclassBbtForumController{
@Autowired
privateBbtForumServicebbtForumService;
@RequestMapping//<
——②
publicStringlistAllBoard(){
bbtForumService.getAllBoard();
System.out.println("
calllistAllBoardmethod."
);
return"
listBoard"
;
}
}
在①处使用了两个注解,分别是@Controller和@RequestMapping。
在“使用Spring2.5基于注解驱动的IoC”这篇文章里,笔者曾经指出过@Controller、@Service以及@Repository和@Component注解的作用是等价的:
将一个类成为Spring容器的Bean。
由于SpringMVC的Controller必须事先是一个Bean,所以@Controller注解是不可缺少的。
真正让BbtForumController具备SpringMVCController功能的是@RequestMapping这个注解。
@RequestMapping可以标注在类定义处,将Controller和特定请求关联起来;
还可以标注在方法签名处,以便进一步对请求进行分流。
在①处,我们让BbtForumController关联“/forum.do”的请求,而②处,我们具体地指定listAllBoard()方法来处理请求。
所以在类声明处标注的@RequestMapping相当于让POJO实现了Controller接口,而在方法定义处的@RequestMapping相当于让POJO扩展Spring预定义的Controller(如SimpleFormController等)。
清单2.web.xml:
启用Spring容器和SpringMVC框架
为了让基于注解的SpringMVC真正工作起来,需要在SpringMVC对应的xxx-servlet.xml配置文件中做一些手脚。
在此之前,还是先来看一下web.xml的配置吧
web-appxmlns="
version="
2.5"
SpringAnnotationMVCSample<
--Spring服务层的配置文件-->