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還沒有生成。

本文轉載來自http://www.cnblogs.com/superjt/p/3309255.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章