Spring MVC

Spring  MVC 背景介紹

Spring 框架提供了構建 Web 應用程序的全功能 MVC 模塊。使用 Spring 可插入的 MVC 架構,能夠選擇是使用內置的 Spring Web 框架仍是 Struts 這樣的 Web 框架。經過策略接口,Spring 框架是高度可配置的,並且包含多種視圖技術,例如 JavaServer PagesJSP)技術、VelocityTilesiText  POISpring MVC 框架並不知道使用的視圖,因此不會強迫您只使用 JSP 技術。Spring MVC 分離了控制器、模型對象、分派器以及處理程序對象的角色,這種分離讓它們更容易進行定製。javascript

 

 

常見MVC框架比較

運行性能上:css

Jsp+servlet>struts1>spring mvc>struts2+freemarker>>struts2,ognl,值棧。html

開發效率上,基本正好相反。值得強調的是,spring mvc開發效率和struts2不相上下。java

 

Struts2的性能低的緣由是由於OGNL和值棧形成的。因此,若是你的系統併發量高,可使用freemaker進行顯示,而不是採用OGNL和值棧。這樣,在性能上會有至關大得提升。mysql

 

 

基於spring2.5的採用XML配置的spring MVC項目

注:本項目所有基於XML配置。同時,集成了hibernate。採用的是:spring MVC+hibernate+spring的開發架構。 web

  1. 創建web項目
  2. 導入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其餘jar包爲hibernate相關jar包)

 

  1. 修改web.xml以下:

<?xml version="1.0" encoding="UTF-8"?>ajax

<web-app version="2.5spring

xmlns="http://java.sun.com/xml/ns/javaee" sql

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>

<filter>

<filter-name>charsetEncode</filter-name>

<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>UTF-8</param-value>

</init-param>

</filter>

 

<filter-mapping>

<filter-name>charsetEncode</filter-name>

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

</filter-mapping>

</web-app>

 

 

 

  1. 增長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="userInfo.do">userInfoController</prop>

            </props>

        </property>

    </bean>

 

<bean id="userInfoController" class="com.zb.action.UserInfoController">

<property name="userInfoService" ref="userInfoService"></property>

      <property name="methodNameResolver" >

<ref local="paraMethodResolver"/>

</property>

</bean>

</beans>

 

  1. 在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="userInfoService" class="com.zb.service.UserInfoService">

<property name="userInfoDao" ref="userInfoDao"></property>

</bean>

 

</beans>

 

  1. 在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.zb"/>   

<!-- 支持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="userInfoname" 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.zb.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.zb.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>

 

  1. 在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="userInfoDao" class="com.zb.dao.UserInfoDao">

  <property name="hibernateTemplate" ref="hibernateTemplate"></property>

</bean>

</beans>

 

  1. 創建相關類和包結構,以下圖所示:

 

  1. 各種代碼以下: 

package com.zb.entity;

 

/**

 * Userinfo entity. @author MyEclipse Persistence Tools

 */

 

public class Userinfo implements java.io.Serializable {

 

// Fields

 

private Integer id;

private String name;

private Integer age;

private String address;

 

// Constructors

 

/** default constructor */

public Userinfo() {

}

 

/** full constructor */

public Userinfo(String name, Integer age, String address) {

this.name = name;

this.age = age;

this.address = address;

}

 

// Property accessors

 

public Integer getId() {

return this.id;

}

 

public void setId(Integer id) {

this.id = id;

}

 

public String getName() {

return this.name;

}

 

public void setName(String name) {

this.name = name;

}

 

public Integer getAge() {

return this.age;

}

 

public void setAge(Integer age) {

this.age = age;

}

 

public String getAddress() {

return this.address;

}

 

public void setAddress(String address) {

this.address = address;

}

 

}}

package com.zb.dao;

 

import org.springframework.orm.hibernate3.HibernateTemplate;

 

import com.zb.po.UserInfo;

 

public class UserInfoDao {

private HibernateTemplate hibernateTemplate;

 

public void add(UserInfo u){

System.out.println("UserInfoDao.add()");

hibernateTemplate.save(u);

}

 

public HibernateTemplate getHibernateTemplate() {

return hibernateTemplate;

}

 

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

 

}

