3.3.1实现Servlet
FirstServlet.java
package com.helloweenvsfei.servlet; 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; public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ this.log("执行doGet方法..."); this.execute(request,response); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ this.log("执行doPost方法..."); this.execute(request,response); } @Override public long getLastModified(HttpServletRequest request){ this.log("执行getLastModified方法"); return -1; } private void execute(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); String requestURI=request.getRequestURI(); String method=request.getMethod(); String param=request.getParameter("param"); response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println("<HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println("<BODY>"); out.println("以"+method+"方式访问该页面。取到的param参数为:"+param+"<br/>"); out.println("<form action='"+requestURI+"'method='get'><input type='text'name='param'value='param string'><input type='submit'value='以GET方式查询页面"+requestURI+"'></form>"); out.println("<form action='"+requestURI+"'method='post'><input type='text'name='param'value='param string'><input type='submit'value='以POST方式查询页面"+requestURI+"'></form>"); out.println("<script>document.write('本页面最后更新时间:'+document.lastModified);</script>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name> FirstServlet</servlet-name> <servlet-class>com.helloweenvsfei.servlet.FirstServlet</servlet-class> <init-param> <param-name>message</param-name> <param-value>welcome to FirstServlet</param-value> </init-param> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/servlet/FirstServlet</url-pattern> <url-pattern>/servlet/FirstServlet.asp</url-pattern> <url-pattern>/servlet/FirstServlet.php</url-pattern> <url-pattern>/servlet/FirstServlet.jsp</url-pattern> <url-pattern>/servlet/FirstServlet.aspx</url-pattern> </servlet-mapping> </web-app>