使用servlet之前需先添加tomcat服务器:
IDEA之配置和使用Tomcat
引入依赖
在pom.xml中添加Servlet依赖包
<!-- servlet依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- servlet依赖的jar包start -->
<!-- jsp依赖jar包start -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jsp依赖jar包end -->
<!--jstl标签依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--jstl标签依赖的jar包end -->
Servlet样例
编写servlet源文件
package com.tung.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class HelloServlet extends HttpServlet {
private String message;
//初始化方法
@Override
public void init() throws ServletException {
message = "Why so serious?!";
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应内容类型
response.setContentType("text/html");
//设置逻辑实现
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
@Override
public void destroy() {
super.destroy();
}
}
部署Servlet
配置文件中部署
在webapp文档下的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>com.tung.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
注解部署
在HelloServlet前添加注解
@WebServlet("/Hello")
运行结果
启动服务器,访问对应路径,结果如下: