學習搭建maven風格的springmvc項目(一)——入門

話不多說,開始。。

 

step1:首先在eclispe中新建一個maven項目:new->project->Maven Project,artifact選擇webapp:



 

step2:填寫項目的group id、artifact id、version、package等信息:



 

step3:打開pom.xml文件,切換至Dependencies標籤頁,選擇左側部分的Add按鈕,加入webmvc項目最基本的jar包:servlet-api和spring-webmvc,如:



 這時再切換至pom.xml標籤頁,你會發現pom.xml文件多了以下內容:

 

<dependency>
    	<groupId>javax.servlet</groupId>
    	<artifactId>servlet-api</artifactId>
    	<version>2.5</version>
    </dependency>
    <dependency>
    	<groupId>org.springframework</groupId>
    	<artifactId>spring-webmvc</artifactId>
    	<version>4.1.4.RELEASE</version>
    </dependency>

有了springmvc依賴的兩個jar包後,就可以開始進行搭建了。你也可以在<dependencies />節點下手動添加一個dependency,無論哪種方式,都等同於我們傳統方式下添加jar包。而maven是首次從中央倉庫下載jar包到本地倉庫,如果本地倉庫有,直接用dependency引用依賴即可~

 

而spring-webmvc這個jar包又引用了其他jar包,maven可以把它的依賴jar包也加載進來,但並不需要你添加它的依賴,所依賴的jar包一樣在本地倉庫中。

切換至Dependency Hierarchy標籤頁,可以看到依賴關係:

 

之後缺了什麼jar包依賴都可以通過這2種方式加進去。

 

step4:補充springmvc的配置WEB-INF/web.xml(maven項目中是在src/main/webapp/WEB-INF下):

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="schedule-console" version="3.0">
	
	<!-- 配置web.xml,使其具有springmvc特性,主要配置兩處,一個是ContextLoaderListener,一個是DispatcherServlet -->
    
    <!-- spring mvc 配置 -->
    <!-- 1.配置DispatcherServlet表示,該工程將採用springmvc的方式。 -->
    <servlet>
        <servlet-name>webmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 啓動項目的時候要加載的配置文件 -->
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath*:/spring-mvc.xml</param-value>
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>
    <servlet-mapping>
        <servlet-name>webmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 2.spring配置 :配置ContextLoaderListener表示,該工程要以spring的方式啓動.啓動時會默認在/WEB-INF目錄下查找applicationContext.xml
作爲spring容器的配置文件,該文件裏可以初始化一些bean-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- 指定Spring Bean的配置文件所在目錄。默認配置在WEB-INF目錄下 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>
    
    <!-- 字符集過濾器 -->  
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
</web-app>

 

 

step5:在src/main/resources下新建一個applicationContext.xml文件(放置事務管理信息等):

applicationContext.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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
   
   <!-- 啓用spring mvc註解 -->
   <context:annotation-config  />
   
   <!-- 配置讀取外部配置文件 -->
   <context:property-placeholder location="classpath:jdbc.properties"  />
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
   	p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" 
   	p:username="${jdbc.username}" p:password="${jdbc.password}" 
   	p:testOnBorrow="true" p:testWhileIdle="true" p:testOnReturn="true"
   	p:timeBetweenEvictionRunsMillis="1800000" p:numTestsPerEvictionRun="3" p:minEvictableIdleTimeMillis="1800000"/>
   	
   <!-- jdbcTemplate -->
   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" 
   	p:dataSource-ref="dataSource"/>
   	
   <!-- 配置事務管理器 -->
   <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
    p:dataSource-ref="dataSource" />
   
    <!-- 事務掃描開始(開啓@Tranctional) -->
    <tx:annotation-driven transaction-manager="txManager" />
    
</beans>

 

 

step6:同理,在src/main/resources下新建一個spring-mvc.xml來配置一些springmvc的基本信息,以及jdbc的屬性文件jdbc.properties:

