Spring MVC入門(4.1版本)

(初版,2014年12月27日)javascript

Web MVC框架中除了最流行的Struts,還有Spring MVC,相對來講Spring MVC更加靈活、簡便,若是你只是開發一個小型的web應用,我認爲Spring MVC是更好的選擇。html

下面我就以一個簡單的例子來講明Spring MVC的基本用法。(示例程序我已上傳至gitcafe,https://gitcafe.com/xt/SpringMVC_Studyjava

首先下載相關的jar包:jquery

spring:http://maven.springframework.org/release/org/springframework/spring/git

jackson:http://repo1.maven.org/maven2/com/fasterxml/jackson/core/  (爲實現先後臺傳遞json數據)web

commons logging:http://commons.apache.org/proper/commons-logging/download_logging.cgiajax

JSTL:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/spring

導入的包以下圖所示:apache

 (固然,若是你懶得下載,能夠直接下載個人工程,將裏面lib文件夾下的包導入你本身的工程裏去便可。)json

新建一個web工程,名稱爲SpringMVC_Study,以後配置web.xml,內容以下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
 xsi:schemaLocation=
 	"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
 	id="WebApp_ID" version="3.0">
 	
 	<!-- spring MVC配置 -->       
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springservlet-config.xml</param-value>
        </init-param>       
        <load-on-startup>1</load-on-startup>
    </servlet>  
    <servlet-mapping>  
	    <servlet-name>SpringMVC</servlet-name>  
	    <url-pattern>/</url-pattern>
	</servlet-mapping> 
  	
  	<!-- 配置post表單編碼格式(避免中文亂碼) -->
  	<filter>
	    <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

在配置中,設置了一個名爲「springMVC」的servlet,其實現類爲spring的DispatcherServlet。contextConfigLocation指定了這個servlet的配置文件位置和名稱,load-on-startup的屬性值爲1,意爲隨着servlet容器一同啓動,servlet-mapping設置爲「/」,即攔截全部請求。

下面在src目錄下新建Spring MVC的配置文件:springservlet-config.xml(其路徑名稱與web.xml中contextConfigLocation的值相對應:即classpath:springservlet-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:p="http://www.springframework.org/schema/p" 
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
 

    <!-- 使用默認的註解映射 --> 
    <mvc:annotation-driven/>

    <!-- 自動掃描controller包中的控制器 -->
    <context:component-scan base-package="controller"/>

    <!-- 視圖解析路徑配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
       <property name="contentType" value="text/html"/>        
       <property name="prefix" value="/WEB-INF/page/"/>
       <property name="suffix" value=".jsp"/>
    </bean>
    
    <!-- Json轉換器配置 -->
    <bean id="mappingJackson2HttpMessageConverter" 
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">    
        <property name="supportedMediaTypes">    
            <list>    
                <value>text/html;charset=UTF-8</value>    
            </list>    
        </property>    
    </bean>     
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    
        <property name="messageConverters">    
            <list>    
                <ref bean="mappingJackson2HttpMessageConverter" />
            </list>    
        </property>    
    </bean>  
    
    <!-- 配置靜態資源(JS、CSS、圖片等)的訪問路徑 -->
    <mvc:resources location="/WEB-INF/plugin/" mapping="/plugin/**"/>
    
</beans>

其中須要說明的是文件最後位置的mvc:resources屬性,因以前在web.xml中設置的是攔截全部請求,所以頁面文件訪問服務器的JS、CSS、圖片等文件時也會被攔截掉。這裏配置了靜態資源的訪問路徑,因此對「plugin」這個文件夾下內容的訪問將再也不被攔截(所以應將將這些文件放在plugin文件夾裏),

以上就是Spring MVC的基本配置了,下面新建一個包:controller,在其下再新建一個類:LoginController,做爲登陸控制器,用來處理用戶登陸的請求,代碼以下:

package controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import service.PersonService;
import entity.Person;

@Controller
public class LoginController {

    
    //域名訪問跳轉到登陸頁
    @RequestMapping("/")    
    public String index(){    

        return "login";    
    }
    
    //登陸跳轉到首頁
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public ModelAndView login(String nickname){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("home/index");
        mv.addObject("nickname",nickname);
        return mv;
    }
    
    //獲取人員信息
    @RequestMapping(value="/getPersonData.do")
    @ResponseBody //添加該註釋後,返回值將由轉換器進行轉換,轉換器爲Jackson,因此會轉換成json格式
    public Map<String,Object> getPersonData(){
        Map<String,Object> personMap = new HashMap<String,Object>();
        PersonService service = new PersonService();
        
        List<Person> personData = service.getPersonInfo();
        personMap.put("rows",personData);
        
        return personMap;
        
    }

}

 類前面前加了「@Controller」註釋,因上面Spring MVC配置文件中配置了對controller包的掃描,因此加了註釋的類會被spring容器自動識別。「@RequestMapping」註釋用來配置跳轉,能夠直接返回一個字符串來匹配要跳轉的JSP文件名稱,也能夠返回一個ModelAndView,裏面除了包含跳轉文件名稱,還能夠包含參數。添加了「@ResponseBody」註釋的函數,其返回值會被轉換器進行轉換,因在配置文件中設置了轉換器爲Jackson,因此會轉換成json格式。

爲了模擬一個web應用的開發,再新建兩個類:personService和PersonBean,做爲業務邏輯和數據模型。

其代碼以下:

Person:

package entity;

public class Person {
    private Integer id;
    private String name;
    private String age;
    private String description;
    
    public Person(Integer id, String name, String age, String description) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.description = description;
    }
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

Person類爲一個POJO,用來存儲人員信息。

PersonService:

package service;

import java.util.ArrayList;
import java.util.List;

import entity.Person;

public class PersonService {
    
    public List<Person> getPersonInfo(){
        List<Person> personData = new ArrayList<Person>();
        //填充數據
        Person p = null;
        p = new Person(1,"小明","25","中共黨員");
        personData.add(p);
        p = new Person(1,"小華","21","共青團員");
        personData.add(p);
        p = new Person(1,"小麗","13","少先隊員");
        personData.add(p);
        return personData;
    }

}

PersonService只包含一個方法getPersonInfo,返回3條含有數據的Person實例。

以上就是用到的JAVA代碼了,下面新建兩個JSP文件login.jsp和index.jsp做爲前臺頁面,其代碼分別以下:

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>登陸</title>
    </head>
<body>
    <form id="loginFrom" name="loginFrom" method="post" action="login.do">
        <label>請輸入暱稱:</label>
        <input id="nickname" name="nickname" type="text"/>
        <button id="login" type="submit">登陸</button>    
    </form>
    <h2 id="errorMsg">${errorMsg}</h2>
</body>
</html>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>歡迎</title>
        
        <script src="plugin/jquery-1.11.2.js"></script>
<script type="text/javascript">
function getPersonData() {
     $.ajax({
         url: "getPersonData.do", 
         success: function (result) {
             var content = "";
            for (var i = 0; i < result.rows.length; i++) {
                var item = result.rows[i];
                content += item.name+","+item.age+","+item.description+"<br>"; 
            }
               $("#personData").after(content);
         }
     });
}
</script>
    </head>
<body>
    你好!${nickname}<br>
    <button onclick="getPersonData()" id="submitButton">獲取人員信息</button>
    <div id="personData"></div>
</body>
</html>

這裏使用了jQuery,將jQuery文件其放到plugin文件夾下便可。

 

以上就是整個示例工程的代碼了,部署到Tomcat後,訪問 http://localhost:8080/SpringMVC_Study/ ,彈出頁面以下:

輸入暱稱後,點擊「登陸」,跳轉至首頁:

點擊「獲取人員信息」,會調用getPersonData方法,返回json格式數據,在index.jsp中對返回的json數據進行了解析,並輸出到頁面上:

 

OK,講解完畢,但願能對你有所幫助 :)

另外,若是你是在一個項目組中,或者研發一個較大的系統,建議使用3.x版本,目前對4.x版本的資料還比較有限,並且一些接口也發生了變化,很容易形成麻煩(好比配置Jackson,3和4就不太同樣,坑了我很久。。。)

相關文章
相關標籤/搜索