java之servlet

实现servlet的两种方式
  1. 继承HttpServlet

    继承的方式一般会使用模板模式

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CommentServlet")
public class CommentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = (String) request.getAttribute("username");
        String comments = (String) request.getAttribute("comment");
        //System.out.println(username);
        //System.out.println(comments);
        request.getRequestDispatcher("commentResult.jsp").forward(request,response);
    }
}

2. 实现接口Servlet

   接口中的所有方法都必须实现,不管你用不用

public class DemoServlet implements Servlet {
   ......
}

 

java之servlet_第1张图片

java之servlet_第2张图片

你可能感兴趣的:(java的一亩三分地)