spring入門(五)【springMVC環境搭建】,springspringmvc

來源:互聯網
上載者:User

spring入門(五)【springMVC環境搭建】,springspringmvc

springMVC作為spring的一個WEB組件,是一個MVC的思想,減少了WEB開發的難度,現介紹springMVC環境的搭建,具體的原理放在後面介紹。用過架構的朋友都知道要在WEB項目中使用一個架構,必須要引入這個架構,和其他架構的引用方式一樣,springMVC的引入方式是通過DispatcherServlet,那麼我們就要在web.xml中配置此servlet,在lib目錄下我已經把用到的jar包全部匯入,下面看我的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" 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">  <display-name>springmvc</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>    <!--log4j的設定檔-->      <context-param>        <param-name>log4jConfigLocation</param-name>        <param-value>/WEB-INF/classes/log4j.properties</param-value>            </context-param>    <!--spring的設定檔-->   <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:application-context.xml</param-value>    </context-param>    <!--配置springmvc-->  <servlet>      <servlet-name>springmvc</servlet-name>      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>    <!--springmvc的設定檔-->    <init-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/classes/springmvc.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>  <!--配置spring-->  <listener>      <listener-class>      org.springframework.web.context.ContextLoaderListener      </listener-class>  </listener>  <!--配置系統中的日誌-->    <listener>        <listener-class>            org.springframework.web.util.Log4jConfigListener        </listener-class>    </listener></web-app>

springMVC

在設定檔中我們配置了DispatherServlet,並且配置了它的初始化參數contextConfigLocation,指定了檔案所在的路徑為:/WEB-INF/classes下;配置了攔截的URL,我們這裡攔截所有的url

spring

你可能會疑惑,這裡我們為什麼又配置了spring,難道只有springmvc不可用嗎?答案是可以的,我們完全可以把所有的配置都放在springmvc的設定檔中,但是我們這裡遵循層次化的配置,讓springMVC是一個設定檔,spring是一個設定檔,把他們所要完成的功能分開,其實所有的配置完全可以由dispatherServlet進行載入。

spring的載入方式這裡使用了一個監聽器,ContextLoaderListener,他會讀取context中的配置參數:contextConfigLocation,讀取spring的設定檔,載入spring容器。

log4j

由於在項目中要使用日誌功能,所以這裡配置了日誌,且引用context中的設定檔。

下面看springmvc的設定檔,

<?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"    xmlns:mvc="http://www.springframework.org/schema/mvc"    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    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"    >    <!--配置了組件掃描,就不需要配置<context:annotation-config> ,因為組件掃描已經包含了,    組件掃描,掃描的註解有@Controller,@Service,@Resposity,@Component,    @Controller註解必須由dispatherDispatcherServlet來掃描,    也實現了依賴注入,對    @Autowired,@Resource的支援    -->    <context:component-scan base-package="com.cn.my">        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>            <!--開啟基於註解的驅動-->    <context:annotation-config></context:annotation-config>    <!--開啟mvc的註解驅動 ,可以使用@RequestParam註解,可以將請求參數幫到到控制器參數上-->    <mvc:annotation-driven/>            <mvc:resources location="/resource/*" mapping="/resource/**"/>    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"></property>        <property name="suffix" value=".jsp"></property>             </bean></beans>

上面是springmvc的設定檔,首先配置了組件掃描,組件掃描的作用是會自動類層級的註解(@Controller、@Component、@Service、@Resposity),這裡配置了只掃描帶有@Controller註解的類,是因為具有@Controller註解的類只能由DispatherServlet載入,接著開啟了基於註解的驅動,此驅動可以實現依賴注入,對@Autowired、@Resource註解起作用,其實可以不配置,因為在組件掃描中已經包含了此功能;基於mvc的註解驅動,可以方便將請求參數邦定到控制器參數上。
最下面配置了視圖解析器,這裡使用的預設的視圖解析器。

 

再看spring的設定檔,

<?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"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"    ><context:component-scan base-package="com.cn.my"><context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/></context:component-scan><!--配置一個資料來源,使用spring提供的資料來源--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"></property><property name="url" value="jdbc:mysql://127.0.0.1:3306/test"></property><property name="username" value="root"></property><property name="password" value="123456"></property></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"></property></bean></beans>

  spring的作用可以實現資料來源的配置,事務或者service層的依賴注入,首先是組件掃描,掃描的對象是除了@Controller的註解,接著是一個資料來源,這裡使用了spring提供的資料來源,其他還可以使用DBCP、C3P0、JNDI等方式,在後邊討論。

然後配置了一個Data Access ObjectsJdbcTemplate,通過此對象可以對資料庫進行操作。

至此我們的環境已經搭建完畢,下面是具體的使用,

編寫Controller類,

由於我們使用了組件掃描,所以在類上使用註解@Controller

package com.cn.my.controllor;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.cn.my.service.CourseServiceInter;@Controller@RequestMapping("/my/*")public class MyController {    @Autowired    private CourseServiceInter csi;        //一般類型的url        @RequestMapping("my")    public String method(HttpServletRequest request,@RequestParam("courseId") String courseid){                csi.findCourse(courseid);        return "success";    }    //restful形式的URL    //http://localhost:8080/my/my2/12    @RequestMapping("my2/{courseId}/{name}")    public String method2(@PathVariable("courseId") String courseId,@PathVariable("name") String name){        csi.findCourse(courseId+"  "+name);        return "success";    }}

除了在類上使用了@Controller註解,還是用了@RequestMapping註解,註明訪問的路徑,接著在方法method上又使用@RequestMapping註解,一個完整的url訪問路徑由類上的路徑加方法上的路徑組成,例:/my/my.do,這就是一個訪問路徑,我們還使用了service層的一個findCourse方法,service層的對象有架構依賴注入;在方法中使用了@RequestParam註解,此註解可以把url中的參數邦定到方法的參數上,其中@RequestParam中的值要和url中的請求參數名一致,後面的則是對應的方法中參數名。方法最後返回的是一個String類型的值,這裡返回的是邏輯視圖名,也可以返回JSON串,這種方式在後邊介紹。

controller配置好之後,便可以訪問了,這樣一個sprigMVC的環境及controller的編寫就完成了。

有不正之處歡迎指出,謝謝!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.