package com.zb.service;

 

import com.zb.dao.UserInfoDao;

import com.zb.po.UserInfo;

 

public class UserInfoService {

 

private UserInfoDao userInfoDao;

 

public void add(String uname){

System.out.println("UserInfoService.add()");

UserInfo u = new UserInfo();

u.setUname(uname);

userInfoDao.add(u);

}

 

public UserInfoDao getUserInfoDao() {

return userInfoDao;

}

 

public void setUserInfoDao(UserInfoDao userInfoDao) {

this.userInfoDao = userInfoDao;

}

 

}

package com.zb.action;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.Controller;

 

import com.zb.service.UserInfoService;

 

public class UserInfoController implements Controller {

 

private UserInfoService userInfoService;

 

@Override

public ModelAndView handleRequest(HttpServletRequest req,

HttpServletResponse resp) throws Exception {

System.out.println("HelloController.handleRequest()");

req.setAttribute("a", "aaaa");

userInfoService.add(req.getParameter("uname"));

return new ModelAndView("index");

}

 

public UserInfoService getUserInfoService() {

return userInfoService;

}

 

public void setUserInfoService(UserInfoService userInfoService) {

this.userInfoService = userInfoService;

}

 

 

}

 

  1. 運行測試:

 

基於spring2.5註解實現的spring MVC項目

咱們採用sprng MVC開發項目時,一般都會採用註解的方式,這樣能夠大大提升咱們的開發效率。實現零配置。下面咱們從零開始從新作一個spring MVC的配置。這個項目徹底採用註解的方式開發。同時,咱們之後的spring MVC項目也都會採用註解的方式。

 

  1. 創建web項目
  2. 導入jar包(spring.jar, spring-webmvc.jar, commons-logging.jar。其餘jar包爲hibernate相關jar包)

 

 

 

  1. 修改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>

 

 

  1. 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.zb"/>

 

    <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

 

    <!--對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 

        p:suffix=".jsp"/>

</beans>

 

  1. 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.zb"/>   

<!-- 支持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="userInfoname" 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.zb.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.zb.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>

 

  1. 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.userInfo}</h1>

  </body>

</html>

 

 

  1. 創建整個項目的包結構和相關類。以下圖所示:

 

  1. UserInfo、UserInfoDao、UserInfoService、UserInfoController類的代碼以下:

}

package com.zb.dao;

 

import javax.annotation.Resource;

 

import org.springframework.orm.hibernate3.HibernateTemplate;

import org.springframework.stereotype.Repository;

 

import com.zb.po.UserInfo;

 

@Repository("userInfoDao")

public class UserInfoDao {

@Resource

private HibernateTemplate hibernateTemplate;

 

public void add(UserInfo u){

System.out.println("UserInfoDao.add()");

hibernateTemplate.save(u);

}

 

public HibernateTemplate getHibernateTemplate() {

return hibernateTemplate;

}

 

public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {

this.hibernateTemplate = hibernateTemplate;

}

 

}

package com.zb.service;

 

import javax.annotation.Resource;

 

import org.springframework.stereotype.Service;

 

import com.zb.dao.UserInfoDao;

import com.zb.po.UserInfo;

 

@Service("userInfoService")

public class UserInfoService {

@Resource

private UserInfoDao userInfoDao;

 

public void add(String uname){

System.out.println("UserInfoService.add()");

UserInfo u = new UserInfo();

u.setUname(uname);

userInfoDao.add(u);

}

 

public UserInfoDao getUserInfoDao() {

return userInfoDao;

}

 

public void setUserInfoDao(UserInfoDao userInfoDao) {

this.userInfoDao = userInfoDao;

}

 

}

package com.zb.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.zb.po.UserInfo;

import com.zb.service.UserInfoService;

 

 

@Controller("userInfoController")

@RequestMapping("/userInfo.do")     

public class UserInfoController  {

 

@Resource

private UserInfoService userInfoService;

 

@RequestMapping(params="method=reg")

public String reg(String uname) {

System.out.println("HelloController.handleRequest()");

userInfoService.add(uname);

return "index";

}

 

public UserInfoService getUserInfoService() {

return userInfoService;

}

 

public void setUserInfoService(UserInfoService userInfoService) {

this.userInfoService = userInfoService;

}

 

 

}

 

  1. 運行測試:

