开发Servlet的3种方式
实现Servlet接口
- 建立web应用
web1
- 在
web1
目录下建立WEB-INF/web.xml
(web.xml可以从root
中拷贝) - 在
web1
目录下classes
和lib
文件夹 在
web1/classes
下建立MyFirstServlet.java
文件实现Servlet接口//MyFirstServlet.java package com.web1; import javax.Servlet.*; import javax.Servlet.http.*; import java.io.*; class MyFisrstServlet implements Servlet{ //该函数用于初始化Servlet,就是把该Servlet装载到内存中,且只被调用一次 public void init(ServletConfig config) throws ServletException{ } //得到Servletconfig对象 public ServletConfig getServletConfig(){ return null; } //该函数是服务函数,我们的业务逻辑代码写在这里 //该函数每次都会被调用 public void service(ServletRequest req,ServletResponse res) throws ServletException,java.io.IOException{ } //该函数得到Servlet配置信息 public java.lang.String getServletInfo(){ return null; } //销毁该Servlet,从内存中清楚,且只被调用一次 public void destroy(){ } }
- 用javac编译,对打包文件应使用命令
javac -d . 文件名
根据Servlet规范部署到
web.xml
文件<?xml version="1.0" encoding="ISO-8859-1"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <web-app 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" version="2.5"> <Servlet> <!--Servlet-name 该名字可以自己定义,也使用该Servlet的名字 --> <Servlet-name>MyFirstServlet</Servlet-name> <!--Servlet-class 要指明该Servlet放在哪个包下面的,形式是包.包.类,类名不加java,eg->com.web1.MyFirstServlet --> <Servlet-class><com.web1.MyFirstServlet</Servlet-class> </Servlet> <!--selverlet-mapping是用来做映射的--> <Servlet-mapping> <!--Servlet-name 这个Servlet名字要和上面的Servlet名字相同 --> <Servlet-name>MyFirstServlet</Servlet-name> <!--url-pattern 是将来访问Servlet的资源名,默认命名为该Servlet的名字 --> <url-pattern>/web1</url-pattern> </Servlet-mapping> </web-app>
一堆bug
- 其他问题如何不重启tomcat,但可以reload一个应用,进入tomcat的manager,
localhost:8080
,点击reload
- 其他问题如何不重启tomcat,但可以reload一个应用,进入tomcat的manager,
- 建立web应用
- 继承GenericServlet
了解即可,只有service
函数需要重写 - 继承HttpServlet
通过继承HttpServlet方法需要重写doGet()
和doPost()
方法
区别是:
安全性:get<post,即get提交的数据会在浏览器地址栏显示
内容大小:get<post,get不能大于2k,post理论不设限
响应速度:get>post,get要求立即处理,post可能会形成请求队列
Servlet的生命周期
- 当Servlet第一被调用时会触发
init
函数,该函数会把Servlet实例加载到内存中,且init函数只会被调用一次 - 然后去调用Servlet 的
service
函数 - 当第二次访问就直接调用
service
函数 - 当web应用relaod或者关闭,都会去调用relaod函数,该函数会销毁