spring mvc 快速入門

weixin_30639719發表於2020-04-05

---------- 轉自尚學堂 高淇 ---------

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的開發架構。

  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>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>

 

  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="user.do">userController</prop>

            </props>

        </property>

    </bean>

 

<bean id="userController" class="com.sxt.action.UserController">

    <property name="userService" ref="userService"></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="userService" class="com.sxt.service.UserService">

       <property name="userDao" ref="userDao"></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.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>

 

  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="userDao" class="com.sxt.dao.UserDao">

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

    </bean>

</beans>

 

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

 

  1. 各類程式碼如下:

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;

    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 org.springframework.orm.hibernate3.HibernateTemplate;

 

import com.sxt.po.User;

 

public class UserDao {

         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 com.sxt.dao.UserDao;

import com.sxt.po.User;

 

public class UserService {

        

         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.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.sxt.service.UserService;

 

public class UserController implements Controller {

 

         private UserService userService;

        

         @Override

         public ModelAndView handleRequest(HttpServletRequest req,

                            HttpServletResponse resp) throws Exception {

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

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

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

                   return new ModelAndView("index");

         }

 

         public UserService getUserService() {

                   return userService;

         }

 

         public void setUserService(UserService userService) {

                   this.userService = userService;

         }

 

        

}

 

  1. 執行測試:

http://locahost:8080/springmvc01/user.do?uname=zhangsan

 

結果:資料庫中增加zhangsan的記錄。頁面跳轉到index.jsp上,顯示:

 

基於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.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>

 

  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.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>

 

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

  </body>

</html>

 

 

  1. 建立整個專案的包結構和相關類。如下圖所示:

 

  1. 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;

         }

 

        

}

 

  1. 執行測試:

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

 

則會呼叫userController的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.sxt.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.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>

 

  1. web.xml檔案不變
  2. 類的程式碼不變。
  3. 執行,測試。跟上一個專案保持一致。

 

 

Spring MVC 3.0 深入

核心原理

  1. 使用者傳送請求給伺服器。url:user.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

spring的aop面向切面程式設計

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能找到定義為controller的bean,需要在spring-context配置檔案中增加如下定義:

 

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

 

         注:實際上,使用@component,也可以起到@Controller同樣的作用。

 

@RequestMapping

 

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

       在方法前面定義,則將url和類的方法繫結,如下所示:

package com.sxt.web;

 

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

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

import com.sxt.service.UserService;

 

@Controller

@RequestMapping("/user.do")

public class UserController  {

 

    @Resource

    private UserService userService;

   

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

    @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;

    }

 

   

}

 

@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("/user.do")

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

public class UserController  {

    @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>

   

    注:名字為”user”的屬性再結合使用註解@SessionAttributes可能會報錯。

 

@ModelAttribute

      這個註解可以跟@SessionAttributes配合在一起用。可以將ModelMap中屬性的值通過該註解自動賦給指定變數。

    示例程式碼如下:

package com.sxt.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("/user.do")

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

public class UserController  {

   

    @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[微軟使用者1] ,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.sxt.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("/user.do")

public class UserController  {

   

    @RequestMapping(params="method=reg4")

    public String reg4(ModelMap map) {

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

//     return "forward:index.jsp";

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

//     return "redirect:user.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("/user.do")

public class UserController  {

   

    @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.sxt.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("/user.do")

public class UserController 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.sxt.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.sxt.po.User;

 

@Controller

@RequestMapping("/user.do")

public class UserController extends MultiActionController  {

   

    @RequestMapping(params="method=reg")

    public ModelAndView reg(String uname){

       ModelAndView mv = new ModelAndView();

       mv.setViewName("index");

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

      

       User u = new User();

       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.user.uname}</h1>

  </body>

</html>

位址列輸入:http://localhost:8080/springmvc03/user.do?method=reg

結果為:

 

 

 

基於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.sxt.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")[微軟使用者2] 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);" οnclick="sendAjaxReq();">測試</a>

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

  </body>

</html>

 

 

  1. 伺服器端程式碼如下:

        

package com.sxt.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.sxt.po.User;

 

@Controller

@RequestMapping("myajax.do")

public class MyAjaxController {

        

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

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

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

                   System.out.println(uname2);

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

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

                   list.add(new User("高淇","123"));

                   list.add(new User("馬士兵","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.sxt.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.sxt.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.sxt.interceptor.MyInterceptor"></bean> <!-- 攔截所有springmvcurl! -->

       <mvc:interceptor>

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

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

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

       </mvc:interceptor>

    </mvc:interceptors>

 

 


 

轉載於:https://www.cnblogs.com/xifenglou/p/5606847.html

相關文章