http://pc-201110291327:8080/springmvc02/userInfo.do?method=reg&uname=gaoqi

 

則會調用userInfoController的reg方法,從而將數據內容插入到數據庫中。

 

 

 

 

 

 

 

基於spring 3.0項目開發實例

spring3.0徹底兼容spring2.5.所以,咱們只要簡單修改上面項目的類庫和配置文件。類的代碼保持不變。

 

  1. 導入相關jar包,以下:

 

  1. spring配置文件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:mvc="http://www.springframework.org/schema/mvc"    

    xmlns:context="http://www.springframework.org/schema/context"    

    xmlns:util="http://www.springframework.org/schema/util"    

    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    

            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd    

            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd    

            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"

     

    <!-- 對web包中的全部類進行掃描,以完成Bean建立和自動依賴注入的功能 -->

    <context:component-scan base-package="com.zb.web"/>

 

 

<mvc:annotation-driven />  <!-- 支持spring3.0新的mvc註解 -->

 

    <!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->

    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

 

    <!--對模型視圖名稱的解析,即在模型視圖名稱添加先後綴 -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 

        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">

         <!-- 若是使用jstl的話,配置下面的屬性 -->

     <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />    

    </bean>

</beans>

 

  1. spring配置文件hib-config.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: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-3.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-3.0.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

  http://www.springframework.org/schema/context   

   http://www.springframework.org/schema/context/spring-context-3.0.xsd

">

<context:component-scan  base-package="com.zb"/>   

<!-- 支持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="userInfoname" 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.zb.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.zb.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>

 

  1. web.xml文件不變
  2. 類的代碼不變。
  3. 運行,測試。跟上一個項目保持一致。

 

 

Spring MVC 3.0 深刻

核心原理

  1. 用戶發送請求給服務器。url:userInfo.do
  2. 服務器收到請求。發現DispatchServlet能夠處理。因而調用DispatchServlet。
  3. DispatchServlet內部,經過HandleMapping檢查這個url有沒有對應的Controller。若是有,則調用Controller。
  4. Controller開始執行。
  5. Controller執行完畢後,若是返回字符串,則ViewResolver將字符串轉化成相應的視圖對象;若是返回ModelAndView對象,該對象自己就包含了視圖對象信息。
  6. DispatchServlet將執視圖對象中的數據,輸出給服務器。
  7. 服務器將數據輸出給客戶端。

spring3.0中相關jar包的含義

org.springframework.aop-3.0.3.RELEASE.jar

springaop面向切面編程

org.springframework.asm-3.0.3.RELEASE.jar

spring獨立的asm字節碼生成程序

org.springframework.beans-3.0.3.RELEASE.jar

IOC的基礎實現

org.springframework.context-3.0.3.RELEASE.jar

IOC基礎上的擴展服務

org.springframework.core-3.0.3.RELEASE.jar

spring的核心包

org.springframework.expression-3.0.3.RELEASE.jar

spring的表達式語言

org.springframework.web-3.0.3.RELEASE.jar

web工具包

org.springframework.web.servlet-3.0.3.RELEASE.jar

mvc工具包

 

 

@Controller控制器定義

和Struts1同樣,Spring的Controller是Singleton的。這就意味着會被多個請求線程共享。所以,咱們將控制器設計成無狀態類。

 

spring 3.0中,經過@controller標註便可將class定義爲一個controller類。爲使spring能找到定義爲controllerbean,須要在spring-context配置文件中增長以下定義:

 

<context:component-scan base-package="com.zb.web"/>

 

注:實際上,使用@component,也能夠起到@Controller一樣的做用。

 

@RequestMapping

 

在類前面定義,則將url和類綁定。

在方法前面定義,則將url和類的方法綁定,以下所示:

package com.zb.web;

 

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import com.zb.service.UserInfoService;

 

@Controller

@RequestMapping("/userInfo.do")

