javaweb Servlet開發(fā)總結(jié)(二)
一、ServletConfig講解
1.1、配置Servlet初始化參數(shù)
在Servlet的配置文件web.xml中,可以使用一個(gè)或多個(gè)<init-param>標(biāo)簽為servlet配置一些初始化參數(shù)。
例如:
<servlet> <servlet-name>ServletConfigDemo1</servlet-name> <servlet-class>gacl.servlet.study.ServletConfigDemo1</servlet-class> <!--配置ServletConfigDemo1的初始化參數(shù) --> <init-param> <param-name>name</param-name> <param-value>gacl</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>123</param-value> </init-param> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </servlet>
1.2、通過ServletConfig獲取Servlet的初始化參數(shù)
當(dāng)servlet配置了初始化參數(shù)后,web容器在創(chuàng)建servlet實(shí)例對(duì)象時(shí),會(huì)自動(dòng)將這些初始化參數(shù)封裝到ServletConfig對(duì)象中,并在調(diào)用servlet的init方法時(shí),將ServletConfig對(duì)象傳遞給servlet。進(jìn)而,我們通過ServletConfig對(duì)象就可以得到當(dāng)前servlet的初始化參數(shù)信息。
例如:
package gacl.servlet.study;
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 ServletConfigDemo1 extends HttpServlet {
/**
* 定義ServletConfig對(duì)象來接收配置的初始化參數(shù)
*/
private ServletConfig config;
/**
* 當(dāng)servlet配置了初始化參數(shù)后,web容器在創(chuàng)建servlet實(shí)例對(duì)象時(shí),
* 會(huì)自動(dòng)將這些初始化參數(shù)封裝到ServletConfig對(duì)象中,并在調(diào)用servlet的init方法時(shí),
* 將ServletConfig對(duì)象傳遞給servlet。進(jìn)而,程序員通過ServletConfig對(duì)象就可以
* 得到當(dāng)前servlet的初始化參數(shù)信息。
*/
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//獲取在web.xml中配置的初始化參數(shù)
String paramVal = this.config.getInitParameter("name");//獲取指定的初始化參數(shù)
response.getWriter().print(paramVal);
response.getWriter().print("<hr/>");
//獲取所有的初始化參數(shù)
Enumeration<String> e = config.getInitParameterNames();
while(e.hasMoreElements()){
String name = e.nextElement();
String value = config.getInitParameter(name);
response.getWriter().print(name + "=" + value + "<br/>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
運(yùn)行結(jié)果如下:

二、ServletContext對(duì)象
WEB容器在啟動(dòng)時(shí),它會(huì)為每個(gè)WEB應(yīng)用程序都創(chuàng)建一個(gè)對(duì)應(yīng)的ServletContext對(duì)象,它代表當(dāng)前web應(yīng)用。
ServletConfig對(duì)象中維護(hù)了ServletContext對(duì)象的引用,開發(fā)人員在編寫servlet時(shí),可以通過ServletConfig.getServletContext方法獲得ServletContext對(duì)象。
由于一個(gè)WEB應(yīng)用中的所有Servlet共享同一個(gè)ServletContext對(duì)象,因此Servlet對(duì)象之間可以通過ServletContext對(duì)象來實(shí)現(xiàn)通訊。ServletContext對(duì)象通常也被稱之為context域?qū)ο蟆?/p>
三、ServletContext的應(yīng)用
3.1、多個(gè)Servlet通過ServletContext對(duì)象實(shí)現(xiàn)數(shù)據(jù)共享
范例:ServletContextDemo1和ServletContextDemo2通過ServletContext對(duì)象實(shí)現(xiàn)數(shù)據(jù)共享
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 ServletContextDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "xdp_gacl";
/**
* ServletConfig對(duì)象中維護(hù)了ServletContext對(duì)象的引用,開發(fā)人員在編寫servlet時(shí),
* 可以通過ServletConfig.getServletContext方法獲得ServletContext對(duì)象。
*/
ServletContext context = this.getServletConfig().getServletContext();//獲得ServletContext對(duì)象
context.setAttribute("data", data); //將data存儲(chǔ)到ServletContext對(duì)象中
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
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 ServletContextDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
String data = (String) context.getAttribute("data");//從ServletContext對(duì)象中取出數(shù)據(jù)
response.getWriter().print("data="+data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
先運(yùn)行ServletContextDemo1,將數(shù)據(jù)data存儲(chǔ)到ServletContext對(duì)象中,然后運(yùn)行ServletContextDemo2就可以從ServletContext對(duì)象中取出數(shù)據(jù)了,這樣就實(shí)現(xiàn)了數(shù)據(jù)共享,如下圖所示:

3.2、獲取WEB應(yīng)用的初始化參數(shù)
在web.xml文件中使用<context-param>標(biāo)簽配置WEB應(yīng)用的初始化參數(shù),如下所示:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <!-- 配置WEB應(yīng)用的初始化參數(shù) --> <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/test</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
獲取Web應(yīng)用的初始化參數(shù),代碼如下:
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();
//獲取整個(gè)web站點(diǎn)的初始化參數(shù)
String contextInitParam = context.getInitParameter("url");
response.getWriter().print(contextInitParam);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
運(yùn)行結(jié)果:

3.3、用servletContext實(shí)現(xiàn)請(qǐng)求轉(zhuǎn)發(fā)
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 = "<h1><font color='red'>abcdefghjkl</font></h1>";
response.getOutputStream().write(data.getBytes());
ServletContext context = this.getServletContext();//獲取ServletContext對(duì)象
RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//獲取請(qǐng)求轉(zhuǎn)發(fā)對(duì)象(RequestDispatcher)
rd.forward(request, response);//調(diào)用forward方法實(shí)現(xiàn)請(qǐng)求轉(zhuǎn)發(fā)
}
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);
}
}
運(yùn)行結(jié)果:

訪問的是ServletContextDemo4,瀏覽器顯示的卻是ServletContextDemo5的內(nèi)容,這就是使用ServletContext實(shí)現(xiàn)了請(qǐng)求轉(zhuǎn)發(fā)
3.4、利用ServletContext對(duì)象讀取資源文件
項(xiàng)目目錄結(jié)構(gòu)如下:

代碼范例:使用servletContext讀取資源文件
package gacl.servlet.study;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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;
/**
* 使用servletContext讀取資源文件
*
* @author gacl
*
*/
public class ServletContextDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/**
* response.setContentType("text/html;charset=UTF-8");目的是控制瀏覽器用UTF-8進(jìn)行解碼;
* 這樣就不會(huì)出現(xiàn)中文亂碼了
*/
response.setHeader("content-type","text/html;charset=UTF-8");
readSrcDirPropCfgFile(response);//讀取src目錄下的properties配置文件
response.getWriter().println("<hr/>");
readWebRootDirPropCfgFile(response);//讀取WebRoot目錄下的properties配置文件
response.getWriter().println("<hr/>");
readPropCfgFile(response);//讀取src目錄下的db.config包中的db3.properties配置文件
response.getWriter().println("<hr/>");
readPropCfgFile2(response);//讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件
}
/**
* 讀取src目錄下的gacl.servlet.study包中的db4.properties配置文件
* @param response
* @throws IOException
*/
private void readPropCfgFile2(HttpServletResponse response)
throws IOException {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/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));
}
/**
* 讀取src目錄下的db.config包中的db3.properties配置文件
* @param response
* @throws FileNotFoundException
* @throws IOException
*/
private void readPropCfgFile(HttpServletResponse response)
throws FileNotFoundException, IOException {
//通過ServletContext獲取web資源的絕對(duì)路徑
String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties");
InputStream in = new FileInputStream(path);
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目錄下的db.config包中的db3.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
}
/**
* 通過ServletContext對(duì)象讀取WebRoot目錄下的properties配置文件
* @param response
* @throws IOException
*/
private void readWebRootDirPropCfgFile(HttpServletResponse response)
throws IOException {
/**
* 通過ServletContext對(duì)象讀取WebRoot目錄下的properties配置文件
* “/”代表的是項(xiàng)目根目錄
*/
InputStream in = this.getServletContext().getResourceAsStream("/db2.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("讀取WebRoot目錄下的db2.properties配置文件:");
response.getWriter().print(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
}
/**
* 通過ServletContext對(duì)象讀取src目錄下的properties配置文件
* @param response
* @throws IOException
*/
private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException {
/**
* 通過ServletContext對(duì)象讀取src目錄下的db1.properties配置文件
*/
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/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));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
運(yùn)行結(jié)果如下:

代碼范例:使用類裝載器讀取資源文件
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;
/**
* 用類裝載器讀取資源文件
* 通過類裝載器讀取資源文件的注意事項(xiàng):不適合裝載大文件,否則會(huì)導(dǎo)致jvm內(nèi)存溢出
* @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進(jìn)行解碼;
* 這樣就不會(huì)出現(xiàn)中文亂碼了
*/
response.setHeader("content-type","text/html;charset=UTF-8");
test1(response);
response.getWriter().println("<hr/>");
test2(response);
response.getWriter().println("<hr/>");
//test3();
test4();
}
/**
* 讀取類路徑下的資源文件
* @param response
* @throws IOException
*/
private void test1(HttpServletResponse response) throws IOException {
//獲取到裝載當(dāng)前類的類裝載器
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 {
//獲取到裝載當(dāng)前類的類裝載器
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));
}
/**
* 通過類裝載器讀取資源文件的注意事項(xiàng):不適合裝載大文件,否則會(huì)導(dǎo)致jvm內(nèi)存溢出
*/
public void test3() {
/**
* 01.avi是一個(gè)150多M的文件,使用類加載器去讀取這個(gè)大文件時(shí)會(huì)導(dǎo)致內(nèi)存溢出:
* 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學(xué)習(xí)視頻\JavaWeb學(xué)習(xí)視頻\JavaWeb\day05視頻\01.avi
// path=01.avi
String path = this.getServletContext().getRealPath("/WEB-INF/classes/01.avi");
/**
* path.lastIndexOf("\\") + 1是一個(gè)非常絕妙的寫法
*/
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);
}
}
運(yùn)行結(jié)果如下:

