新建ServletDemo实现类
/*
* 实现Servlet的三种方法
* 1实现Servlet接口
* 缺点:必须实现所有方法
* */
public class ServletDemo 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 {
servletResponse.setContentType("text/html;charset=utf-8");
servletResponse.getWriter().write("<h1>hello<h1>");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
配置web.xml
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>servletDemo</servlet-name>
<servlet-class>com.by.servlet.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletDemo</servlet-name>
<url-pattern>/servletDemo</url-pattern>
</servlet-mapping>
输出结果
?
新建GenericServlet类
/*
* 实现Servlet的三种方法
* 2继承GenericServlet抽象类
* 优点:只用重写service方法
* */
public class GenericServlet extends javax.servlet.GenericServlet {
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
servletResponse.setContentType("text/html;charset=utf-8");
servletResponse.getWriter().append("我是第二种创建Servlet的方法");
}
}
?配置web.xml
<servlet>
<servlet-name>genericServlet</servlet-name>
<servlet-class>com.by.servlet.GenericServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>genericServlet</servlet-name>
<url-pattern>/genericServlet</url-pattern>
</servlet-mapping>
?输出结果
新建HttpServletDemo类
/*
* 实现Servlet的三种方法
* 3 继承HttpServlet抽象类
1.可以减少对其他方法的要求 init destroy
2.可以根据前端的要求进行分门别类 doGet doPost
* */
public class HttpServletDemo extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("我是HttpServlet创建的Servlet");
}
}
配置web.xml
<servlet>
<servlet-name>httpServlet</servlet-name>
<servlet-class>com.by.servlet.HttpServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>httpServlet</servlet-name>
<url-pattern>/httpServlet</url-pattern>
</servlet-mapping>
?输出结果