Servlet的两种创建方法
我们所说servlet是一种运行在服务器端的扩展程序,继承自javax.servlet.http.HttpServlet。HttpServlet继承GenericServlet,GenericServlet实现了
Servlet, ServletConfig, Serializable这三个接口。它的作用是处理客户端发送的请求。
访问方法:http://主机名:端口号/servlet名称 这里说servlet名称是不准确的,应该说是servlet名称的映射名称或者是urlPatterns
例如:http://localhost:8080/hehe 即可访问该servlet
1.常规方法
(1)创建一个类,继承javax.servlet.http.HttpServlet,重写doPost,doGet等方法
package com.test.hehe;
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 Haha extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("hahaha");
}
}
(2)在项目的/web/WEB-INF/目录下,打开web.xml,在<web-app> 这里是内部 </web-app>的内部加入如下几行:
<servlet>
<display-name>Haha</display-name>
<servlet-name>Haha</servlet-name>
<servlet-class>com.test.hehe.Haha</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Haha</servlet-name>
<url-pattern>/hahaha</url-pattern>
</servlet-mapping>
在浏览器中输入http://localhost:8080/hahaha就可以看见结果了(前提是,你已经启动了服务器,并且该项目已经在服务器中跑了,端口号是8080,主机名是localhost)。
2.注解
这个创建sevrlet很简单,但是在较低的版本中不支持,废话不多说,看代码:
package com.test.hehe; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet(name="hehe",urlPatterns="/hehe") public class SayHehe extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().println("hehe"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}}resp.getWriter().println("hehe");
一定要 importjavax.servlet.annotation.WebServlet;并在顶部写:@WebServlet(name="hehe",urlPatterns="/hehe")
http://localhost:8080/hehe 就可以看到效果了