servlet就是一个Java类。类就会有一系列的属性和方法
Java包组成:javax.servlet和javax.servlet.http
在javax.servlet包中定义了所有的Servlet类都必须实现或扩展的的通用接口和类
在javax.servlet.http包中定义了采用HTTP通信协议的HttpServlet类.

1-1.三种创建方式

1.实现servlet接口

import javax.servlet

  1. /**
  2. * @author:Cherry
  3. * @createTime:2020-12-31 9:57
  4. *
  5. * 要实现接口里面的方法
  6. * - 但实际上有用的只有service方法
  7. * 基本上不用这个方法创建
  8. */
  9. public class LoginServlet implements Servlet {
  10. @Override
  11. public void init(ServletConfig servletConfig) throws ServletException {
  12. }
  13. @Override
  14. public ServletConfig getServletConfig() {
  15. return null;
  16. }
  17. @Override
  18. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  19. }
  20. @Override
  21. public String getServletInfo() {
  22. return null;
  23. }
  24. @Override
  25. public void destroy() {
  26. j
  27. }
  28. }

2.继承GenericServlet抽象类

import javax.servlet.GenericServlet;

  1. /**
  2. * @author:Cherry
  3. * @createTime:2020-12-31 10:01
  4. *
  5. * 这个创建方法也基本不用
  6. * - 继承人抽象类只实现一个service方法
  7. */
  8. public class RegisterServlet extends GenericServlet {
  9. @Override
  10. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  11. }
  12. }


3.继承HttpServlet抽象类

import javax.servlet.http.HttpServlet;

  1. /**
  2. * @author:Cherry
  3. * @createTime:2020-12-30 20:05
  4. */
  5. public class UserServlet extends HttpServlet {
  6. private IUserService userService = new UserServiceImpl();
  7. @Override
  8. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  9. List<User> users = userService.showUsersInfo();
  10. for (User user : users) {
  11. resp.getWriter().println(user);
  12. }
  13. }
  14. @Override
  15. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  16. doGet(req, resp);
  17. }
  18. }