HelloServlet
2021-01-30 本文已影响0人
了春风
1、通过Maven创建web项目!
Snipaste_2021-01-30_12-32-06.png2、输入项目名
Snipaste_2021-01-30_12-35-13.png3、配置Maven
Snipaste_2021-01-30_12-39-37.png4、创建文件夹
Snipaste_2021-01-30_12-37-26.png5、导入Maven依赖
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
6、在Java中创建Servlet的实现类:
package com.why.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 {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//响应的类型:html
resp.setContentType("text/html");
//获取响应的输出流
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>我是导航栏</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello Servlet!</h1>");
out.println("</body>");
out.println("</html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
<!-- web.xml中是配置我们web的核心应用-->
<!-- 注册Servlet-->
<servlet>
<servlet-name>helloServlet</servlet-name>
<servlet-class>com.why.servlet.HelloServlet</servlet-class>
</servlet>
<!-- 一个Servlet对应一个Mapping:映射-->
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<!-- 请求路径-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
8、配置Tomcat
Snipaste_2021-01-30_12-55-03.png Snipaste_2021-01-30_12-57-00.png Snipaste_2021-01-30_12-59-24.png Snipaste_2021-01-30_13-00-49.png Snipaste_2021-01-30_13-01-26.pngApply → OK
9、启动Servlet
Snipaste_2021-01-30_13-03-39.png10、运行结果
Snipaste_2021-01-30_13-05-26.png Snipaste_2021-01-30_13-09-59.png