HttpServlet深入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet extends HttpServlet { public void init() { } public void init(ServletConfig sc) { this.sc = sc; this.init(); } public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { …………………… } }
|
在webapp
下建立子文件夹(如first
),first
下建立WEB-INF
文件夹(在旧标准中是必须的,新标准已改为非必须),WEB-INF
下有lib
和classes
文件夹,以及文件web.xml
(此为配置文件)
以下是web.xml
文件大概的样子。它一般在webapp/ROOT/WEB-INF
文件夹下。
1 2 3 4 5 6 7 8 9
| <?xml version="1.0" encoding="UTF-8"?> <web-app metadata-complete="true" version="3.1" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee"> <display-name>Welcome to Tomcat</display-name> <description> Welcome to Tomcat </description> </web-app>
|
注意,XML
文件的根元素只有一个。
关于XML
的其它知识:
我们重点关注servlet
相关的部分:
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> <servlet> <servlet-name>al</servlet-name> <servlet-class>HelloServlet</servlet-class> <init-param> <param-name>port</param-name> <param-value>8081</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>al</servlet-name> <url-pattern>/hello.html</url-pattern> </servlet-mapping> </web-app>
|
该文件的具体含义,可以参考:菜鸟教程-web.xml文件详解
Servlet
的部署方式:
一,拷到webapp下
二,config/server里Host标签下这样修改:
1
| <Context path="/xyz" docBase="c:\abc" />
|
然后爱放哪儿放哪儿
三,如果用 eclipseforJavaEE 等IDE,就没那么麻烦了。其中 eclipseforJavaEE 在新建工程的配置向导中会帮你设置好servlet-name
, init-param
, servlet-mapping
等。
替代web.xml
的方式:java config