public class UserInfoController  {

 

@Resource

private UserInfoService userInfoService;

 

//http://localhost:8080/springmvc02/userInfo.do?method=reg&uname=zzzz

@RequestMapping(params="method=reg")

public String reg(String uname) {

System.out.println("HelloController.handleRequest()");

userInfoService.add(uname);

return "index";

}

 

public UserInfoService getUserInfoService() {

return userInfoService;

}

public void setUserInfoService(UserInfoService userInfoService) {

this.userInfoService = userInfoService;

}

 

 

}

 

@RequestParam

通常用於將指定的請求參數付給方法中形參。示例代碼以下:

 

@RequestMapping(params="method=reg5")

public String reg5(@RequestParam("name")String uname,ModelMap map) {

System.out.println("HelloController.handleRequest()");

System.out.println(uname);

return "index";

}

 

這樣,就會將name參數的值付給uname。固然,若是請求參數名稱和形參名稱保持一致,則不須要這種寫法。

@SessionAttributes

ModelMap中指定的屬性放到session中。示例代碼以下:

 

@Controller

@RequestMapping("/userInfo.do")

@SessionAttributes({"u","a"})   //ModelMap中屬性名字爲ua的再放入session中。這樣,requestsession中都有了。

public class UserInfoController  {

@RequestMapping(params="method=reg4")

public String reg4(ModelMap map) {   System.out.println("HelloController.handleRequest()");

map.addAttribute("u","uuuu");  //u放入request做用域中,這樣轉發頁面也能夠取到這個數據。

return "index";

}

}

  <body>

   <h1>**********${requestScope.u.uname}</h1>

   <h1>**********${sessionScope.u.uname}</h1>

  </body>

 

注:名字爲」userInfo」的屬性再結合使用註解@SessionAttributes可能會報錯。

 

@ModelAttribute

這個註解能夠跟@SessionAttributes配合在一塊兒用。能夠將ModelMap中屬性的值經過該註解自動賦給指定變量。

示例代碼以下:

package com.zb.web;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

@Controller

@RequestMapping("/userInfo.do")

@SessionAttributes({"u","a"})  

public class UserInfoController  {

 

@RequestMapping(params="method=reg4")

public String reg4(ModelMap map) {

System.out.println("HelloController.handleRequest()");

map.addAttribute("u","高淇");

return "index";

}

 

@RequestMapping(params="method=reg5")

public String reg5(@ModelAttribute("u")String uname,ModelMap map) {

System.out.println("HelloController.handleRequest()");

System.out.println(uname);

return "index";

}

 

}

 

先調用reg4方法,再調用reg5方法。咱們發現控制檯打印出來:

 

Controller類中方法參數的處理

 

Controller類中方法返回值的處理

  1. 返回string(建議)

a) 根據返回值找對應的顯示頁面。路徑規則爲:prefix前綴+返回值+suffix後綴組成

b) 代碼以下:

@RequestMapping(params="method=reg4")

public String reg4(ModelMap map) {

System.out.println("HelloController.handleRequest()");

return "index";

}

前綴爲:/WEB-INF/jsp/    後綴是:.jsp

在轉發到:/WEB-INF/jsp/index.jsp

 

  1. 也能夠返回ModelMap、ModelAndView、map、List、Set、Object、無返回值。 通常建議返回字符串!

 

 

請求轉發和重定向

代碼示例:

 

package com.zb.web;

 

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

 

@Controller

@RequestMapping("/userInfo.do")

public class UserInfoController  {

 

@RequestMapping(params="method=reg4")

public String reg4(ModelMap map) {

System.out.println("HelloController.handleRequest()");

// return "forward:index.jsp";

// return "forward:userInfo.do?method=reg5"; //轉發

// return "redirect:userInfo.do?method=reg5";  //重定向

return "redirect:http://www.baidu.com";  //重定向

}

 

@RequestMapping(params="method=reg5")

public String reg5(String uname,ModelMap map) {

System.out.println("HelloController.handleRequest()");

System.out.println(uname);

return "index";

}

 

}

 

訪問reg4方法,既能夠看到效果。

 

 

 

得到request對象、session對象

普通的Controller類,示例代碼以下:

@Controller

@RequestMapping("/userInfo.do")

