1. 程式人生 > >如何使用Intellij + Maven + Jetty進行Java Web開發及部署

如何使用Intellij + Maven + Jetty進行Java Web開發及部署

================================
關於Maven的配置,請參閱:http://maven.apache.org/

1. 建立Maven專案





一路next,生成Maven專案。 2. 修改pom.xml檔案,加入jetty-maven-plugin外掛的依賴
<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>cn.marcusli.demo</groupId>
    <artifactId>helloMavenAndJetty</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>helloMavenAndJetty Maven Webapp</name>
    <url>http://maven.apache.org</url>


    <properties>
        <jettyVersion>9.3.0.M1</jettyVersion>
        <servletVersion>3.1.0</servletVersion>
    </properties>


    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servletVersion}</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>helloMavenAndJetty</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jettyVersion}</version>
            </plugin>
        </plugins>
    </build>
</project>

Intellij 檢視如下:


3. 編寫servlet類:HelloServlet.java
package cn.marcusli.example;

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


/**
 * Created by marcusli on 1/7/2015.
 */
public class HelloServlet extends HttpServlet
{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		resp.setContentType("text/html");
		resp.setStatus(HttpServletResponse.SC_OK);
		resp.getWriter().println("<h1>Hello Servlet!!!!, My Name is Marcus Li.</h1>");
		resp.getWriter().println("session=" + req.getSession(true).getId());
	}
}
4. web.xml 配置servlet
<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <servlet>
        <servlet-name>helloServlet</servlet-name>
        <servlet-class>cn.marcusli.example.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>helloServlet</servlet-name>
        <url-pattern>/hello/*</url-pattern>
    </servlet-mapping>
</web-app>
5 執行jetty-maven-plugin外掛,訪問 http://localhost:8080/hello檢視結果:




以上只是簡單的說明,很多細節並沒有講到,希望共同學習。