SpringMVC

Spring MVC 背景介绍
  Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架。通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术、Velocity、Tiles、iText 和 POI。Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。

常见MVC框架比较
运行性能上:
Jsp+servlet>struts1>spring mvc>struts2+freemarker>>struts2,ognl,值栈。
开发效率上,基本正好相反。值得强调的是,spring mvc开发效率和struts2不相上下。

  Struts2的性能低的原因是因为OGNL和值栈造成的。所以,如果你的系统并发量高,可以使用freemaker进行显示,而不是采用OGNL和值栈。这样,在性能上会有相当大得提高。

基于spring2.5的采用XML配置的spring MVC项目
  注:本项目全部基于XML配置。同时,集成了hibernate。采用的是:spring MVC+hibernate+spring的开发架构。
建立web项目
导入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar包)

修改web.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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(这里包含spring mvc相关的相关配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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方法调用规则定义 -->
<bean id="paraMethodResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name="paramName" value="action"/>
<property name="defaultMethodName" value="list"/>
</bean>

<!-- 页面View层基本信息设定 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"/>
<!--<property name="prefix" value="/myjsp/"/>-->
<property name="suffix" value=".jsp"/>
</bean>

<!-- servlet映射列表,所有控制层Controller的servlet在这里定义 -->
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="user.do">userController</prop>
</props>
</property>
</bean>

<bean id="userController" class="com.sxt.action.UserController">
<property name="userService" ref="userService"></property>
</bean>
</beans>

在WEB-INF下增加service-config.xml(这里包含service层类的相关配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">

<bean id="userService" class="com.sxt.service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>

</beans>

在WEB-INF下增加hib-config.xml(这里包含spring集成hibernate相关的配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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-scan base-package="com.sxt"/>
<!-- 支持aop注解 -->
<aop:aspectj-autoproxy />


<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<!-- key的名字前面都要加hibernate. -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!--配置一个JdbcTemplate实例-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>


<!-- 配置事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<aop:config>
<aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager" >
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
<!-- get开头的方法不需要在事务中运行 。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:method name="*"/> <!-- 其他方法在实务中运行 -->
</tx:attributes>
</tx:advice>

</beans>

在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">

<bean id="userDao" class="com.sxt.dao.UserDao">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>

在WEB-INF下增加dao-config.xml(这里包含dao层类的相关配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">

<bean id="userDao" class="com.sxt.dao.UserDao">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
</beans>

运行测试:
http://locahost:8080/springmvc01/user.do?uname=zhangsan。

结果:数据库中增加zhangsan的记录。页面跳转到index.jsp上,显示:

基于spring2.5注解实现的spring MVC项目
  我们采用sprng MVC开发项目时,通常都会采用注解的方式,这样可以大大提高我们的开发效率。实现零配置。下面我们从零开始重新做一个spring MVC的配置。这个项目完全采用注解的方式开发。同时,我们以后的spring MVC项目也都会采用注解的方式。

建立web项目
导入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其他jar包为hibernate相关jar包)

修改web.xml,文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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配置内容如下:
<?xml version="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-scan base-package="com.sxt"/>

<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<!--对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:suffix=".jsp"/>
</beans>

hib-config.xml(配置了spring集成hibernate)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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-scan base-package="com.sxt"/>
<!-- 支持aop注解 -->
<aop:aspectj-autoproxy />


<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://localhost:3306/myhib"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>

<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<!-- key的名字前面都要加hibernate. -->
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan">
<value>com.sxt.po</value>
</property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<!--配置一个JdbcTemplate实例-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>


<!-- 配置事务管理 -->
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<aop:config>
<aop:pointcut expression="execution(public * com.sxt.service.impl.*.*(..))" id="businessService"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="businessService" />
</aop:config>
<tx:advice id="txAdvice" transaction-manager="txManager" >
<tx:attributes>
<tx:method name="find*" read-only="true" propagation="NOT_SUPPORTED" />
<!-- get开头的方法不需要在事务中运行 。
有些情况是没有必要使用事务的,比如获取数据。开启事务本身对性能是有一定的影响的-->
<tx:method name="*"/> <!-- 其他方法在实务中运行 -->
</tx:attributes>
</tx:advice>

</beans>

WEB-INF下建立jsp文件夹,并且将index.jsp放入该文件夹下。Index.jsp的内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="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类的代码如下:
package com.sxt.po;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String uname;
private String pwd;


public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}


}
package com.sxt.dao;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.sxt.po.User;

@Repository("userDao")
public class UserDao {
@Resource
private HibernateTemplate hibernateTemplate;

public void add(User u){
System.out.println("UserDao.add()");
hibernateTemplate.save(u);
}

public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}

}
package com.sxt.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sxt.dao.UserDao;
import com.sxt.po.User;

@Service("userService")
public class UserService {
@Resource
private UserDao userDao;

public void add(String uname){
System.out.println("UserService.add()");
User u = new User();
u.setUname(uname);
userDao.add(u);
}

public UserDao getUserDao() {
return userDao;
}

public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}

}
package com.sxt.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.sxt.po.User;
import com.sxt.service.UserService;


@Controller("userController")
@RequestMapping("/user.do")
public class UserController {

@Resource
private UserService userService;

@RequestMapping(params="method=reg")
public String reg(String uname) {
System.out.println("HelloController.handleRequest()");
userService.add(uname);
return "index";
}

public UserService getUserService() {
return userService;
}

public void setUserService(UserService userService) {
this.userService = userService;
}


}

运行测试:
http://pc-201110291327:8080/springmvc02/user.do?method=reg&uname=gaoqi

则会调用userController的reg方法,从而将数据内容插入到数据库中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值