public class UserInfoController  {

 

@RequestMapping(params="method=reg2")

public String reg2(String uname,HttpServletRequest req,ModelMap map){

req.setAttribute("a", "aa");

req.getSession().setAttribute("b", "bb");

return "index";

}

}

 

 

ModelMap

是map的實現,能夠在其中存放屬性,做用域同request。下面這個示例,咱們能夠在modelMap中放入數據,而後在forward的頁面上顯示這些數據。經過el表達式、JSTL、java代碼都可。代碼以下:

 

package com.zb.web;

 

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

 

@Controller

@RequestMapping("/userInfo.do")

public class UserInfoController extends MultiActionController  {

 

@RequestMapping(params="method=reg")

public String reg(String uname,ModelMap map){

map.put("a", "aaa");

return "index";

}

}

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head></head>

  <body>

   <h1>${requestScope.a}</h1>

   <c:out value="${requestScope.a}"></c:out>

  </body>

</html>

 

ModelAndView模型視圖類

見名知意,從名字上咱們能夠知道ModelAndView中的Model表明模型,View表明視圖。即,這個類把要顯示的數據存儲到了Model屬性中,要跳轉的視圖信息存儲到了view屬性。咱們看一下ModelAndView的部分源碼,便可知其中關係:

public class ModelAndView {

 

/** View instance or view name String */

private Object view;

 

/** Model Map */

private ModelMap model;

 

/**

 * Indicates whether or not this instance has been cleared with a call to {@link #clear()}.

 */

private boolean cleared = false;

 

 

/**

 * Default constructor for bean-style usage: populating bean

 * properties instead of passing in constructor arguments.

 * @see #setView(View)

 * @see #setViewName(String)

 */

public ModelAndView() {

}

 

/**

 * Convenient constructor when there is no model data to expose.

 * Can also be used in conjunction with <code>addObject</code>.

 * @param viewName name of the View to render, to be resolved

 * by the DispatcherServlet's ViewResolver

 * @see #addObject

 */

public ModelAndView(String viewName) {

this.view = viewName;

}

 

/**

 * Convenient constructor when there is no model data to expose.

 * Can also be used in conjunction with <code>addObject</code>.

 * @param view View object to render

 * @see #addObject

 */

public ModelAndView(View view) {

this.view = view;

}

 

/**

 * Creates new ModelAndView given a view name and a model.

 * @param viewName name of the View to render, to be resolved

 * by the DispatcherServlet's ViewResolver

 * @param model Map of model names (Strings) to model objects

 * (Objects). Model entries may not be <code>null</code>, but the

 * model Map may be <code>null</code> if there is no model data.

 */

public ModelAndView(String viewName, Map<String, ?> model) {

this.view = viewName;

if (model != null) {

getModelMap().addAllAttributes(model);

}

}

 

/**

 * Creates new ModelAndView given a View object and a model.

 * <emphasis>Note: the supplied model data is copied into the internal

 * storage of this class. You should not consider to modify the supplied

 * Map after supplying it to this class</emphasis>

 * @param view View object to render

 * @param model Map of model names (Strings) to model objects

 * (Objects). Model entries may not be <code>null</code>, but the

 * model Map may be <code>null</code> if there is no model data.

 */

public ModelAndView(View view, Map<String, ?> model) {

this.view = view;

if (model != null) {

getModelMap().addAllAttributes(model);

}

}

 

/**

 * Convenient constructor to take a single model object.

 * @param viewName name of the View to render, to be resolved

 * by the DispatcherServlet's ViewResolver

 * @param modelName name of the single entry in the model

 * @param modelObject the single model object

 */

public ModelAndView(String viewName, String modelName, Object modelObject) {

this.view = viewName;

addObject(modelName, modelObject);

}

 

/**

 * Convenient constructor to take a single model object.

 * @param view View object to render

 * @param modelName name of the single entry in the model

 * @param modelObject the single model object

 */

public ModelAndView(View view, String modelName, Object modelObject) {

this.view = view;

addObject(modelName, modelObject);

}

 

 

/**

 * Set a view name for this ModelAndView, to be resolved by the

 * DispatcherServlet via a ViewResolver. Will override any

 * pre-existing view name or View.

 */

public void setViewName(String viewName) {

this.view = viewName;

}

 

/**

 * Return the view name to be resolved by the DispatcherServlet

 * via a ViewResolver, or <code>null</code> if we are using a View object.

 */

public String getViewName() {

return (this.view instanceof String ? (String) this.view : null);

}

 

/**

 * Set a View object for this ModelAndView. Will override any

 * pre-existing view name or View.

 */

public void setView(View view) {

this.view = view;

}

 

/**

 * Return the View object, or <code>null</code> if we are using a view name

 * to be resolved by the DispatcherServlet via a ViewResolver.

 */

public View getView() {

return (this.view instanceof View ? (View) this.view : null);

}

 

/**

 * Indicate whether or not this <code>ModelAndView</code> has a view, either

 * as a view name or as a direct {@link View} instance.

 */

public boolean hasView() {

return (this.view != null);

}

 

/**

 * Return whether we use a view reference, i.e. <code>true</code>

 * if the view has been specified via a name to be resolved by the

 * DispatcherServlet via a ViewResolver.

 */

public boolean isReference() {

return (this.view instanceof String);

}

 

/**

 * Return the model map. May return <code>null</code>.

 * Called by DispatcherServlet for evaluation of the model.

 */

protected Map<String, Object> getModelInternal() {

return this.model;

}

 

/**

 * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).

 */

public ModelMap getModelMap() {

if (this.model == null) {

this.model = new ModelMap();

}

return this.model;

}

 

/**

 * Return the model map. Never returns <code>null</code>.

 * To be called by application code for modifying the model.

 */

public Map<String, Object> getModel() {

return getModelMap();

}

 

 

/**

 * Add an attribute to the model.

 * @param attributeName name of the object to add to the model

 * @param attributeValue object to add to the model (never <code>null</code>)

 * @see ModelMap#addAttribute(String, Object)

 * @see #getModelMap()

 */

public ModelAndView addObject(String attributeName, Object attributeValue) {

getModelMap().addAttribute(attributeName, attributeValue);

return this;

}

 

/**

 * Add an attribute to the model using parameter name generation.

 * @param attributeValue the object to add to the model (never <code>null</code>)

 * @see ModelMap#addAttribute(Object)

 * @see #getModelMap()

 */

public ModelAndView addObject(Object attributeValue) {

getModelMap().addAttribute(attributeValue);

return this;

}

 

/**

 * Add all attributes contained in the provided Map to the model.

 * @param modelMap a Map of attributeName -> attributeValue pairs

 * @see ModelMap#addAllAttributes(Map)

 * @see #getModelMap()

 */

public ModelAndView addAllObjects(Map<String, ?> modelMap) {

getModelMap().addAllAttributes(modelMap);

return this;

}

 

 

/**

 * Clear the state of this ModelAndView object.

 * The object will be empty afterwards.

 * <p>Can be used to suppress rendering of a given ModelAndView object

 * in the <code>postHandle</code> method of a HandlerInterceptor.

 * @see #isEmpty()

 * @see HandlerInterceptor#postHandle

 */

public void clear() {

this.view = null;

this.model = null;

this.cleared = true;

}

 

/**

 * Return whether this ModelAndView object is empty,

 * i.e. whether it does not hold any view and does not contain a model.

 */

public boolean isEmpty() {

return (this.view == null && CollectionUtils.isEmpty(this.model));

}

 

/**

 * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}

 * i.e. whether it does not hold any view and does not contain a model.

 * <p>Returns <code>false</code> if any additional state was added to the instance

 * <strong>after</strong> the call to {@link #clear}.

 * @see #clear()

 */

public boolean wasCleared() {

return (this.cleared && isEmpty());

}

 

 

/**

 * Return diagnostic information about this model and view.

 */

@Override

public String toString() {

StringBuilder sb = new StringBuilder("ModelAndView: ");

if (isReference()) {

sb.append("reference to view with name '").append(this.view).append("'");

}

else {

sb.append("materialized View is [").append(this.view).append(']');

}

sb.append("; model is ").append(this.model);

return sb.toString();

}

}

 

