1。新建一个空maven项目,删掉src文件夹。
2.在pom.xml里建中加入依赖关系
<dependencies> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 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> </dependencies>
3.建立子项目
4. Maven环境优化
- web子项目的web.xml替换以下代码(来自tomcat的webapp)
<?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-app>
- 将maven的结构搭建完整,新建java,resources 文件夹并标记。
5编写一个servlet程序。
编写一个普通类,实现servlet接口,这里我们直接继承HttpServlet
package com.yin.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 { //GET和PUT只是请求实现的不同方式,业务逻辑都一样,可以互相调用 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getInputStream(); PrintWriter writer=resp.getWriter();//响应流 writer.println("Hello YinSong!"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
6.编写Servlet的映射,web.xml添加以下代码
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.yin.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>
7.配置Tomcat
标签:初始化,resp,req,import,servlet,javax,HelloServlet From: https://www.cnblogs.com/insoon/p/17044734.html