新建maven项目,注意项目的类型
工程名为ServletExample
点击Finish,建立maven项目完成如下
生成后的目录没有java源码目录,按照maven的约定,还要新建src/main/java的源码目录。选中项目,点击鼠标右键
不知道为什么,新建src/main/java目录时,eclipse报这个目录已经存在。没办法,先建立src/main/java2,然后再重构为src/main/java
配置maven的构建文件pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<projectxmlns="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.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<name>ServletExample</name>
<groupId>com.ydoing</groupId>
<artifactId>ServletExample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
</project>
更新maven项目
新增HelloServlet
代码如下,该类核心代码是doGet,作用是向客户端返回“Hello, world!”
package com.ydoing.helloapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servletimplementation class HelloServlet
*/
publicclassHelloServletextendsHttpServlet{
privatestaticfinallongserialVersionUID
=1L;
/**
* @see HttpServlet#HttpServlet()
*/
publicHelloServlet(){
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequestrequest, HttpServletResponse response)
*/
protectedvoid doGet(HttpServletRequest
request,HttpServletResponse response)throwsServletException,IOException{
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out
= response.getWriter();
String msg
="Hello, world!";
out.println("<h1>"+
msg +"</h1>");
}
/**
* @see HttpServlet#doPost(HttpServletRequestrequest, HttpServletResponse response)
*/
protectedvoid doPost(HttpServletRequest
request,HttpServletResponse response)throwsServletException,IOException{
// TODO Auto-generated method stub
}
}
修改web.xml文件。作用是将URI映射到指定的Servlet上
<?xml version="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"version="3.0">
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.ydoing.helloapp.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
运行在Tomcat上
运行结果如下