Servlet学习笔记(一)
使用Servlet所需要导入的包: java.io.*;
javax.servlet.*;
javax.servlet.http.*;
配置Tomcat 的web.xml文件
<web-app> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> <servlet> <servlet-name>HelloWorldTwo</servlet-name> <servlet-class>HelloWorldTwo</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorldTwo</servlet-name> <url-pattern>/HelloWorldTwo</url-pattern> </servlet-mapping> </web-app>
Servlet创建的三种方式:
1.实现Servlet接口
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorldTwo implements Servlet{ private String message; public void init( ServletConfig arg0) throws ServletException{ System.out.println("初始化init"); message="我是实现接口Servlet的HelloWorld"; } public void service(ServletRequest request, ServletResponse response) throws ServletException ,IOException{ System.out.println("service"); request.setCharacterEncoding("UTF-8"); String name= request.getParameter("name"); // 设置响应内容类型 response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); // 实际的逻辑是在这里 PrintWriter out = response.getWriter(); out.println("<h1>" + name + "</h1>"); } public void destroy(){ System.out.println("*******destory******"); } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } }
2.继承GenericService类
3.继承HttpServlet类
// 导入必需的 java 库 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // 扩展 HttpServlet 类 public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { System.out.println("初始化init"); // 执行必需的初始化 message = "我是继承HttpServlet的HelloWorld"; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); // 设置响应内容类型 response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); // 实际的逻辑是在这里 PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // 什么也不做 System.out.println("destroy"); } }
其中1和2两种方式实现的是service方法,第三种实现的是doGet 和 doPost