servlet就是一个Java类。类就会有一系列的属性和方法
Java包组成:javax.servlet和javax.servlet.http
在javax.servlet包中定义了所有的Servlet类都必须实现或扩展的的通用接口和类
在javax.servlet.http包中定义了采用HTTP通信协议的HttpServlet类.
1-1.三种创建方式
1.实现servlet接口
import javax.servlet
/**
* @author:Cherry
* @createTime:2020-12-31 9:57
*
* 要实现接口里面的方法
* - 但实际上有用的只有service方法
* 基本上不用这个方法创建
*/
public class LoginServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
j
}
}
2.继承GenericServlet抽象类
import javax.servlet.GenericServlet;
/**
* @author:Cherry
* @createTime:2020-12-31 10:01
*
* 这个创建方法也基本不用
* - 继承人抽象类只实现一个service方法
*/
public class RegisterServlet extends GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
}
}
3.继承HttpServlet抽象类
import javax.servlet.http.HttpServlet;
/**
* @author:Cherry
* @createTime:2020-12-30 20:05
*/
public class UserServlet extends HttpServlet {
private IUserService userService = new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> users = userService.showUsersInfo();
for (User user : users) {
resp.getWriter().println(user);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}