什么是servlet
是一个java小程序,在服务器上运行,
实现servlet
- 编写一个类去实现servlet接口
public class HelloServlet implements Servlet{}
- 实现service方法,处理请求,并响应数据
//service方法专门用来处理请求和响应的
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("hello servlet again 5555");
}
- 到web.xml去配置servlet访问地址
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.jd.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
- 用tomcat运行web工程,即可访问地址
http://localhost:8080/06_servlet/hello
Servlet生命周期
- 构造器
- init初始化
- 执行service
- 执行销毁destroy方法
package com.jd.servlet;
import javax.servlet.*;
import java.io.IOException;
public class HelloServlet implements Servlet {
public HelloServlet(){
System.out.println("1 构造器");
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("2 初始化");
}
@Override
public ServletConfig getServletConfig() {
return null;
}
//service方法专门用来处理请求和响应的
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("3 访问service方法");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
System.out.println("4 销毁方法destroy");
}
}
get 和 post 处理
// get
public void doGET(){
System.out.println("GET request");
System.out.println("GET request");
System.out.println("GET request");
}
public void doPOST(){
System.out.println("POST request");
System.out.println("POST request");
System.out.println("POST request");
}
继承HttpServlet来实现Servlet程序
package com.example.Demo1;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
@WebServlet(name = "helloServlet", value = "/hello-servlet")
public class HelloServlet extends HttpServlet {
private String message;
public void init() {
message = "Hello World!";
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
// Hello
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>" + message + "</h1>");
out.println("</body></html>");
}
public void destroy() {
}
}
HttpServletRequest类
作用:tomcat把请求封装到Request对象中,传递到service方法(doGet,doPost)中使用,所以可以通过HttpServletRequest来获取请求信息
常用方法:
req.getRequestURI();
req.getRequestURL();
req.getRemoteAddr();
req.getHeader();
req.getMethod();
req.getAttribute();
req.setAttribute();
req.getRequestDispatcher(); //获取请求转发对象
获取参数
req.getParameter("name");
req.getParameterValues("students"); 多个值,比如列表
doPost方法要设置编码,否则中文乱码
req.setCharacterEncoding("UTF-8");
HttpServletReponse
//浏览器中文乱码设置UTF-8
resp.setContentType("text/html;charset=UTF-8");
或者
resp.setHeader("Content-Type","text/html;charset=UTF-8");
响应字节
PrintWriter writer = resp.getWriter();
writer.write("你好");