介绍
Servlet
是用Java
编写的服务器端程序。
其主要功能在于交互式地浏览和修改数据,生成动态Web
内容。
狭义的Servlet
是指Java
语言实现的一个接口,广义的Servlet
是指任何实现了这个Servlet
接口的类,
一般情况下,人们将Servlet
理解为后者。
使用
- 实现
javax.servlet.Servlet
接口
- 继承
javax.servlet.GenericServlet
抽象类(实现了Servlet
接口)
- 继承
javax.servlet.http.HttpServlet
类(继承自GenericServlet
类)(推荐)
先写一个类继承自HttpServlet
1 2 3 4 5 6 7 8 9 10 11
| public class Person extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
|
并在web.xml
中配置Servlet
,对应在ServletConfig
类中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>myServlet</servlet-name> <servlet-class>com.ahao.javaeeDemo.MyServlet</servlet-class> <load-on-startup>0</load-on-startup> <init-param> <param-name>myParam</param-name> <param-value>第一个参数</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/myServlet</url-pattern> </servlet-mapping> </web-app>
|
web.xml介绍
所有项目的web.xml
都有一个父的web.xml
,位于Tomcat/conf/web.xml
其中有两个默认的Servlet
default
:解析/
的url
地址,即所有servlet
都不匹配时,执行default
,返回404
等各种错误
jsp
:解析jsp
后缀的url
地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>default</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <servlet-name>jsp</servlet-name> <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class> <init-param> <param-name>fork</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>xpoweredBy</param-name> <param-value>false</param-value> </init-param> <load-on-startup>3</load-on-startup> </servlet> <servlet-mapping> <servlet-name>jsp</servlet-name> <url-pattern>*.jsp</url-pattern> <url-pattern>*.jspx</url-pattern> </servlet-mapping> </web-app>
|