01_3_创建一个Servlet

时间:2022-09-14 21:31:49

01_3_创建一个Servlet

1.创建一个Servlet

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

//设置返回信息的内容字符集,切记位置

resp.setContentType("text/html;charset=gbk");

//处理客户端的请求

PrintWriter out = resp.getWriter();

//获取基于字符的打印流

out.println("<html><title>Hello World Servlet</title><head><body>你好hello world!!!</body></head></html>");

out.flush();

//更新缓存

out.close();

//关闭流

}

private static final long serialVersionUID = 1L;

}

2. 配置web.xml

<servlet>

<servlet-name>HelloWorldServlet</servlet-name>

<servlet-class>HelloWorldServlet</servlet-class>

<!--这里配置src全路径的servlet类路径-->

</servlet>

<servlet-mapping>

<servlet-name>HelloWorldServlet</servlet-name>

<url-pattern>/HelloWorldServlet</url-pattern>

<!--这里配置访问的时候的URL-->

</servlet-mapping>