Servlet入門(第一個Servlet的Web程式)
新建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"?>
<project
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>
<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上
執行結果如下