|
SpringMVC背景介绍Spring框架提供了构建Web?http://baike.baidu.com/view/330120. htm应用程序的全功能MVC模块。使用Spring可插入的MVC架构,可以选择是使用内置的SpringWeb框架 还是Struts这样的Web框架。通过策略接口,Spring框架是高度可配置的,而且包含多种http://baike.b aidu.com/view/71981.htm视图技术,例如JavaServerPages(JSP)技术、Velocity、T iles、iText和POI。SpringMVC框架并不知道使用的视图,所以不会强迫您只使用JSP技术。Spring MVC分离了控制器、模型http://baike.baidu.com/view/2387.htm对象、分派器以及处理程序对象的角 色,这种分离让它们更容易进行定制。常见MVC框架比较运行性能上:Jsp+servlet>struts1>springmvc>st ruts2+freemarker>>struts2,ognl,值栈。开发效率上,基本正好相反。值得强调的是,springmvc开 发效率和struts2不相上下。Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用fre emaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。基于spring2.5的采用XML配置的sprin gMVC项目注:本项目全部基于XML配置。同时,集成了hibernate。采用的是:springMVC+hibernate+s pring的开发架构。建立web项目导入jar包(spring.jar,spring-webmvc.jar,commons- logging.jar。其他jar包为hibernate相关jar包)修改web.xml如下:"encoding="UTF-8"?>.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-i nstance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeeht tp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">>let-name>dispatcherServletorg.spr ingframework.web.servlet.DispatcherServlet-param>contextConfigLocationue>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/servi ce-config.xml,/WEB-INF/dao-config.xml 1>dispatcherServlet.d o增加web-config.xml(这里包含 springmvc相关的相关配置)lns="http://www.springframework.org/schema/beans"xmlns:xsi="http: //www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http:// www.springframework.org/schema/beanshttp://www.springframework.o rg/schema/beans/spring-beans-2.5.xsd"> vlet.mvc.multiaction.ParameterMethodNameResolver">="paramName"value="action"/>value="list"/>lver"class="org.springframework.web.servlet.view.InternalResourc eViewResolver">work.web.servlet.view.JstlView"/>< !--servlet映射列表,所有控制层Controller的servlet在这里定义-->ping"class="org.springframework.web.servlet.handler.SimpleUrlHan dlerMapping">do">userControllerserController"class="com.sxt.action.UserController">me="userService"ref="userService">在WEB -INF下增加service-config.xml(这里包含service层类的相关配置)encoding="UTF-8"?>hema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beansh ttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> rtyname="userDao"ref="userDao">在WEB-I NF下增加hib-config.xml(这里包含spring集成hibernate相关的配置)"encoding="UTF-8"?>schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx=" http://www.springframework.org/schema/tx"xmlns:context="http://ww w.springframework.org/schema/context"xsi:schemaLocation="http://w ww.springframework.org/schema/beanshttp://www.springframework.or g/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org /schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.5. xsdhttp://www.springframework.org/schema/aophttp://www.springfra mework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframewo rk.org/schema/contexthttp://www.springframework.org/schema/conte xt/spring-context-2.5.xsd">com.sxt"/>aSource"class="org.apache.commons.dbcp.BasicDataSource">ertyname="driverClassName"value="com.mysql.jdbc.Driver">operty>myhib">erty>n>ernate3.annotation.AnnotationSessionFactoryBean">="dataSource">name="hibernateProperties">org.hibernate.dialect.MySQLDi alecttruekey="hibernate.hbm2ddl.auto">update< propertyname="packagesToScan">com.sxt.poy>k.orm.hibernate3.HibernateTemplate">ry"ref="sessionFactory">JdbcTemplate"> bean>ork.orm.hibernate3.HibernateTransactionManager">sessionFactory"ref="sessionFactory">tion-driventransaction-manager="txManager"/>ointcutexpression="execution(publiccom.sxt.service.impl..(. .))"id="businessService"/>intcut-ref="businessService"/>vice"transaction-manager="txManager">dname="find"read-only="true"propagation="NOT_SUPPORTED"/>--get开头的方法不需要在事务中运行。有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的--> advice>在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)rsion="1.0"encoding="UTF-8"?>ework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchem a-instance"xsi:schemaLocation="http://www.springframework.org/sc hema/beanshttp://www.springframework.org/schema/beans/spring-bea ns-2.5.xsd">ertyname="hibernateTemplate"ref="hibernateTemplate"> 建立相关类和包结构,如下图所示:各类代码如下:packagecom.sxt.po;import javax.persistence.Entity;importjavax.persistence.GeneratedValue; importjavax.persistence.GenerationType;importjavax.persistence. Id;@EntitypublicclassUser{@Id@GeneratedValue(strategy=Generati onType.AUTO)privateintid;privateStringuname;publicintgetId( ){returnid;}publicvoidsetId(intid){this.id=id;}publicStr inggetUname(){returnuname;}publicvoidsetUname(Stringuname) {this.uname=uname;}}packagecom.sxt.dao;importorg.springframew ork.orm.hibernate3.HibernateTemplate;importcom.sxt.po.User;publi cclassUserDao{privateHibernateTemplatehibernateTemplate;publ icvoidadd(Useru){System.out.println("UserDao.add()");hibernate Template.save(u);}publicHibernateTemplategetHibernateTemplate() {returnhibernateTemplate;}publicvoidsetHibernateTemplate(Hibe rnateTemplatehibernateTemplate){this.hibernateTemplate=hibern ateTemplate;}}packagecom.sxt.service;importcom.sxt.dao.UserDao; importcom.sxt.po.User;publicclassUserService{privateUserDao userDao;publicvoidadd(Stringuname){System.out.println("UserSer vice.add()");Useru=newUser();u.setUname(uname);userDao.add(u) ;}publicUserDaogetUserDao(){returnuserDao;}publicvoidsetUse rDao(UserDaouserDao){this.userDao=userDao;}}packagecom.sxt.a ction;importjavax.servlet.http.HttpServletRequest;importjavax.s ervlet.http.HttpServletResponse;importorg.springframework.web.se rvlet.ModelAndView;importorg.springframework.web.servlet.mvc.Con troller;importcom.sxt.service.UserService;publicclassUserContr ollerimplementsController{privateUserServiceuserService;@Ove rridepublicModelAndViewhandleRequest(HttpServletRequestreq,Htt pServletResponseresp)throwsException{System.out.println("Hell oController.handleRequest()");req.setAttribute("a","aaaa");userS ervice.add(req.getParameter("uname"));returnnewModelAndView("i ndex");}publicUserServicegetUserService(){returnuserService;} publicvoidsetUserService(UserServiceuserService){this.userSer vice=userService;}}运行测试:http://locahost:8080/springmvc01/user.d o?uname=zhangsanhttp://locahost:8080/springmvc01/user.do?uname=zh angsan。结果:数据库中增加zhangsan的记录。页面跳转到index.jsp上,显示:基于spring2.5注解实现的sp ringMVC项目我们采用sprngMVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。实现零配置。下面 我们从零开始重新做一个springMVC的配置。这个项目完全采用注解的方式开发。同时,我们以后的springMVC项目也都会采 用注解的方式。建立web项目导入jar包(spring.jar,spring-webmvc.jar,commons-loggi ng.jar。其他jar包为hibernate相关jar包)修改web.xml,文件内容如下:"encoding="UTF-8"?>.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-i nstance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaeeht tp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">et-name>springmvcorg.springframew ork.web.servlet.DispatcherServlet< param-name>contextConfigLocation/WEB-I NF/hib-config.xml,/WEB-INF/springmvc-servlet.xml init-param>1let-mapping>springmvc .dospringmvc-servlet. xml配置内容如下:tp://www.springframework.org/schema/beans"xmlns:xsi="http://www .w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframew ork.org/schema/p"xmlns:context="http://www.springframework.org/ schema/context"xsi:schemaLocation="http://www.springframework.or g/schema/beanshttp://www.springframework.org/schema/beans/sprin g-beans-2.5.xsdhttp://www.springframework.org/schema/contextht tp://www.springframework.org/schema/context/spring-context-2.5.xs d">nt-scanbase-package="com.sxt"/>tion.AnnotationMethodHandlerAdapter"/>ResourceViewResolver"p:suffix=".jsp"/>hib-config.xml(配置 了spring集成hibernate)mlns="http://www.springframework.org/schema/beans"xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.spri ngframework.org/schema/aop"xmlns:tx="http://www.springframework.o rg/schema/tx"xmlns:context="http://www.springframework.org/schema /context"xsi:schemaLocation="http://www.springframework.org/schem a/beanshttp://www.springframework.org/schema/beans/spring-beans- 2.5.xsdhttp://www.springframework.org/schema/txhttp://www.springf ramework.org/schema/tx/spring-tx-2.5.xsdhttp://www.springframewor k.org/schema/aophttp://www.springframework.org/schema/aop/spring -aop-2.5.xsdhttp://www.springframework.org/schema/contexthttp:/ /www.springframework.org/schema/context/spring-context-2.5.xsd">< context:component-scanbase-package="com.sxt"/>< aop:aspectj-autoproxy/>commons.dbcp.BasicDataSource">value="com.mysql.jdbc.Driver">"value="jdbc:mysql://localhost:3306/myhib">yname="username"value="root">ord"value="123456">"class="org.springframework.orm.hibernate3.annotation.Annotatio nSessionFactoryBean">ataSource"/> lect">org.hibernate.dialect.MySQLDialecthibernate.show_sql">true">updaten">com.sxt.poteTemplate"class="org.springframework.orm.hibernate3.HibernateTe mplate">roperty>class="org.springframework.jdbc.core.JdbcTemplate">me="dataSource"ref="dataSource"/>d="txManager"class="org.springframework.orm.hibernate3.Hibernate TransactionManager">Factory">ger="txManager"/>n(publiccom.sxt.service.impl..(..))"id="businessService"/> />xManager">ue"propagation="NOT_SUPPORTED"/>WEB-INF下建立js p文件夹,并且将index.jsp放入该文件夹下。Index.jsp的内容如下:<%@pagelanguage="java" import="java.util."pageEncoding="gbk"%><%Stringpath=request. getContextPath();StringbasePath=request.getScheme()+"://"+requ est.getServerName()+":"+request.getServerPort()+path+"/";%>YPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">< head>">MyJSP''index.jsp''star tingpagetahttp-equiv="cache-control"content="no-cache">="expires"content="0">ord1,keyword2,keyword3">hisismypage">${params.uname}>${requestScope.u}${requestSco pe.user} | | |