目录:
Servlet 主要作用 通过程序来生成 网页
Servlet 生命周期
读取本地工程下的文件
读取web工程发布后的文件
获得输入字符串,统计字母次数
使用ServletConfig对象 向Servlet传递初始化信息
读取 全局初始化参数
统计浏览器访问次数案例
自定义缺省Servlet
*注:web.xml配置文件在最下面,注意查看
Servlet 主要作用 通过程序来生成 网页
package cn.itcast.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet 主要作用 通过程序来生成 网页 * * 继承 HttpServlet * * 覆盖 doGet 和 doPost * * @author seawind * */ public class HelloServlet extends HttpServlet { @Override public void init() throws ServletException { } @Override public void init(ServletConfig config) throws ServletException { } @Override // 处理 HTTP GET方式请求 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("hello servlet do get ..."); // 处理中文字符集 response.setContentType("text/html;charset=utf-8"); // 生成网页 需要使用 response PrintWriter out = response.getWriter(); // 通过响应输出流 生成一个网页 out.println("<html>"); // 生成的HTML 源代码 out.println("<body>"); out.println("<h1>Hello Servlet</h1>"); out.println("当前的时间是:" + new Date().toLocaleString()); out.println("</body>"); out.println("</html>"); } @Override // 处理 HTTP POST 方式请求 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("hello servlet do post ..."); } }
Servlet 生命周期
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; /** * Servlet 生命周期 * * @author seawind * */ public class InitServlet implements Servlet { // 构造函数 public InitServlet() { System.out.println("init servlet 创建对象"); } @Override // Servlet对象销毁操作 public void destroy() { System.out.println("destroy..."); } @Override // Servlet对象初始化操作 public void init(ServletConfig config) throws ServletException { System.out.println("init..."); } @Override // Servlet对象 提供服务 public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println("service ..."); } @Override public ServletConfig getServletConfig() { return null; } @Override public String getServletInfo() { return null; } }
读取本地工程下的文件
package cn.itcast.io; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReaderTest { public static void main(String[] args) throws IOException { // 编写四个文件 路径,调用readfile方法 完成文件读取 // 读取1.txt String filename1 = "1.txt"; readfile(filename1); // 读取2.txt String filename2 = "WebRoot/2.txt"; readfile(filename2); // 读取3.txt String filename3 = "WebRoot/WEB-INF/3.txt"; readfile(filename3); // 读取4.txt String filename4 = "src/4.txt"; readfile(filename4); // 读取4.txt String filename5 = FileReaderTest.class.getResource("/4.txt").getFile(); readfile(filename5); } public static void readfile(String filename) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader( filename)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } }
读取web工程发布后的文件
package cn.itcast.servlet.contextdemo3; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 读取 1.txt 2.txt 3.txt 4.txt * * @author seawind * */ public class ReadFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 读取 1.txt (不会被发布到tomcat,没法读) // 读取 2.txt String filename1 = "/2.txt"; // 根据相对于网站根目录绝对路径 ---- 获得磁盘绝对路径 filename1 = getServletContext().getRealPath(filename1); System.out.println(filename1); readfile(filename1); // 读取3.txt String filename2 = getServletContext().getRealPath("/WEB-INF/3.txt"); readfile(filename2); // 读取4.txt String filename3 = getServletContext().getRealPath( "/WEB-INF/classes/4.txt"); readfile(filename3); // 读取4.txt 用类加载器读取 String filename4 = ReadFileServlet.class.getResource("/4.txt") .getFile(); readfile(filename4); } public static void readfile(String filename) throws IOException { BufferedReader bufferedReader = new BufferedReader(new FileReader( filename)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
获得输入字符串,统计字母次数
html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>输入字符串,统计每个字母出现次数</h1>
<form action="/day5/countletter" method="post">
请输入任意字符串 <textarea rows="5" cols="80" name="content"></textarea>
<input type="submit" value="提交" />
</form>
</body>
</html>
package cn.itcast.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; /** * 获得输入字符串,统计字母次数 * * @author seawind * */ public class CountLetterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得输入字符串 String content = request.getParameter("content"); // 转换字符串小写 content = content.toLowerCase(); // 定义存放字母出现次数 数组 int[] times = new int[26]; // 在0 位置存放 a次数,在1位置存放b次数 // 遍历字符串 for (int i = 0; i < content.length(); i++) { char c = content.charAt(i); // 判断c 必须是一个字母 if (Character.isLetter(c)) { times[c - 'a']++; } } // 将统计字母出现次数 显示在浏览器上 response.setContentType("text/html;charset=utf-8");// 设置字符串 PrintWriter out = response.getWriter(); for (int i = 0; i < times.length; i++) { int lettertimes = times[i];// 字母次数 char letter = (char) ('a' + i); out.println(letter + "字母出现了" + lettertimes + "次<br/>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
使用ServletConfig对象 向Servlet传递初始化信息
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对象 向Servlet传递初始化信息 * * @author seawind * */ public class ConfigServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得 Servlet对象 初始化信息 ServletConfig config = getServletConfig(); System.out.println(config.getInitParameter("company")); System.out.println(config.getInitParameter("address")); // 通过所有初始化参数名称 遍历 值 Enumeration<String> names = config.getInitParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); System.out.println(name + ":" + config.getInitParameter(name)); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
读取 全局初始化参数
package cn.itcast.servlet.contextdemo1; 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 seawind * */ public class ContextServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得 ServletContext对象 // ServletContext context = getServletConfig().getServletContext(); ServletContext context = getServletContext(); System.out.println(context.getInitParameter("name")); // 输出文件 MIME类型 System.out.println(context.getMimeType("1.html")); System.out.println(context.getMimeType("2.jpg")); System.out.println(context.getMimeType("3.ppt")); // 记录日志 context.log("我很好,天晴了!"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
统计浏览器访问次数案例
package cn.itcast.servlet.contextdemo2; 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; /** * 每次请求 访问Servlet,将访问次数 +1 保存ServletContext * * @author seawind * */ public class VisitServlet extends HttpServlet { @Override // 对访问次数 进行初始化 public void init() throws ServletException { ServletContext context = getServletContext(); // 保存数据 到ServletContext context.setAttribute("times", 0);// 初始化访问次数为0 } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 有了一次请求,访问次数 +1 ServletContext context = getServletContext(); // 取出访问次数 int times = (Integer) context.getAttribute("times"); times++; // 将次数 放回去 context.setAttribute("times", times); System.out.println("visitServlet 被访问了一次"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package cn.itcast.servlet.contextdemo2; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 读取Context中保存访问次数,显示浏览器页面上 * * @author seawind * */ public class ShowVisitTimesServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获得ServletContext对象 ServletContext context = getServletContext(); // 读取访问次数 int times = (Integer) context.getAttribute("times"); // 将次数显示在浏览器上 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<h1>VisitServlet被访问了的" + times + "次</h1>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
自定义缺省Servlet
package cn.itcast.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义缺省Servlet * * @author seawind * */ public class DefaultServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("缺省Servlet 获得执行..."); // 获得客户端访问资源路径 String requestURI = request.getRequestURI(); // /day5/hello.html // getContextPath ----- /day5 String path = requestURI.substring(request.getContextPath().length()); // path ---- /hello.html // 将path 转换绝对磁盘路径 String absolutePath = getServletContext().getRealPath(path); File file = new File(absolutePath); if (file.exists() && file.isFile()) { // 将文件内容返回客户端 InputStream in = new FileInputStream(file); OutputStream out = response.getOutputStream(); int b; while ((b = in.read()) != -1) { out.write(b); } in.close(); out.close(); } else { // 文件不存在,或者是一个目录 response.setStatus(404); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" 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"> <!-- 全局初始化参数 , 任何Servlet都可以读取--> <context-param> <param-name>name</param-name> <param-value>张三</param-value> </context-param> <!-- 注册Servlet 程序, 为Servlet class 起一个名字 --> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>cn.itcast.servlet.HelloServlet</servlet-class> </servlet> <servlet> <servlet-name>InitServlet</servlet-name> <servlet-class>cn.itcast.servlet.InitServlet</servlet-class> <!-- 通过 load-on-startup 让Servlet 随服务器启动 加载,完成初始化 --> <!-- 中间值 是一个数字 取值 0-9 ,代表优先级 0最高 --> <load-on-startup>0</load-on-startup> </servlet> <servlet> <servlet-name>HelloServlet2</servlet-name> <servlet-class>cn.itcast.servlet.HelloServlet2</servlet-class> </servlet> <servlet> <servlet-name>HelloServlet3</servlet-name> <servlet-class>cn.itcast.servlet.HelloServlet3</servlet-class> </servlet> <servlet> <servlet-name>ConfigServlet</servlet-name> <servlet-class>cn.itcast.servlet.ConfigServlet</servlet-class> <!-- 通过 init-param 标签 传递初始化 信息 --> <init-param> <param-name>company</param-name> <param-value>传智播客</param-value> </init-param> <init-param> <param-name>address</param-name> <param-value>春生泰克</param-value> </init-param> </servlet> <servlet> <servlet-name>ContextServlet1</servlet-name> <servlet-class>cn.itcast.servlet.contextdemo1.ContextServlet1</servlet-class> </servlet> <servlet> <servlet-name>VisitServlet</servlet-name> <servlet-class>cn.itcast.servlet.contextdemo2.VisitServlet</servlet-class> </servlet> <servlet> <servlet-name>ShowVisitTimesServlet</servlet-name> <servlet-class>cn.itcast.servlet.contextdemo2.ShowVisitTimesServlet</servlet-class> </servlet> <servlet> <servlet-name>ReadFileServlet</servlet-name> <servlet-class>cn.itcast.servlet.contextdemo3.ReadFileServlet</servlet-class> </servlet> <servlet> <servlet-name>DefaultServlet</servlet-name> <servlet-class>cn.itcast.servlet.DefaultServlet</servlet-class> </servlet> <servlet> <servlet-name>CountLetterServlet</servlet-name> <servlet-class>cn.itcast.servlet.CountLetterServlet</servlet-class> </servlet> <!-- 配置Servlet 访问 路径 --> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>InitServlet</servlet-name> <url-pattern>/init</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>HelloServlet2</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>HelloServlet3</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ConfigServlet</servlet-name> <url-pattern>/config</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ContextServlet1</servlet-name> <url-pattern>/context1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>VisitServlet</servlet-name> <url-pattern>/visit</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ShowVisitTimesServlet</servlet-name> <url-pattern>/show</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ReadFileServlet</servlet-name> <url-pattern>/readfile</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>DefaultServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CountLetterServlet</servlet-name> <url-pattern>/countletter</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>