1.什么是servlet?
1 、 Servlet 是 JavaEE 规范之一。规范就是接口2 、 Servlet 就 JavaWeb 三大组件之一。三大组件分别是: Servlet 程序、 Filter 过滤器、 Listener 监听器。3 、 Servlet 是运行在服务器上的一个 java 小程序, 它可以接收客户端发送过来的请求,并响应数据给客户端。
2. 如何实现servlet程序?
1 、编写一个类去实现 Servlet 接口2 、实现 service 方法,处理请求,并响应数据3 、到 web.xml 中去配置 servlet 程序的访问地址
Servlet 程序的示例代码:
package com.ning.servlet;
import javax.servlet.*;
import java.io.IOException;
public class Hello implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service被执行了~");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
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">
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>com.ning.servlet.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
运行程序,在浏览器中访问http://localhost:8080/hello ,控制台打印:
3.如何访问servlet程序?
4.get和post请求处理
public class Hello implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init~");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("service被执行了~");
//HttpServletRequest有getMethod()方法,才能分辨出get、post请求
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String method = httpServletRequest.getMethod();
if ("GET".equals(method))
System.out.println("是GET请求");
else if ("POST".equals(method))
System.out.println("是POST请求");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("destroy~");
}
}
输出:
5.通过继承 HttpServlet 实现 Servlet 程序
一般在实际项目开发中,都是使用继承 HttpServlet 类的方式去实现 Servlet 程序。①编写一个类去继承 HttpServlet 类②根据业务需要重写 doGet 或 doPost 方法③到 web.xml 中的配置 Servlet 程序的访问地址
public class Hello1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet~");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost~");
}
}
<servlet>
<servlet-name>Hello1</servlet-name>
<servlet-class>com.ning.servlet.Hello1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello1</servlet-name>
<url-pattern>/hello1</url-pattern>
</servlet-mapping>