1. 程式人生 > >SpringMVC配置詳情

SpringMVC配置詳情

現在主流的Web MVC框架除了Struts這個主力 外,其次就是Spring MVC了,因此這也是作為一名程式設計師需要掌握的主流框架,框架選擇多了,應對多變的需求和業務時,可實行的方案自然就多了。不過要想靈活運用Spring MVC來應對大多數的Web開發,就必須要掌握它的配置及原理。

  一、Spring MVC環境搭建:(Spring 2.5.6 + Hibernate 3.2.0)

  1. jar包引入

  Spring 2.5.6:spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar

  Hibernate 3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、javassist-3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相應資料庫的驅動jar包

 

SpringMVC是一個基於DispatcherServlet的MVC框架,每一個請求最先訪問的都是DispatcherServlet,DispatcherServlet負責轉發每一個Request請求給相應的Handler,Handler處理以後再返回相應的檢視(View)和模型(Model),返回的檢視和模型都可以不指定,即可以只返回Model或只返回View或都不返回。

DispatcherServlet是繼承自HttpServlet的,既然SpringMVC是基於DispatcherServlet的,那麼我們先來配置一下DispatcherServlet,好讓它能夠管理我們希望它管理的內容。HttpServlet是在web.xml檔案中宣告的。

複製程式碼
<!-- Spring MVC配置 -->
<!-- ====================================== -->
<servlet>
    <servlet-name>spring</servlet-name
> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 可以自定義servlet.xml配置檔案的位置和名稱,預設為WEB-INF目錄下,名稱為[<servlet-name>]-servlet.xml,如spring-servlet.xml <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-servlet.xml</param-value>&nbsp; 預設 </init-param> --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Spring配置 --> <!-- ====================================== --> <listener> <listenerclass> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- 指定Spring Bean的配置檔案所在目錄。預設配置在WEB-INF目錄下 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:config/applicationContext.xml</param-value> </context-param>
複製程式碼

 

 spring-servlet.xml配置

  spring-servlet這個名字是因為上面web.xml中<servlet-name>標籤配的值為spring(<servlet-name>spring</servlet-name>),再加上“-servlet”字尾而形成的spring-servlet.xml檔名,如果改為springMVC,對應的檔名則為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-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       http://www.springframework.org/schema/context <a href="http://www.springframework.org/schema/context/spring-context-3.0.xsd">http://www.springframework.org/schema/context/spring-context-3.0.xsd</a>">

    <!-- 啟用spring mvc 註解 -->
    <context:annotation-config />

    <!-- 設定使用註解的類所在的jar包 -->
    <context:component-scan base-package="controller"></context:component-scan>

    <!-- 完成請求和註解POJO的對映 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  
    <!-- 對轉向頁面的路徑解析。prefix:字首, suffix:字尾 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
</beans>
複製程式碼

 

DispatcherServlet會利用一些特殊的bean來處理Request請求和生成相應的檢視返回。

關於檢視的返回,Controller只負責傳回來一個值,然後到底返回的是什麼檢視,是由檢視解析器控制的,在jsp中常用的檢視解析器是InternalResourceViewResovler,它會要求一個字首和一個字尾

在上述檢視解析器中,如果Controller返回的是blog/index,那麼通過檢視解析器解析之後的檢視就是/jsp/blog/index.jsp。

 

 

主要是說說Controller.

一個類使用了@Controller進行標記的都是Controller

複製程式碼
package controller;

import javax.servlet.http.HttpServletRequest;

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

import entity.User;

@Controller  //類似Struts的Action
public class TestController {

