package cn.itcast;
import java.io.*;
import javax.servlet.*;
public class FirstServlet extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws ServletException,java.io.IOException
{
String data = "hello servlet!!";
OutputStream out = res.getOutputStream();
out.write(data.getBytes());
}
}
2) 进入到classes目录,编译FirstServlet
FirstServlet
cn.itcast.FirstServlet
FirstServlet
/xxx
4)启动服务器 在IE输入 http://localhost:80/day04/xxx
package cn.itcast.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* 生命周期
* @author Administrator
*
*/
public class ServletDemo2 implements Servlet {
/**
* Servlet实例被创建后,调用init方法进行初始化
* Servlet什么时候被创建呢?
* * 不是服务器一启动时,实例被创建,第一次访问的时候,实例才被创建。
* init方法调用几次呢?
* * 只被调用一次。
*/
public void init(ServletConfig config) throws ServletException {
System.out.println("init...");
}
/**
* service调用几次呢?
* * 有一次请求,调用一次service方法
*/
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
System.out.println("service...");
}
/**
* Servlet实例什么时候被销毁呢?
* * 服务器关闭,手动移除。
* destroy调用几次呢?
* * 一次
*/
public void destroy() {
System.out.println("destroy...");
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
}
配置web.xml
ServletDemo2
cn.itcast.servlet.ServletDemo2
ServletDemo2
/demo2
public class ServlerDemo3 extends GenericServlet {
public void init(ServletConfig config) throws ServletException {
}
public void init() throws ServletException {
}
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
}
}
点击CRTL 查看如下:进入GenericServlet的类中init方法的实现:
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
}
public abstract void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
可以看到GenericServlet是不直接实现service方法的,而是交给子类去实现的
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
HttpServletRequest request;
HttpServletResponse response;
try {
request = (HttpServletRequest) req;
response = (HttpServletResponse) res;
} catch (ClassCastException e) {
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String method = req.getMethod();
if (method.equals(METHOD_GET)) {
long lastModified = getLastModified(req);
if (lastModified == -1) {
// servlet doesn't support if-modified-since, no reason
// to go through further expensive logic
doGet(req, resp);
} else {
long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
if (ifModifiedSince < (lastModified / 1000 * 1000)) {
// If the servlet mod time is later, call doGet()
// Round down to the nearest second for a proper compare
// A ifModifiedSince of -1 will always be less
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
} else if (method.equals(METHOD_HEAD)) {
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else if (method.equals(METHOD_POST)) {
doPost(req, resp);
} else if (method.equals(METHOD_PUT)) {
doPut(req, resp);
} else if (method.equals(METHOD_DELETE)) {
doDelete(req, resp);
} else if (method.equals(METHOD_OPTIONS)) {
doOptions(req,resp);
} else if (method.equals(METHOD_TRACE)) {
doTrace(req,resp);
} else {
//
// Note that this means NO servlet supports whatever
// method was requested, anywhere on this server.
//
String errMsg = lStrings.getString("http.method_not_implemented");
Object[] errArgs = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
}
}
可以看出真正实现Service方法的是HttpServlet类,而在HttpServlet中service方法会根据请求方式调用对应的doXXX
修改Servlet模板
- 先找到MyEclipse的安装路径。
- \myeclipse10.7\Common\plugins\com.genuitec.eclipse.wizards.xxxx.jar
- 我自己的:com.genuitec.eclipse.wizards_9.0.0.me201211011550.jar
- 千万别解压,右键--选择压缩工具打开--templates--Servlet.java 拖到桌面进行编辑保存成所需要的模板格式
- 拖回去之前,先MyEclipse关闭。
配置Servlet自动加载
Servlet默认是在第一次访问的时候创建实例。通过配置,服务器启动,创建实例。
init()方法做初始化的操作,是非常耗费时间的,因此可以配置在服务器启动的时候创建实例。
如果在如果在元素中配置了一个元素,那么WEB应用程序在启动时,就会装载并创建Servlet的实例对象、以及调用Servlet实例对象的init()方法。
配置方法:在标签下添加
值是正整数:如果值越小,优先级越高。
package cn.itcast.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 配置servlet启动时加载
* @author Administrator
*
*/
public class ServletDemo5 extends HttpServlet {
/**
* 默认的情况下第一次访问的时候init被调用。
*
*/
public void init() throws ServletException {
System.out.println("init...");
// 初始化数据库的链接
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 写的内容
// 获取表单输入的内容
// 自己逻辑,通过名称查询数据库,把张三的姓名查到了
// 把张三返回浏览器
System.out.println("doGet...");
// 向页面输出内容
response.getWriter().write("hello demo5...");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
在web.xml中添加代码如下:
ServletDemo5
cn.itcast.servlet.ServletDemo5
3
ServletDemo5
/demo5
AnyName
HelloServlet
AnyName
/demo/hello.html
·
路径分为相对路径和绝对路径两种写法
(1). 相对路径,根据当前资源路径 与 目标资源路径,寻找相对位置关系,通过 . (当前目录) 和 .. (上一级目录) 访问目标资源
1.html 访问 HelloServlet
当前路径 http://localhost/day5/1.html
目标路径 http://localhost/day5/hello
位于同一个目录中 ./hello 、hello ===== 替换当前路径最后一个资源
2.html 访问 HelloServlet
当前路径 http://localhost/day5/aa/2.html
目标路径 http://localhost/day5/hello
上一级目录中 ../hello ===== 替换上一级目录资源
相对路径,总需要分析当前路径与目标路径对应关系,编写规则会根据当前路径不同而不同
(2)绝对路径
带有协议完整路径 (跨网站) http://localhost/day5/hello
以/ 开始路径 (同一个站点内) : /day5/hello
服务器端和客户端对于/ 的区别
客户端访问路径:/day5/hello
服务器内部路径:/hello
结论:web访问中所有资源路径,都使用绝对路径
package cn.itcast.servlet;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ServletConfig对象
* @author Administrator
*
*/
public class ServletDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 测试ServletConfig对象的api
// 先获取ServletConfig对象
ServletConfig config = getServletConfig();
// 获取配置文件中serlvet的名称
System.out.println("servlet的名称:"+config.getServletName());
// 获取初始化的参数
String username = config.getInitParameter("username");
String password = config.getInitParameter("password");
System.out.println(username+" : "+password);
Enumeration e = config.getInitParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
String value = config.getInitParameter(name);
System.out.println(name+" : "+value);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在web.xml中添加如下内容:
ServletDemo6
cn.itcast.servlet.ServletDemo6
username
root
password
123
ServletDemo6
/demo6
运行结果如下:
package cn.itcast.context;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 获取全局初始化参数
* @author Administrator
*
*/
public class ContextDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 先获取ServletContext对象
ServletContext context = getServletContext();
// 获取初始化参数
String encoding = context.getInitParameter("encoding");
System.out.println("编码:"+encoding);
Enumeration e = context.getInitParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
// 通过name获取值
String value = context.getInitParameter(name);
System.out.println(name+" : "+value);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在web.xml中添加配置信息
package cn.itcast.context;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取资源文件
* @author Administrator
*
*/
public class ReadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
read5();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* 通过ServletContext对象获取文件的绝对磁盘路径
* 获取src目录下文件
* @throws IOException
*/
public void read5() throws IOException{
// 获取对象
String path = getServletContext().getRealPath("/WEB-INF/classes/db.properties");
// System.out.println(path);
// C:\apache-tomcat-6.0.14\webapps\day09\WEB-INF\classes\db.properties
// 获取输入流
InputStream in = new FileInputStream(path);
print(in);
}
/**
* 获取WebRoot目录目录下db.properties文件
* @throws IOException
*/
public void read4() throws IOException{
// ServletContext读取文件
InputStream in = getServletContext().getResourceAsStream("/db.properties");
// 打印方式
print(in);
}
/**
* 获取包目录下db.properties文件
* @throws IOException
*/
public void read3() throws IOException{
// ServletContext读取文件
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/cn/itcast/context/db.properties");
// 打印方式
print(in);
}
/**
* 获取src目录下db.properties文件
* @throws IOException
*/
public void read2() throws IOException{
// ServletContext读取文件
InputStream in = getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
// 打印方式
print(in);
}
/**
* 传统方式读取资源文件
* 交给服务器处理,相对的位置tomcat/bin
* @throws IOException
*/
public void read1() throws IOException{
// 获取输入流
InputStream in = new FileInputStream("src/db.properties");
print(in);
}
/**
* 在控制台打印内容
* @param in
* @throws IOException
*/
public void print(InputStream in) throws IOException{
Properties pro = new Properties();
// 加载
pro.load(in);
// 获取文件中的内容
String username = pro.getProperty("username");
String password = pro.getProperty("password");
String desc = pro.getProperty("desc");
System.out.println("用户名:"+username);
System.out.println("密码:"+password);
System.out.println("描述:"+desc);
}
}
package cn.itcast.context;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 统计网站的访问次数
* @author Administrator
*
*/
public class CountServlet extends HttpServlet {
/**
* 实例被创建,调用init方法进行初始化
* 在域对象存入一个变量,赋值为0
*/
public void init() throws ServletException {
// 获取ServletContext对象
getServletContext().setAttribute("count", 0);
}
/**
* 每一次访问,都会执行该方法。
* 拿出count的变量,值自增,存入到域对象中
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 先获取ServletContext对象
ServletContext context = getServletContext();
// 获取count的值,自增
Integer count = (Integer) context.getAttribute("count");
// 存入到域对象中
context.setAttribute("count", ++count);
// 向页面输出内容
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("大爷,欢迎再来哦!!
");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
ShowServlet.java如下:
package cn.itcast.context;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 显示网站的访问次数
* @author Administrator
*
*/
public class ShowServlet extends HttpServlet {
/**
* 获取网站的访问次数,输出到客户端
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Integer count = (Integer) getServletContext().getAttribute("count");
// 向页面输出
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("该网站一共被访问了"+count+"次
");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
在web.xml中添加如下配置:
CountServlet
cn.itcast.context.CountServlet
ShowServlet
cn.itcast.context.ShowServlet
CountServlet
/count
ShowServlet
/show
package cn.itcast.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 页面定时跳转
* @author Administrator
*
*/
public class RefreshServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("访问到了...");
// 页面5秒会跳转
response.setHeader("refresh", "5;url=/day09/1.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
package cn.itcast.http;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 和location和302一起完成重定向
* @author Administrator
*
*/
public class ServletDmo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 向页面输出内容
response.setContentType("text/html;charset=UTF-8");
// response.getWriter().write("向班长借钱...");
// 我没钱
response.setStatus(302);
// 告诉我富班长的地址
response.setHeader("location", "/day09/1.html");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}