javaweb学习总结(五) - - Servlet开发(二)

2021-06-22 02:05

阅读:669

标签:根目录   资源   patch   htm   存储   配置   获取文件   res   context   

一、ServletConfig讲解

1.1、配置Servlet初始化参数

  在Servlet的配置文件web.xml中,可以使用一个或多个标签为servlet配置一些初始化参数。

例如:

ServletDemo2class>com.tanlei.cn.ServletDemo2class>
    nametanleipassword123charsetUTF-8

 

1.2、通过ServletConfig获取Servlet的初始化参数

  当servlet配置了初始化参数后,web容器在创建servlet实例对象时,会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,将ServletConfig对象传递给servlet。进而,我们通过ServletConfig对象就可以得到当前servlet的初始化参数信息。

package com.tanlei.cn;

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;

public class ServletDemo2 extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    /**
     * 定义ServletConfig对象来接收配置的初始化参数
     */
    private ServletConfig config;
    
     /**
     * 当servlet配置了初始化参数后,web容器在创建servlet实例对象时,
     * 会自动将这些初始化参数封装到ServletConfig对象中,并在调用servlet的init方法时,
     * 将ServletConfig对象传递给servlet。进而,程序员通过ServletConfig对象就可以
     * 得到当前servlet的初始化参数信息。
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config=config;
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取在web.xml中配置的初始化参数
        String paramVal=this.config.getInitParameter("name");//获取指定的初始化参数
        resp.getWriter().println(paramVal);
        resp.getWriter().println("
"); //获取所有的初始化参数 Enumeration enumeration=config.getInitParameterNames(); while(enumeration.hasMoreElements()) { String name=enumeration.nextElement(); String value=config.getInitParameter(name); resp.getWriter().print(name+"="+value); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doPost(req, resp); } }

运行结果如下:

技术分享图片

二、ServletContext对象

  WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。
  ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,可以通过ServletConfig.getServletContext方法获得ServletContext对象。
  由于一个WEB应用中的所有Servlet共享同一个ServletContext对象,因此Servlet对象之间可以通过ServletContext对象来实现通讯。ServletContext对象通常也被称之为context域对象。

三、ServletContext的应用

  3.1、多个Servlet通过ServletContext对象实现数据共享

  范例:ServletContextDemo1和ServletContextDemo2通过ServletContext对象实现数据共享

package com.tanlei.cn;

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;

public class ServletContextDemo1 extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
   
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String data="tl_com";
        /**
         * ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,
          * 可以通过ServletConfig.getServletContext方法获得ServletContext对象。
         */
        ServletContext context=this.getServletConfig().getServletContext();
        context.setAttribute("data", data);//将data存储到ServletContext对象中
       
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }
}
package com.tanlei.cn;

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;

public class ServletContextDemo2 extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context=this.getServletContext();
        String data=(String) context.getAttribute("data");
        resp.getWriter().print(data);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doPost(req, resp);
    }
}

先运行ServletContextDemo1,将数据data存储到ServletContext对象中,然后运行ServletContextDemo2就可以从ServletContext对象中取出数据了,这样就实现了数据共享,如下图所示:

技术分享图片

 

 

3.2、获取WEB应用的初始化参数

  在web.xml文件中使用标签配置WEB应用的初始化参数,如下所示:

  
  urljdbc:mysql://localhost:3306/musqlindex.jsp

获取Web应用的初始化参数,代码如下:

package gacl.servlet.study;

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;


public class ServletContextDemo3 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext context = this.getServletContext();
        //获取整个web站点的初始化参数
        String contextInitParam = context.getInitParameter("url");
        response.getWriter().print(contextInitParam);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

技术分享图片

3.3、用servletContext实现请求转发

ServletContextDemo4

package gacl.servlet.study;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String data = "

abcdefghjkl

