1. 程式人生 > 程式設計 >詳解使用Maven開發Web應用詳細步驟

詳解使用Maven開發Web應用詳細步驟

開發 Web 應用的思路

實現一個簡單的 JSP/Servlet。

  • 搭建建立 Web 應用工程的環境。
  • 建立 Web 應用工程。
  • Web 應用工程的目錄結構。
  • 結合 Web 伺服器,釋出 Web 應用。
  • 體驗 Web 應用的開發和釋出測試過程。

實現經典的 MVC 版本的使用者 CRUD。

  • 熟練第 1 步中的幾個方面。
  • 結合典型的業務邏輯,實現 CRUD。

實現 Web 版 HelloWorld

1)選擇 File→New→Others 命令。選擇 Create Maven Project 命令,單擊“下一步”按鈕。選中建立 Web 應用工程的 Archetype,如圖 1 所示。

圖 1 選擇Web Archetype

也可以選擇其他類似的,建立 Web 應用的都可以,比如 maven-archetype-webapp 也可以。當然,也可以選擇從網上找到座標後的 Archetype 外掛,再安裝進去。

怎麼安裝新的 Archetype 呢?單擊圖中的 Add Archetype… 按鈕,在出現的視窗中輸入在網上找到的外掛座標資訊,如圖 2 所示。

圖 2 新增 Archetype

單擊 OK 按鈕,MyEclipse 會自動下載該構件。重新開啟建立工程的嚮導頁面,就可以發現新增了剛剛新增的 Archetype 外掛,如圖 3 所示。

圖 3 選擇 webapp-javaee6 Archetype

2)點選“next”,在下一個介面中輸入新建立的 Web 工程的座標資訊和包名,如圖 4 所示。

圖 4 Maven專案座標

3)單擊 Finish 按鈕,M2Eclipse 會自動建立一個 Web 工程 MvnDemo02。其在 src/main 目錄下添加了 webapp 目錄,裡面有 Web 應用特有的 WEB-INF 目錄,web.xml 和 index.jsp 等。

其中,webapp 目錄和裡面的檔案以及結構在 Maven 中也是固定的。這樣就建立好了 Web 應用工程。

編寫樣例程式碼

工程建立好了,下一步就是寫測試程式碼了。接下來會寫 3 個程式碼(2 個 jsp 和 1 個servlet)。

index.jsp,裡面顯示輸入框,能提交輸入的內容,程式碼如下所示:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Index JSP</title>
  </head>
  <body>
    <form action="welcomeServlet" method="post">
      請輸入問候人名:<input type='text' name="name"/><br/>
      <input type='submit' value='問候'/>
    </form>
  </body>
</html>

welcome.jsp,顯示問候資訊,程式碼如下所示:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome JSP</title>
  </head>
  <body>
    問候資訊:${welcome }
  </body>
</html>

welcomeServlet,接收 index.jsp 發過來的名稱,生成問候資訊,轉給 welcome.jsp 顯示。

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class WelcomeServlet
*/
public class WelcomeServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  /**
   * @see HttpServlet#service(HttpServletRequest request,HttpServletResponse
   *   response)
   */
  protected void service(HttpServletRequest request,HttpServletResponse response)
      throws ServletException,IOException {
    request.setCharacterEncoding("UTF-8");
    String name = request.getParameter("name");
    String welcome = "Hello," + name;
    request.setAttribute("welcome",welcome);
    request.getRequestDispatcher("/index.jsp").forward(request,response);
  }
}

當然,除了編寫程式碼外,還需要配置 web.xml,servlet 的,web.xml 程式碼如下所示:

<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_2_5.xsd"
  version="2.5">
  <display-name>MvnDemo02</display-name>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>WelcomeServlet</display-name>
    <servlet-name>WelcomeServlet</servlet-name>
    <servlet-class>com.mengma.demo.MvnDemo02.WelcomeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>WelcomeServlet</servlet-name>
    <url-pattern>/WelcomeServlet</url-pattern>
  </servlet-mapping>
</web-app>

構建 Web 專案

前期的構建過程同前面基本的 Java 工程一樣,根據自己的需要,在 pom.xml 中配置好對應功能的外掛,再執行對應的圖形化選單命令就可以了,在這裡不做重複說明。

一個 Web 應用構建好後,不只是編譯打包安裝就可以了,還需要將它釋出到 Web 伺服器中進行測試除錯才行。這裡主要介紹兩種釋出到 Tomcat 7 伺服器啟動測試的方式。在專案開發過程中可以根據自己的需要,選擇其中一種。

1. 使用 Maven 的 Jetty 外掛部署 Web

在 pom.xml 中新增 Jetty 外掛的座標資訊,內容如下:

<plugin>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>maven-jetty-plugin</artifactId>
  <version>6.1.26</version>
  <configuration>
    <webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory>
  </configuration>
</plugin>

在 MyEclipse 中配置 Web 伺服器執行環境。

選擇 MyEclipse 選單 Window→Preferences 命令,開啟 Preferences 視窗,選中左邊樹 Server→Runtime Environment,如圖 5 所示。

圖 5 MyEclipse的Web伺服器

單擊右邊的 Add… 按鈕,彈出一個選擇伺服器的視窗。選中視窗中的 Apache Tomcat v 7.0 伺服器,如圖 6 所示。

圖 6 新增 Tomcat 7.0

單擊 Next 按鈕,進入選擇 Tomat Server 配置頁面,選擇 Tomcat 的安裝目錄和 JRE 執行環境(JDK),如圖 7 所示。

圖 7 新增 Tomcat 的 Java home

單擊 Finish 和 Apply and Close 按鈕,關閉所有配置視窗,完成 MyEclipse 中的 Web Server 配置。

右擊“工程”,選擇 Run As→Maven build 命令,開啟自定義 launch 視窗,在 Goals 中輸入啟動的外掛名和目標“jetty:run”,如圖 8 所示。

圖 8 執行 jetty

單擊 Run 按鈕執行一次後,以後每次都可以在 Run As→Maven build 命令中選擇重複執行。

伺服器啟動了,接下來開啟瀏覽器,輸入:

http://localhost:8080/MvnDemo02/index.jsp

這樣就可以訪問第一個頁面了。

2. 使用 cargo-maven2-plugin 外掛部署 Web

使用 cargo 外掛相對簡單,只需在 pom.xml 中進行配置,指定部署應用所需要的資訊,再執行 Run As→Maven install 命令,cargo 外掛自動會把打成 war 包的應用,釋出到指定 Web 伺服器的釋出目錄下。

接下來要做的是啟動 Web 伺服器,按以前的方式開啟瀏覽器瀏覽頁面。

Gargo 在 pom.xml 中的外掛配置如下所示。

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>cn.com.mvnbook.demo</groupId>
  <artifactId>MvnDemo02</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>MvnDemo02 Web App</name>

  <properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-web-api</artifactId>
      <version>6.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>maven-jetty-plugin</artifactId>
        <version>6.1.26</version>
        <configuration>
          <webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory>
        </configuration>
      </plugin>
      <plugin>
        <!-- 指定外掛名稱及版本號 -->
        <groupId>org.codehaus.cargo</groupId>
        <artifactId>cargo-maven2-plugin</artifactId>
        <version>1.4.8</version>
        <configuration>
          <!--是否說明,操作start、stop等後續操作必須等前面操作完成才能繼續 -->
          <wait>true</wait>
          <!-- 容器的配置 -->
          <container>
            <!-- 指定tomcat版本 -->
            <containerId>tomcat7x</containerId>
            <!-- 指定型別:standalone,installed等 -->
            <type>installed</type>
            <!-- 指定Tomcat的位置,即catalina.home -->
            <home>C:\work\servers\apache-tomcat-7.0.69</home>
          </container>
          <!-- 具體的配置 -->
          <configuration>
            <!-- 型別,existing:存在 -->
            <type>existing</type>
            <!-- Tomcat的位置,即catalina.home -->
            <home>C:\work\servers\apache-tomcat-7.0.69</home>
          </configuration>
          <deployables>  <!-- 部署設定 -->
            <deployable>  <!-- 部署的War包名等 -->
              <groupId>cn.com.mvnbook.demo</groupId>
              <artifactId>MvnDemo02</artifactId>
              <type>war</type>
              <properties>
                <context>MvnDemo02</context>  <!-- 部署路徑 -->
              </properties>
            </deployable>
          </deployables>
          <deployer>    <!-- 部署配置 -->
            <type>installed</type>    <!-- 型別 -->
          </deployer>
        </configuration>
        <executions>
          <!-- 執行的動作 -->
          <execution>
            <id>verify-deployer</id>
            <phase>install</phase>   <!-- 解析install -->
            <goals>
              <goal>deployer-deploy</goal>
            </goals>
          </execution>
          <execution>
            <id>clean-deployer</id>
            <phase>clean</phase>
            <goals>
              <goal>deployer-undeploy</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.6</source>
          <target>1.6</target>
          <compilerArguments>
            <endorseddirs>${endorsed.dir}</endorseddirs>
          </compilerArguments>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.1</version>
        <configuration>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.1</version>
        <executions>
          <execution>
            <phase>validate</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <outputDirectory>${endorsed.dir}</outputDirectory>
              <silent>true</silent>
              <artifactItems>
                <artifactItem>
                  <groupId>javax</groupId>
                  <artifactId>javaee-endorsed-api</artifactId>
                  <version>6.0</version>
                  <type>jar</type>
                </artifactItem>
              </artifactItems>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
    <finalName>MvnDemo02</finalName>
  </build>
</project>

右擊“工程”,選擇 Run As→Maven install 命令後,就可以在 Tomcat 7 的釋出目錄下發現 MvnDemo02.war,啟動後它就能自動釋出並且能被訪問。

測試

不管前面哪種方式,啟動伺服器後,開啟瀏覽器,輸入 http://localhost:8080/MvnDemo02/index.jsp 連結後,就可以進行測試了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。