1. 程式人生 > >使用Maven創建一個Spring MVC Web 項目

使用Maven創建一個Spring MVC Web 項目

dart 目的 servle end location r文件 ext version ons

使用Maven創建java web 項目(Spring MVC)用到如下工具:

1、Maven 3.2

2、IntelliJ IDEA 13

3、JDK 1.7

4、Spring 4.1.1 released

5、Tomcat7

6、Logback 1.0.13 日誌輸出組件

接下來開始演示如何用Maven模板創建web項目

1、使用maven-archetype-webapp模板快速創建web項目的骨架結構

打開控制臺,進入到你想要創建web項目的目錄,然後運行如下命令:

1 $ mvn archetype:generate -DgroupId=com.yanyd 
2     -DartifactId=CounterWebApp 
3     -DarchetypeArtifactId=maven-archetype-webapp 
4     -DinteractiveMode=false

一個名為CounterWebApp的項目就被創建起來了,標準的web目錄結構就會被自動創建,結構如下:

技術分享
1 |____CounterWebApp
2 | |____pom.xml
3 | |____src
4 | | |____main
5 | | | |____resources
6 | | | |____webapp
7 | | | | |____index.jsp
8 | | | | |____WEB-INF
9 | | | | | |____web.xml
技術分享

源碼包java/com/yanyd並不會自動創建,需要我們自己手動創建,然後將在IDEA中將該目錄變成src目錄。

2、使用命令mvn idea:idea 把該項目變成IDEA支持的項目,然後導入中IDEA中進行編程。

接下來要在pom.xml文件中配置項目依賴的文件和編譯、部署插件,內容如下:

技術分享
  1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3   <modelVersion>4.0.0</modelVersion>
  4   <groupId>com.yanyd</groupId>
  5   <artifactId>CounterWebApp</artifactId>
  6   <packaging>war</packaging>
  7   <version>1.0-SNAPSHOT</version>
  8   <name>CounterWebApp Maven Webapp</name>
  9   <url>http://maven.apache.org</url>
 10   <properties>
 11       <jdk.version>1.7</jdk.version>
 12       <spring.version>4.1.1.RELEASE</spring.version>
 13       <jstl.version>1.2</jstl.version>
 14       <junit.version>4.11</junit.version>
 15       <logback.version>1.0.13</logback.version>
 16       <jcl-over-slf4j.version>1.7.5</jcl-over-slf4j.version>
 17   </properties>
 18   <dependencies>
 19     <dependency>
 20       <groupId>junit</groupId>
 21       <artifactId>junit</artifactId>
 22       <version>${junit.version}</version>
 23       <scope>test</scope>
 24     </dependency>
 25 
 26     <!--spring core-->
 27       <dependency>
 28           <groupId>org.springframework</groupId>
 29           <artifactId>spring-core</artifactId>
 30           <version>${spring.version}</version>
 31           <exclusions>
 32               <exclusion>
 33                   <groupId>commons-logging</groupId>
 34                   <artifactId>commons-logging</artifactId>
 35               </exclusion>
 36           </exclusions>
 37       </dependency>
 38 
 39       <dependency>
 40           <groupId>org.slf4j</groupId>
 41           <artifactId>jcl-over-slf4j</artifactId>
 42           <version>${jcl-over-slf4j.version}</version>
 43       </dependency>
 44 
 45       <dependency>
 46           <groupId>ch.qos.logback</groupId>
 47           <artifactId>logback-classic</artifactId>
 48           <version>${logback.version}</version>
 49       </dependency>
 50 
 51       <dependency>
 52           <groupId>org.springframework</groupId>
 53           <artifactId>spring-web</artifactId>
 54           <version>${spring.version}</version>
 55       </dependency>
 56 
 57       <dependency>
 58           <groupId>org.springframework</groupId>
 59           <artifactId>spring-webmvc</artifactId>
 60           <version>${spring.version}</version>
 61       </dependency>
 62 
 63       <!-- jstl -->
 64       <dependency>
 65           <groupId>jstl</groupId>
 66           <artifactId>jstl</artifactId>
 67           <version>${jstl.version}</version>
 68       </dependency>
 69 
 70   </dependencies>
 71   <build>
 72     <!--最終生成的war文件名-->
 73     <finalName>CounterWebApp</finalName>
 74     <plugins>
 75 
 76         <!-- Set JDK Compiler Level -->
 77         <plugin>
 78             <groupId>org.apache.maven.plugins</groupId>
 79             <artifactId>maven-compiler-plugin</artifactId>
 80             <version>3.2</version>
 81             <configuration>
 82                 <source>${jdk.version}</source>
 83                 <target>${jdk.version}</target>
 84             </configuration>
 85         </plugin>
 86 
 87         <!-- For Maven Tomcat Plugin -->
 88         <plugin>
 89             <groupId>org.apache.tomcat.maven</groupId>
 90             <artifactId>tomcat7-maven-plugin</artifactId>
 91             <version>2.2</version>
 92             <configuration>
 93                 <!--Deploy to server-->
 94                 <url>http://localhost:8080/manager/text</url>
 95                 <server>Tomcat7Server</server>
 96                 <path>/CounterWebApp</path>
 97             </configuration>
 98         </plugin>
 99     </plugins>
100   </build>
101 </project>
技術分享

