1.maven操作过程
首先建一个空的maven项目,将src文件夹删掉,然后建一个我们自己的module文件用来写servlet。在创建的时候点击使用wepapp模板
建完module后,我们在父工程的pom文件需要配置我们需要的jar包
<dependencies>
<!-- 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>
<!-- 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>
jar包配置完成后,开始写servlet
首先在main文件夹下创建Java包和resources包
将两个包设置为源文件夹后建包,写servlet
2.servlet写法
首先servlet继承了一个httpservlet的一个类,这个类继承了GenericServlet类,GenericServlet类又实现了servlet,ServletConfig, Serializable接口。这就是servlet的整体继承关系。
在接口servlet接口中有四个方法:
void init(ServletConfig var1) throws ServletException;
//初始化servlet
ServletConfig getServletConfig();
//获取servlet配置信息
void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
//获取请求响应
String getServletInfo();
//调用销毁方法
void destroy();
继承HttpServlet类重写doGet()和doPost()方法:
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ServletInputStream inputStream = req.getInputStream();
// ServletOutputStream outputStream = resp.getOutputStream();
// BufferedReader reader = req.getReader();
PrintWriter writer = resp.getWriter();
writer.print("Hello,servlet!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
在xml文件中注册servlet并且添加servlet映射
<?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">
<!--注册servlet-->
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.gsy.HelloServlet</servlet-class>
</servlet>
<!--设置servlet映射以及响应路径-->
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
之后将项目部署到tomcat服务器上:
启动tomcat服务器即可完成!