測試代碼以下:

package com.zb.web;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

 

import com.zb.po.UserInfo;

 

@Controller

@RequestMapping("/userInfo.do")

public class UserInfoController extends MultiActionController  {

 

@RequestMapping(params="method=reg")

public ModelAndView reg(String uname){

ModelAndView mv = new ModelAndView();

mv.setViewName("index");

// mv.setView(new RedirectView("index"));

 

UserInfo u = new UserInfo();

u.setUname("老章");

mv.addObject(u);   //查看源代碼,得知,直接放入對象。屬性名爲」首字母小寫的類名」。 通常建議手動增長屬性名稱。

mv.addObject("a", "aaaa");

return mv;

}

 

}

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

   <h1>${requestScope.a}</h1>

   <h1>${requestScope.userInfo.uname}</h1>

  </body>

</html>

 

 

 

基於spring 3.0mvc 框架的文件上傳實現

1. spring使用了apache-commons下得上傳組件,所以,咱們須要引入兩個jar包:

  1. apache-commons-fileupload.jar
  2. apache-commons-io.jar

 

2.  在springmvc-servlet.xml配置文件中,增長CommonsMultipartResoler配置:

<!-- 處理文件上傳 -->

<bean id="multipartResolver"  

    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  

    <property name="defaultEncoding" value="gbk"/> <!-- 默認編碼 (ISO-8859-1) -->  

    <property name="maxInMemorySize" value="10240"/> <!-- 最大內存大小 (10240)-->  

    <property name="uploadTempDir" value="/upload/"/> <!-- 上傳後的目錄名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->  

    <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1爲無限止(-1) -->  