四、在客戶端緩存Servlet的輸出
對(duì)于不經(jīng)常變化的數(shù)據(jù),在servlet中可以為其設(shè)置合理的緩存時(shí)間值,以避免瀏覽器頻繁向服務(wù)器發(fā)送請(qǐng)求,提升服務(wù)器的性能。例如:
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";
/**
* 設(shè)置數(shù)據(jù)合理的緩存時(shí)間值,以避免瀏覽器頻繁向服務(wù)器發(fā)送請(qǐng)求,提升服務(wù)器的性能
* 這里是將數(shù)據(jù)的緩存時(shí)間設(shè)置為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);
}
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家掌握javaweb Servlet開發(fā)技術(shù)有所幫助。
相關(guān)文章
2023最新版IDEA創(chuàng)建javaweb項(xiàng)目的詳細(xì)圖文教程
之前用的社區(qū)版IDEA無法部署JavaWeb項(xiàng)目,于是裝了一個(gè)最新版的IDEA,下面這篇文章主要給大家介紹了關(guān)于2023最新版IDEA創(chuàng)建javaweb項(xiàng)目的詳細(xì)圖文教程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
使用spring框架實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)處理方式
這篇文章主要介紹了使用spring框架實(shí)現(xiàn)數(shù)據(jù)庫(kù)事務(wù)處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10
SpringMVC Controller解析ajax參數(shù)過程詳解
這篇文章主要介紹了SpringMVC Controller解析ajax參數(shù)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07
Java SpringBoot實(shí)現(xiàn)AOP
AOP包括連接點(diǎn)(JoinPoint)、切入點(diǎn)(Pointcut)、增強(qiáng)(Advisor)、切面(Aspect)、AOP代理(AOP Proxy),具體的方法和類型下面文章會(huì)舉例說明,感興趣的小伙伴和小編一起閱讀全文吧2021-09-09
Mybatis-plus更新字段為null兩種常用方法及優(yōu)化
Mybatis Plus在進(jìn)行更新操作時(shí),默認(rèn)情況下是不能將字段更新為null的,如果要更新字段為null,需要進(jìn)行以下處理,這篇文章主要給大家介紹了關(guān)于Mybatis-plus更新字段為null的兩種常用方法及優(yōu)化,需要的朋友可以參考下2024-03-03
簡(jiǎn)單學(xué)習(xí)Java API 設(shè)計(jì)實(shí)踐
API(Application Programming Interface,應(yīng)用程序編程接口)是一些預(yù)先定義的函數(shù),目的是提供應(yīng)用程序與開發(fā)人員基于某軟件或硬件的以訪問一組例程的能力,而又無需訪問源碼,或理解內(nèi)部工作機(jī)制的細(xì)節(jié)。需要的可以了解一下2019-06-06

