Servlet学习笔记(一)

使用Servlet所需要导入的包: java.io.*;

                                                javax.servlet.*;

                                                javax.servlet.http.*;

配置Tomcat 的web.xml文件

<web-app>
    <servlet>
        <servlet-name>HelloWorldservlet-name>
        <servlet-class>HelloWorldservlet-class>
    servlet>
     <servlet-mapping>
        <servlet-name>HelloWorldservlet-name>
        <url-pattern>/HelloWorldurl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>HelloWorldTwoservlet-name>
        <servlet-class>HelloWorldTwoservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>HelloWorldTwoservlet-name>
        <url-pattern>/HelloWorldTwourl-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("

" + name + "

"); } 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("

" + message + "

"); } public void destroy() { // 什么也不做 System.out.println("destroy"); } }

 

其中1和2两种方式实现的是service方法,第三种实现的是doGet 和 doPost

转载于:https://www.cnblogs.com/Y-X-DONG/p/11416184.html

你可能感兴趣的:(Servlet学习笔记(一))