servlet
HttpServlet
创建javaweb项目关联tomcat安装目录
java项目目录
JAVA存放目录:SRC
WEB文件目录:WebContent
WEB配置文件:web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>javaweb</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> <load-on-startup>10</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloSevlet</url-pattern> </servlet-mapping> <servlet> <!-- servlet的内部名称,自定义。尽量有意义 --> <servlet-name>ServletDemo</servlet-name> <!-- servlet的类全名: 包名+简单类名 --> <servlet-class>servlet.ServletDemo</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! --> <servlet-name>ServletDemo</servlet-name> <!-- servlet的映射路径(访问servlet的名称) --> <url-pattern>/servlet/ServletDemo</url-pattern> </servlet-mapping> </web-app> |
welcome-file-list:当用户在浏览器中输入的URL不包含某个servlet名或JSP页面时,welcome-file-list元素可指定显示的默认文件。
javax.servlet.http.HttpServlet方法
• doPost, for HTTP POST requests
• doPut, for HTTP PUT requests
• doDelete, for HTTP DELETE requests
• init and destroy,to manage resources that are held for the life of the servlet
• getServletInfo, which the servlet uses toprovide information about itself
创建一个继承HttpServlet的类
package 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 HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter writer= resp.getWriter(); resp.setContentType("text/html;charset=GBK"); writer.println("<strong>Hello,222222</strong>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("处理post请求"); } } |
web.xml配置servlet
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloSevlet</url-pattern> </servlet-mapping> |
编译前自动保存
servlet执行流程
servlet生命周期
servlet与jsp九大内置对象