博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet 2 生命周期 ServletConfig 自定义缺省Servlet
阅读量:5059 次
发布时间:2019-06-12

本文共 16078 字,大约阅读时间需要 53 分钟。

目录:

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 源代码        out.println("");        out.println("

Hello Servlet

"); out.println("当前的时间是:" + new Date().toLocaleString()); out.println(""); out.println(""); } @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

Insert title here

输入字符串,统计每个字母出现次数

请输入任意字符串
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 + "次
"); } } 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
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("

VisitServlet被访问了的" + times + "次

"); } 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

name
张三
HelloServlet
cn.itcast.servlet.HelloServlet
InitServlet
cn.itcast.servlet.InitServlet
0
HelloServlet2
cn.itcast.servlet.HelloServlet2
HelloServlet3
cn.itcast.servlet.HelloServlet3
ConfigServlet
cn.itcast.servlet.ConfigServlet
company
传智播客
address
春生泰克
ContextServlet1
cn.itcast.servlet.contextdemo1.ContextServlet1
VisitServlet
cn.itcast.servlet.contextdemo2.VisitServlet
ShowVisitTimesServlet
cn.itcast.servlet.contextdemo2.ShowVisitTimesServlet
ReadFileServlet
cn.itcast.servlet.contextdemo3.ReadFileServlet
DefaultServlet
cn.itcast.servlet.DefaultServlet
CountLetterServlet
cn.itcast.servlet.CountLetterServlet
HelloServlet
/hello
InitServlet
/init
HelloServlet2
/hello2
HelloServlet3
/hello3
ConfigServlet
/config
ContextServlet1
/context1
VisitServlet
/visit
ShowVisitTimesServlet
/show
ReadFileServlet
/readfile
DefaultServlet
/
CountLetterServlet
/countletter
index.jsp

 

转载于:https://www.cnblogs.com/vaer/p/3925112.html

你可能感兴趣的文章
201521123024 《java程序设计》 第12周学习总结
查看>>
贪吃蛇游戏改进
查看>>
新作《ASP.NET MVC 5框架揭秘》正式出版
查看>>
“前.NET Core时代”如何实现跨平台代码重用 ——源文件重用
查看>>
【POJ1845】Sumdiv(数论/约数和定理/等比数列二分求和)
查看>>
在WPF中使用Caliburn.Micro搭建MEF插件化开发框架
查看>>
IdentityServer4-用EF配置Client(一)
查看>>
UWP: 掌握编译型绑定 x:Bind
查看>>
asp.net core系列 35 EF保存数据(2) -- EF系列结束
查看>>
WPF程序加入3D模型
查看>>
WPF中实现多选ComboBox控件
查看>>
读构建之法第四章第十七章有感
查看>>
C#中的IEnumerable<T>知识点
查看>>
android访问链接时候报java.net.MalformedURLException: Protocol not found
查看>>
dwz ie10一直提示数据加载中
查看>>
Windows Phone开发(4):框架和页 转:http://blog.csdn.net/tcjiaan/article/details/7263146
查看>>
Windows Phone Marketplace 发布软件全攻略
查看>>
Unity3D研究院之打开Activity与调用JAVA代码传递参数(十八)【转】
查看>>
语义web基础知识学习
查看>>
hexo个人博客添加宠物/鼠标点击效果/博客管理
查看>>