Servlet简单实例:
1.引入依赖包:
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency>
2.配置web.xml
<servlet> <!--设置servlet的名字--> <servlet-name>hello</servlet-name> <!--具体的servlet的类--> <servlet-class>com.servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <!--指定要映射的servlet的名字--> <servlet-name>hello</servlet-name> <!--servlet的具体路径--> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>http</servlet-name> <servlet-class>com.servlet.HttpServletTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>http</servlet-name> <url-pattern>/http</url-pattern> </servlet-mapping>
3.创建代码:
package com.servlet; import javax.servlet.*; import java.io.IOException; public class TestServlet implements Servlet { /* 当servlet被创建时调用。做初始化工作 仅第一次被访问时调用(可以改的) */ public void init(ServletConfig config) throws ServletException { System.out.println("servlet组件初始化。。。"); } /* servlet的配置对象,初始化的时候可以进行配置 */ public ServletConfig getServletConfig() { System.out.println("getServletConfig方法调用。。。"); return null; } @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println("service处理请求。。。"); res.getOutputStream().write("<font color='red'>HelloServlet</font>".getBytes()); } /* 获取当前servlet一些属性信息 */ public String getServletInfo() { System.out.println("getServletInfo方法调用。。。"); return null; } /* 销毁时被调用 */ public void destroy() { System.out.println("destroy销毁实例。。。"); } }
4.创建代码:
package com.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class HttpServletTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet方法调用了"); resp.getOutputStream().write("doGet方法调用了".getBytes()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost方法调用了"); doGet(req, resp); } }