SpringMVC
SpringMVC背景介绍
Spring框架提供了构建Web应用程序的全功能MVC模块。使用Spring可插入的MVC架构,可以选择是使用内置的SpringWeb框架还是Struts这样的Web框架。通过策略接口,Spring框架是高度可配置的,而且包含多种视图技术,例如JavaServerPages(JSP)技术、Velocity、Tiles、iText和POI。SpringMVC框架并不知道使用的视图,所以不会强迫您只使用JSP技术。SpringMVC分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。
常见MVC框架比较
运行性能上:
Jsp+servlet>struts1>springmvc>struts2+freemarker>>struts2,ognl,值栈。
开发效率上,基本正好相反。值得强调的是,springmvc开发效率和struts2不相上下。
Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。
基于spring2.5的采用XML配置的springMVC项目
注:本项目全部基于XML配置。同时,集成了hibernate。采用的是:springMVC+hibernate+spring的开发架构。
建立web项目
导入jar包(spring.jar,spring-webmvc.jar,commons-logging.jar。其他jar包为hibernate相关jar包)
修改web.xml如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/hib-config.xml,/WEB-INF/web-config.xml,/WEB-INF/service-config.xml,/WEB-INF/dao-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
增加web-config.xml(这里包含springmvc相关的相关配置)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!--Controller方法调用规则定义-->
<beanid="paraMethodResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<propertyname="paramName"value="action"/>
<propertyname="defaultMethodName"value="list"/>
</bean>
<!--页面View层基本信息设定-->
<beanid="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<propertyname="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<!--<propertyname="prefix"value="/myjsp/"/>-->
<propertyname="suffix"value=".jsp"/>
</bean>
<!--servlet映射列表,所有控制层Controller的servlet在这里定义-->
<beanid="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<propertyname="mappings">
<props>
<propkey="user.do">userController</prop>
</props>
</property>
</bean>
<beanid="userController"class="com.sxt.action.UserController">
<propertyname="userService"ref="userService"></property>
</bean>
</beans>
在WEB-INF下增加service-config.xml(这里包含service层类的相关配置)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanid="userService"class="com.sxt.service.UserService">
<propertyname="userDao"ref="userDao"></property>
</bean>
</beans>
在WEB-INF下增加hib-config.xml(这里包含spring集成hibernate相关的配置)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/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://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<context:component-scanbase-package="com.sxt"/>
<!--支持aop注解-->
<aop:aspectj-autoproxy/>
<beanid="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<propertyname="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<propertyname="url"value="jdbc:mysql://localhost:3306/myhib"></property>
<propertyname="username"value="root"></property>
<propertyname="password"value="123456"></property>
</bean>
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<propertyname="dataSource">
<refbean="dataSource"/>
</property>
<propertyname="hibernateProperties">
<props>
<!--key的名字前面都要加hibernate.-->
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.show_sql">true</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<propertyname="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>
<beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<!--配置一个JdbcTemplate实例-->
<beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--配置事务管理-->
<beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<tx:annotation-driventransaction-manager="txManager"/>
<aop:config>
<aop:pointcutexpression="execution(public*com.sxt.service.impl.*.*(..))"id="businessService"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="businessService"/>
</aop:config>
<tx:adviceid="txAdvice"transaction-manager="txManager">
<tx:attributes>
<tx:methodname="find*"read-only="true"propagation="NOT_SUPPORTED"/>
<!--get开头的方法不需要在事务中运行。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:methodname="*"/><!--其他方法在实务中运行-->
</tx:attributes>
</tx:advice>
</beans>
在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanid="userDao"class="com.sxt.dao.UserDao">
<propertyname="hibernateTemplate"ref="hibernateTemplate"></property>
</bean>
</beans>
在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<beanid="userDao"class="com.sxt.dao.UserDao">
<propertyname="hibernateTemplate"ref="hibernateTemplate"></property>
</bean>
</beans>
运行测试:
http://locahost:8080/springmvc01/user.do?uname=zhangsan。
结果:数据库中增加zhangsan的记录。页面跳转到index.jsp上,显示:
基于spring2.5注解实现的springMVC项目
我们采用sprngMVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。实现零配置。下面我们从零开始重新做一个springMVC的配置。这个项目完全采用注解的方式开发。同时,我们以后的springMVC项目也都会采用注解的方式。
建立web项目
导入jar包(spring.jar,spring-webmvc.jar,commons-logging.jar。其他jar包为hibernate相关jar包)
修改web.xml,文件内容如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/hib-config.xml,/WEB-INF/springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
springmvc-servlet.xml配置内容如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!--对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能-->
<context:component-scanbase-package="com.sxt"/>
<!--启动SpringMVC的注解功能,完成请求和注解POJO的映射-->
<beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<!--对模型视图名称的解析,即在模型视图名称添加前后缀-->
<beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:suffix=".jsp"/>
</beans>
hib-config.xml(配置了spring集成hibernate)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/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://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<context:component-scanbase-package="com.sxt"/>
<!--支持aop注解-->
<aop:aspectj-autoproxy/>
<beanid="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<propertyname="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<propertyname="url"value="jdbc:mysql://localhost:3306/myhib"></property>
<propertyname="username"value="root"></property>
<propertyname="password"value="123456"></property>
</bean>
<beanid="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<propertyname="dataSource">
<refbean="dataSource"/>
</property>
<propertyname="hibernateProperties">
<props>
<!--key的名字前面都要加hibernate.-->
<propkey="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<propkey="hibernate.show_sql">true</prop>
<propkey="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<propertyname="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>
<beanid="hibernateTemplate"class="org.springframework.orm.hibernate3.HibernateTemplate">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<!--配置一个JdbcTemplate实例-->
<beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--配置事务管理-->
<beanid="txManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<propertyname="sessionFactory"ref="sessionFactory"></property>
</bean>
<tx:annotation-driventransaction-manager="txManager"/>
<aop:config>
<aop:pointcutexpression="execution(public*com.sxt.service.impl.*.*(..))"id="businessService"/>
<aop:advisoradvice-ref="txAdvice"pointcut-ref="businessService"/>
</aop:config>
<tx:adviceid="txAdvice"transaction-manager="txManager">
<tx:attributes>
<tx:methodname="find*"read-only="true"propagation="NOT_SUPPORTED"/>
<!--get开头的方法不需要在事务中运行。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:methodname="*"/><!--其他方法在实务中运行-->
</tx:attributes>
</tx:advice>
</beans>
WEB-INF下建立jsp文件夹,并且将index.jsp放入该文件夹下。Index.jsp的内容如下:
<%@pagelanguage="java"import="java.util.*"pageEncoding="gbk"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>MyJSP'index.jsp'startingpage</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="Thisismypage">
<!--
<linkrel="stylesheet"type="text/css"href="styles.css">
-->
</head>
<body>
<h1>**********${params.uname}</h1>
<h1>**********${requestScope.u}</h1>
<h1>**********${requestScope.user}</h1>
</body>
</html>
User、UserDao、UserService、UserController类的代码如下:
packagecom.sxt.po;
importjavax.persistence.Entity;
importjavax.persistence.GeneratedValue;
importjavax.persistence.GenerationType;
importjavax.persistence.Id;
@Entity
publicclassUser{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
privateintid;
privateStringuname;
privateStringpwd;
publicStringgetPwd(){
returnpwd;
}
publicvoidsetPwd(Stringpwd){
this.pwd=pwd;
}
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetUname(){
returnuname;
}
publicvoidsetUname(Stringuname){
this.uname=uname;
}
}
packagecom.sxt.dao;
importjavax.annotation.Resource;
importorg.springframework.orm.hibernate3.HibernateTemplate;
importorg.springframework.stereotype.Repository;
importcom.sxt.po.User;
@Repository("userDao")
publicclassUserDao{
@Resource
privateHibernateTemplatehibernateTemplate;
publicvoidadd(Useru){
System.out.println("UserDao.add()");
hibernateTemplate.save(u);
}
publicHibernateTemplategetHibernateTemplate(){
returnhibernateTemplate;
}
publicvoidsetHibernateTemplate(HibernateTemplatehibernateTemplate){
this.hibernateTemplate=hibernateTemplate;
}
}
packagecom.sxt.service;
importjavax.annotation.Resource;
importorg.springframework.stereotype.Service;
importcom.sxt.dao.UserDao;
importcom.sxt.po.User;
@Service("userService")
publicclassUserService{
@Resource
privateUserDaouserDao;
publicvoidadd(Stringuname){
System.out.println("UserService.add()");
Useru=newUser();
u.setUname(uname);
userDao.add(u);
}
publicUserDaogetUserDao(){
returnuserDao;
}
publicvoidsetUserDao(UserDaouserDao){
this.userDao=userDao;
}
}
packagecom.sxt.web;
importjavax.annotation.Resource;
importorg.springframework.stereotype.Controller;
importorg.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.SessionAttributes;
importcom.sxt.po.User;
importcom.sxt.service.UserService;
@Controller("userController")
@RequestMapping("/user.do")
publicclassUserController{
@Resource
privateUserServiceuserService;
@RequestMapping(params="method=reg")
publicStringreg(Stringuname){
System.out.println("HelloController.handleRequest()");
userService.add(uname);
return"index";
}
publicUserServicegetUserService(){
returnuserService;
}
publicvoidsetUserService(UserServiceuserService){
this.userService=userService;
}
}
运行测试:
http://pc-201110291327:8080/springmvc02/user.do?method=reg&uname=gaoqi
则会调用userController的reg方法,从而将数据内容插入到数据库中。