3、編寫源文件,測試Spring MVC框架是否正常,最終的文件結構如下:

技術分享
 1 |____pom.xml
 2 |____src
 3 | |____main
 4 | | |____java
 5 | | | |____com
 6 | | | | |____yanyd
 7 | | | | | |____controller
 8 | | | | | | |____BaseController.java
 9 | | |____resources
10 | | | |____logback.xml
11 | | |____webapp
12 | | | |____WEB-INF
13 | | | | |____mvc-dispatcher-servlet.xml
14 | | | | |____pages
15 | | | | | |____index.jsp
16 | | | | |____web.xml
技術分享

開始寫Spring MVC控制類,BaseController.java:

技術分享
 1 package com.yanyd.controller;
 2 
 3 import org.slf4j.Logger;
 4 import org.slf4j.LoggerFactory;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.ui.ModelMap;
 7 import org.springframework.web.bind.annotation.PathVariable;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.RequestMethod;
10 
11 /**
12  * Created by Administrator on 15-1-31.
13  */
14 /*There must be a Controller annotation or the application will doesn‘t work .*/
15 @Controller
16 public class BaseController {
17     private static int counter=0;
18     private static final String VIEW_INDEX="index";
19     private static final Logger logger= LoggerFactory.getLogger(BaseController.class);
20 
21     @RequestMapping(value = "/" ,method = RequestMethod.GET)
22     public String welcome(ModelMap model){
23         model.addAttribute("message","Welcome");
24         model.addAttribute("counter",++counter);
25         logger.debug("[Welcome counter :{}",counter);
26         return VIEW_INDEX;//返回index.jsp
27     }
28 
29     @RequestMapping(value = "/{name}" ,method = RequestMethod.GET)
30     public String welcome(@PathVariable String name , ModelMap model){
31         model.addAttribute("message","Welcome "+name);
32         model.addAttribute("counter",++counter);
33         logger.debug("[Welcome counter :{}",counter);
34         return VIEW_INDEX;//返回index.jsp
35     }
36 }
技術分享

有一點要註意的就是Controller註解一定寫,否則部署後訪問時會出現404,一直找不到問題在哪!

接著寫Spring的配置文件,mvc-dispatcher-servlet.xml:

技術分享
 1 <beans xmlns="http://www.springframework.org/schema/beans"
 2        xmlns:context="http://www.springframework.org/schema/context"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xsi:schemaLocation="
 5         http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         http://www.springframework.org/schema/context/spring-context.xsd">
 9 
10     <context:component-scan base-package="com.yanyd.controller"/>
11     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
12         <property name="prefix">
13             <value>/WEB-INF/pages/</value>
14         </property>
15         <property name="suffix">
16             <value>.jsp</value>
17         </property>
18     </bean>
19 </beans>
技術分享

最後要在web.xml文件中把Spring框架集成進來並配置監聽器:

技術分享
 1 <web-app xmlns="http://java.sun.com/xml/ns/javaee"
 2          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 3          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 4           http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 5          version="2.5">
 6 
 7     <display-name>Counter  Web  Application </display-name>
 8 
 9     <servlet>
10         <servlet-name>mvc-dispatcher</servlet-name>
11         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
12         <load-on-startup>1</load-on-startup>
13     </servlet>
14     <servlet-mapping>
15         <servlet-name>mvc-dispatcher</servlet-name>
16         <url-pattern>/</url-pattern>
17     </servlet-mapping>
18 
19     <context-param>
20         <param-name>contextConfigLocation</param-name>
21         <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
22     </context-param>
23     
24     <listener>
25         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
26     </listener>
27 </web-app>
技術分享

為了避免我們的jsp文件被直接訪問,需要在WEB-INF目錄下創建一個pages目錄,並把jsp文件放入裏面,index.jsp內容如下:

技術分享
1 <html>
2 <body>
3 <h1>Maven + Spring MVC Web Project Example</h1>
4 <h2>Hello World!</h2>
5 <h3>Message:${message}</h3>
6 <h3>Counter:${counter}</h3>
7 </body>
8 </html>
技術分享

為了讓日誌輸出組件起作用,還需在resources目錄下創建一個日誌輸出的配置文件logback.xml:

技術分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <configuration>
 3 
 4     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
 5         <layout class="ch.qos.logback.classic.PatternLayout">
 6 
 7             <Pattern>
 8                 %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
 9             </Pattern>
10 
11         </layout>
12     </appender>
13 
14     <logger name="com.yanyd.controller" level="debug"
15             additivity="false">
16         <appender-ref ref="STDOUT" />
17     </logger>
18 
19     <root level="error">
20         <appender-ref ref="STDOUT" />
21     </root>
22 
23  </configuration>
技術分享

4、部署web項目

方法1:mvn package,把生成的war文件部署到tomcat裏。

方法2:mvn idea:idea,把項目轉成支持IDEA的項目後直接在IDEA中部署。

方法3:mvn tomcat:run,如果已經在pom文件裏配置了tomcat部署插件,直接運行該命令,會把項目部署到8080端口。

5、訪問項目

http://localhost:8080/CounterWebApp/

http://localhost:8080/CounterWebApp/yanyd

如果內容正常輸出,那麽就是部署成功,項目結構也沒問題!

使用Maven創建一個Spring MVC Web 項目