    @RequestMapping("test/login.do")  // 請求url地址對映,類似Struts的action-mapping
    public String testLogin(@RequestParam(value="username")String username, String password, HttpServletRequest request) {
        // @RequestParam是指請求url地址對映中必須含有的引數(除非屬性required=false)
        // @RequestParam可簡寫為:@RequestParam("username")

        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError"; // 跳轉頁面路徑(預設為轉發),該路徑不需要包含spring-servlet配置檔案中配置的字首和字尾
        }
        return "loginSuccess";
    }

    @RequestMapping("/test/login2.do")
    public ModelAndView testLogin2(String username, String password, int age){
        // request和response不必非要出現在方法中,如果用不上的話可以去掉
        // 引數的名稱是與頁面控制元件的name相匹配,引數型別會自動被轉換
        
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return new ModelAndView("loginError"); // 手動例項化ModelAndView完成跳轉頁面(轉發),效果等同於上面的方法返回字串
        }
        return new ModelAndView(new RedirectView("../index.jsp"));  // 採用重定向方式跳轉頁面
        // 重定向還有一種簡單寫法
        // return new ModelAndView("redirect:../index.jsp");
    }

    @RequestMapping("/test/login3.do")
    public ModelAndView testLogin3(User user) {
        // 同樣支援引數為表單物件,類似於Struts的ActionForm,User不需要任何配置,直接寫即可
        String username = user.getUsername();
        String password = user.getPassword();
        int age = user.getAge();
        
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return new ModelAndView("loginError");
        }
        return new ModelAndView("loginSuccess");
    }

    @Resource(name = "loginService")  // 獲取applicationContext.xml中bean的id為loginService的,並注入
    private LoginService loginService;  //等價於spring傳統注入方式寫get和set方法,這樣的好處是簡潔工整,省去了不必要得程式碼

    @RequestMapping("/test/login4.do")
    public String testLogin4(User user) {
        if (loginService.login(user) == false) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
複製程式碼

 

以上4個方法示例,是一個Controller裡含有不同的請求url,也可以採用一個url訪問,通過url引數來區分訪問不同的方法,程式碼如下:

複製程式碼
package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/test2/login.do")  // 指定唯一一個*.do請求關聯到該Controller
public class TestController2 {
    
    @RequestMapping
    public String testLogin(String username, String password, int age) {
        // 如果不加任何引數,則在請求/test2/login.do時,便預設執行該方法
        
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }

    @RequestMapping(params = "method=1", method=RequestMethod.POST)
    public String testLogin2(String username, String password) {
        // 依據params的引數method的值來區分不同的呼叫方法
        // 可以指定頁面請求方式的型別,預設為get請求
        
        if (!"admin".equals(username) || !"admin".equals(password)) {
            return "loginError";
        }
        return "loginSuccess";
    }
    
    @RequestMapping(params = "method=2")
    public String testLogin3(String username, String password, int age) {
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
複製程式碼

 

 其實RequestMapping在Class上,可看做是父Request請求url,而RequestMapping在方法上的可看做是子Request請求url,父子請求url最終會拼起來與頁面請求url進行匹配,因此RequestMapping也可以這麼寫:

複製程式碼
package controller;

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

@Controller
@RequestMapping("/test3/*")  // 父request請求url
public class TestController3 {

    @RequestMapping("login.do")  // 子request請求url,拼接後等價於/test3/login.do
    public String testLogin(String username, String password, int age) {
        if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
            return "loginError";
        }
        return "loginSuccess";
    }
}
複製程式碼

 

在SpringMVC中常用的註解還有@PathVariable,@RequestParam,@PathVariable標記在方法的引數上,利用它標記的引數可以利用請求路徑傳值,看下面一個例子

@RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST)
public void comment(Comment comment,@PathVariable int blogId, HttpSession session, HttpServletResponse response) throws IOException {
    
}

 

在該例子中,blogId是被@PathVariable標記為請求路徑變數的,如果請求的是/blog/comment/1.do的時候就表示blogId的值為1. 同樣@RequestParam也是用來給引數傳值的,但是它是從頭request的引數裡面取值,相當於request.getParameter("引數名")方法。

在Controller的方法中,如果需要WEB元素HttpServletRequest,HttpServletResponse和HttpSession,只需要在給方法一個對應的引數,那麼在訪問的時候SpringMVC就會自動給其傳值,但是需要注意的是在傳入Session的時候如果是第一次訪問系統的時候就呼叫session會報錯,因為這個時候session還沒有生成。