经过上次的讲解,相信小伙伴们已经对servlet的生命周期有了不少的了解,下面我们就通过一些实例来更加深入了解一下servlet吧。
一、什么是servlet?
实例:
servlet继承于HttpServlet ,java代码如下: package com.test.action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * servlet 继承与 HttpServlet 重写 doGet() doPost()方法 * servlet可以直接返回 ,即获取PrintWriter输出流,在PrintWriter中输出字符串 * servlet也可以返回jsp,即response.sendRedirect(jspPath) * * @author * @version * @see * @since */ public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //直接返回 // resp.setContentType("text/html;charset=utf-8"); // PrintWriter pw = resp.getWriter(); // pw.println("<html><head>"); // pw.println("<title>testServlet</title>"); // pw.println("</head><body>this is a testServlet example!"); // pw.println("</body></html>"); // pw.close(); //返回jsp resp.sendRedirect("servlet.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doGet(req, resp); } }
Web.xml配置代码:
<servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>com.test.action.TestServlet</servlet-class> </servlet> <servlet - mapping > <servlet-name>TestServlet</servlet-name> <url - pattern >/testServlet</url - pattern > </servlet-mapping>
以上就是今天内容的全部介绍了,更多相关servlet常见问题快关注我们网站了解具体详情吧。
推荐阅读: