一、什么是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 经典实战视频教程:servlet详细教程与讲解,实例开发”的内容进行的回答,希望对大家有所帮助,如有疑问,请在线咨询,有专业老师随时为你服务。
你适合学Java吗?4大专业测评方法
代码逻辑 吸收能力 技术学习能力 综合素质
先测评确定适合在学习