</bean>

 

3.  創建upload.jsp頁面,內容以下:

 

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>測試springmvc中上傳的實現</title>

</head>

<body>

<form action="upload.do"  method="post" enctype="multipart/form-data">

<input type="text" name="name" />

<input type="file" name="file" />

<input type="submit" />

</form>

</body>

</html>

 

4. 創建控制器,代碼以下:

 

package com.zb.web;

 

import java.io.File;

import java.util.Date;

 

import javax.servlet.ServletContext;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.context.ServletContextAware;

import org.springframework.web.multipart.commons.CommonsMultipartFile;

 

@Controller

public class FileUploadController implements ServletContextAware {

 

private ServletContext servletContext;

 

@Override

public void setServletContext(ServletContext context) {

this.servletContext  = context;

}

 

@RequestMapping(value="/upload.do", method = RequestMethod.POST)

public String handleUploadData(String name,@RequestParam("file")CommonsMultipartFile file){

if (!file.isEmpty()) {

   String path = this.servletContext.getRealPath("/tmp/");  //獲取本地存儲路徑

   System.out.println(path);

   String fileName = file.getOriginalFilename();

   String fileType = fileName.substring(fileName.lastIndexOf("."));

   System.out.println(fileType);

   File file2 = new File(path,new Date().getTime() + fileType); //新建一個文件

   try {

    file.getFileItem().write(file2); //將上傳的文件寫入新建的文件中

   } catch (Exception e) {

    e.printStackTrace();

   }

   return "redirect:upload_ok.jsp";

}else{

return "redirect:upload_error.jsp";

}

}

}

 

5. 創建upload_ok.jsp頁面

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

   <h1>上傳成功!</h1>

  </body>

</html>

 

6. 創建upload_error.jsp頁面

  <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

  </head>

  <body>

   <h1>上傳失敗!</h1>

  </body>

</html>

 

  1. 發佈項目,運行測試:http://localhost:8080/springmvc03/upload.jsp

 

   進入項目發佈後的目錄,發現文件上傳成功:

 

 

處理ajax請求

spring使用了jackson類庫,幫助咱們在java對象和json、xml數據之間的互相轉換。他能夠將控制器返回的對象直接轉換成json數據,供客戶端使用。客戶端也能夠傳送json數據到服務器進行直接轉換。使用步驟以下:

 

1.  項目中須要引入以下兩個jar包:

jackson-core-asl-1.7.2jar

jackson-mapper-asl-1.7.2jar

2.  spring配置文件中修改:

<mvc:annotation-driven />  <!-- 支持spring3.0新的mvc註解 -->

<!-- 啓動Spring MVC的註解功能,完成請求和註解POJO的映射 -->

  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  

        <property name="cacheSeconds" value="0" />  

        <property name="messageConverters">  

            <list>  

                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>  

            </list>  

        </property>

    </bean>  

 

  1. 客戶端代碼a.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">

<script>

function createAjaxObj(){

var req;

if(window.XMLHttpRequest){

req = new XMLHttpRequest();

}else{

req = new ActiveXObject("Msxml2.XMLHTTP");  //ie

}

return req;

}

 

function sendAjaxReq(){

var req = createAjaxObj();

req.open("get","myajax.do?method=test2&uname=張三");

req.setRequestHeader("accept","application/json");

req.onreadystatechange  = function(){

eval("var result="+req.responseText);

document.getElementById("div1").innerHTML=result[0].uname;

}

req.send(null);

}

</script>

  </head>

  

  <body>

    <a href="javascript:void(0);" onclick="sendAjaxReq();">測試</a>

    <div id="div1"></div>

  </body>

</html>

 

 

  1. 服務器端代碼以下:

 

package com.zb.web;

 

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.List;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.zb.po.UserInfo;

 

@Controller

@RequestMapping("myajax.do")

public class MyAjaxController {

 

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

public @ResponseBody List<UserInfo> test1(String uname) throws Exception{

String uname2 = new String(uname.getBytes("iso8859-1"),"gbk");

System.out.println(uname2);

System.out.println("MyAjaxController.test1()");

List<UserInfo> list = new ArrayList<UserInfo>();

list.add(new UserInfo("a","123"));

list.add(new UserInfo("b","456"));

 

return list;

}

 

}

 

 

  1. 測試。

a) 啓動服務器。輸入:http://localhost:8080/springmvc03/a.jsp

 

 

 

 

 

 

 

Spring中的攔截器

定義spring攔截器兩種基本方式

  1. 實現接口:org.springframework.web.servlet.HandlerInterceptor。

接口中有以下方法須要重寫:

注意:參數中的Object handler是下一個攔截器。

a) public boolean preHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler) throws Exception

該方法在action執行前執行,能夠實現對數據的預處理,好比:編碼、安全控制等。

若是方法返回true,則繼續執行action。

b) public void postHandle
(HttpServletRequest request,HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception

該方法在action執行後,生成視圖前執行。在這裏,咱們有機會修改視圖層數據。

c) public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception

最後執行,一般用於釋放資源,處理異常。咱們能夠根據ex是否爲空,來進行相關的異常處理。由於咱們在平時處理異常時,都是從底層向上拋出異常,最後到了spring框架從而到了這個方法中。

  1. 繼承適配器:
    org.springframework.web.servlet.handler.HandlerInterceptorAdapter

這個適配器實現了HandlerInterceptor接口。提供了這個接口中全部方法的空實現。

 

以下咱們寫出兩個攔截器的示例代碼,僅供你們參考:

package com.zb.interceptor;

 

import javax.interceptor.Interceptors;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

 

public class MyInterceptor implements HandlerInterceptor {

 

@Override

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

System.out.println("最後執行!!!通常用於釋放資源!!");

 

}

 

@Override

public void postHandle(HttpServletRequest request,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

System.out.println("Action執行以後,生成視圖以前執行!!");

}

 

@Override

public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {

System.out.println("action以前執行!!!");

return true;  //繼續執行action

}

 

}

 

package com.zb.interceptor;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

 

 

public class MyInterceptor2 extends HandlerInterceptorAdapter {

 

@Override

public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {

System.out.println("MyInterceptor2.preHandle()");

return true;  //繼續執行action

}

 

}

 

 

 

  1. XML中如何配置。以下爲示例代碼:

<mvc:interceptors>

<bean class="com.zb.interceptor.MyInterceptor"></bean> <!-- 攔截全部springmvcurl! -->

<mvc:interceptor>

<mvc:mapping path="/userInfo.do" />

<!--<mvc:mapping path="/test/*" />-->

<bean class="com.zb.interceptor.MyInterceptor2"></bean>

</mvc:interceptor>

</mvc:interceptors>

相關文章
相關標籤/搜索