spring-mvc.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx" 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/context 
       http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  	
  	 <!-- 基本包掃描 -->
   <context:component-scan base-package="com.spring" /> 
  	
  	<!-- 註冊HandlerMapper、HandlerAdapter兩個映射類,負責將請求映射到類和方法中 -->
    <mvc:annotation-driven />

    <!-- 訪問靜態資源,如js, css文件等 -->
    <mvc:default-servlet-handler />
    
    <!-- 視圖解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean> 
  
</beans>

 jdbc.properties:

 

 

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/xxxx?useUnicode=true&characterEncoding=UTF-8
jdbc.username=*********
jdbc.password=************

 

 

step7:在基本掃描包com.spring(spring-mvc.xml裏有配置)下新建一個package:controller,並新建一個LoginController.java,裏面的一個方法很簡單,用於頁面跳轉~

 

package com.spring.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Controller
public class LoginController {

	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("index");
		return mav;
	}
}

 

 

或者說這樣寫:

 

@RequestMapping("/index")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "index";
	}

 這意味着,你在頁面輸入:http://127.0.0.1/springmvc/index會跳轉到WEB-INF/view下的index.jsp頁面。ModelAndView包含了一個model屬性和一個view屬性:model:其實是一個ModelMap類型,view:包含了一些視圖信息。視圖解析器將model中的每個元素都通過request.setAttribute(name, value);添加request請求域中。如果controller上也加了requestMapping:

 

 

@Controller
@RequestMapping("/test")
public class LoginController {

	@RequestMapping("/index")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		return "index";
	}
}

 則需輸入:http://127.0.0.1/springmvc/test/index纔會跳轉到WEB-INF/view下的index.jsp頁面。同理,如果是return "test/index"則是跳轉到view/test/index.jsp。

 

 

step8:在view下建一個index.jsp:

 

<html>
<body>
<h2>Hello Springmvc</h2>
</body>
</html>

 

 

番外篇之一:如何加入自定義的jar包,如在中央倉庫下新建一個mine/batch/${version},放我們自定義的jar包batch-${version}.jar:



 同時,同名的pom文件必須要有:

<project>
  <modelVersion>1.0</modelVersion>
  <groupId>mine</groupId>
  <artifactId>batch</artifactId>
  <version>1.0</version>
  <!--<dependencies> 如果此jar包還依賴其它jar包則在這裏加依賴
    <dependency>
      <groupId>xerces</groupId>
      <artifactId>xercesImpl</artifactId>
      <version>2.6.0</version>
      <optional>true</optional>
    </dependency>
   
  </dependencies>-->
</project>

 然後我們再在項目的pom文件的<dependencies />節點下加入:

<dependency>
    	<groupId>mine</groupId>
    	<artifactId>batch</artifactId>
    	<version>${batch.version}</version>
</dependency>

 其中${batch.version}是引用pom.xml下的屬性節點的,這種寫法方便我們以後切換版本:

<properties>
    <batch.version>1.0</batch.version>
</properties>

 

番外篇之二:別忘記右鍵項目-->properties-->Deployment Assembly-->Add-->Java Build Path Entries-->Maven Dependencies:



 

step9:啓動項目,在瀏覽器端輸入:http://localhost:7004/springmvc/index:



 step10:看一下最終最基本的結構吧~



 

入門完畢~~  下一章就開始會做登陸模塊。

 

  • 763e2796-3250-3244-b1dc-7a95df9db0b9-thumb.png
  • 大小: 35.8 KB
  • 0c493a98-84ad-382b-8e1c-b331fe8af4c7-thumb.png
  • 大小: 25.3 KB
  • 1704b337-7929-3a1e-a2bf-0df94c16479d-thumb.png
  • 大小: 22 KB
  • c778f344-7fa0-3e83-938b-7e86f349a68a-thumb.png
  • 大小: 47.2 KB
  • 7c1a2527-3022-3003-a066-9aa3cc4d2bf0-thumb.png
  • 大小: 17.6 KB
  • 65222f7f-5f18-3382-aae3-eefd690ff3b6-thumb.png
  • 大小: 51.5 KB
  • c4c81cd4-69f4-3611-bb59-59e0548d2e08-thumb.png
  • 大小: 7.4 KB
  • 580b5137-9ea1-351b-8218-5f763784bed6-thumb.png
  • 大小: 20.4 KB
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章