"; response.getOutputStream().write(data.getBytes()); ServletContext context = this.getServletContext();//获取ServletContext对象 RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//获取请求转发对象(RequestDispatcher) rd.forward(request, response);//调用forward方法实现请求转发 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
ServletContextDemo5

package gacl.servlet.study;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletContextDemo5 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getOutputStream().write("servletDemo5".getBytes());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

技术分享图片

访问的是ServletContextDemo4,浏览器显示的却是ServletContextDemo5的内容,这就是使用ServletContext实现了请求转发

  3.4、利用ServletContext对象读取资源文件

  项目目录结构如下:

技术分享图片

代码范例:使用servletContext读取资源文件

package gacl.servlet.study;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用类装载器读取资源文件
 * 通过类装载器读取资源文件的注意事项:不适合装载大文件,否则会导致jvm内存溢出
 * @author gacl
 *
 */
public class ServletContextDemo7 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /**
         * response.setContentType("text/html;charset=UTF-8");目的是控制浏览器用UTF-8进行解码;
         * 这样就不会出现中文乱码了
         */
        response.setHeader("content-type","text/html;charset=UTF-8");
        test1(response);
        response.getWriter().println("
"); test2(response); response.getWriter().println("
"); //test3(); test4(); } /** * 读取类路径下的资源文件 * @param response * @throws IOException */ private void test1(HttpServletResponse response) throws IOException { //获取到装载当前类的类装载器 ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用类装载器读取src目录下的db1.properties配置文件 InputStream in = loader.getResourceAsStream("db1.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("用类装载器读取src目录下的db1.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 读取类路径下面、包下面的资源文件 * @param response * @throws IOException */ private void test2(HttpServletResponse response) throws IOException { //获取到装载当前类的类装载器 ClassLoader loader = ServletContextDemo7.class.getClassLoader(); //用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件 InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties"); Properties prop = new Properties(); prop.load(in); String driver = prop.getProperty("driver"); String url = prop.getProperty("url"); String username = prop.getProperty("username"); String password = prop.getProperty("password"); response.getWriter().println("用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件:"); response.getWriter().println( MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } /** * 通过类装载器读取资源文件的注意事项:不适合装载大文件,否则会导致jvm内存溢出 */ public void test3() { /** * 01.avi是一个150多M的文件,使用类加载器去读取这个大文件时会导致内存溢出: * java.lang.OutOfMemoryError: Java heap space */ InputStream in = ServletContextDemo7.class.getClassLoader().getResourceAsStream("01.avi"); System.out.println(in); } /** * 读取01.avi,并拷贝到e:\根目录下 * 01.avi文件太大,只能用servletContext去读取 * @throws IOException */ public void test4() throws IOException { // path=G:\Java学习视频\JavaWeb学习视频\JavaWeb\day05视频\01.avi // path=01.avi String path = this.getServletContext().getRealPath("/WEB-INF/classes/01.avi"); /** * path.lastIndexOf("\\") + 1是一个非常绝妙的写法 */ String filename = path.substring(path.lastIndexOf("\\") + 1);//获取文件名 InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/01.avi"); byte buffer[] = new byte[1024]; int len = 0; OutputStream out = new FileOutputStream("e:\\" + filename); while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); in.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }

 

技术分享图片

四、在客户端缓存Servlet的输出

  对于不经常变化的数据,在servlet中可以为其设置合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能。例如

package gacl.servlet.study;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDemo5 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String data = "abcddfwerwesfasfsadf";
        /**
         * 设置数据合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能
         * 这里是将数据的缓存时间设置为1天
         */
        response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000);
        response.getOutputStream().write(data.getBytes());
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doGet(request, response);
    }

}

技术分享图片

 

javaweb学习总结(五) - - Servlet开发(二)

标签:根目录   资源   patch   htm   存储   配置   获取文件   res   context   

原文地址:https://www.cnblogs.com/tanlei-sxs/p/9635816.html


评论


亲,登录后才可以留言!