javaweb Servlet開發(fā)總結(jié)(二)
一、ServletConfig講解
1.1、配置Servlet初始化參數(shù)
在Servlet的配置文件web.xml中,可以使用一個或多個<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í)例對象時,會自動將這些初始化參數(shù)封裝到ServletConfig對象中,并在調(diào)用servlet的init方法時,將ServletConfig對象傳遞給servlet。進(jìn)而,我們通過ServletConfig對象就可以得到當(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對象來接收配置的初始化參數(shù) */ private ServletConfig config; /** * 當(dāng)servlet配置了初始化參數(shù)后,web容器在創(chuàng)建servlet實(shí)例對象時, * 會自動將這些初始化參數(shù)封裝到ServletConfig對象中,并在調(diào)用servlet的init方法時, * 將ServletConfig對象傳遞給servlet。進(jìn)而,程序員通過ServletConfig對象就可以 * 得到當(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對象
WEB容器在啟動時,它會為每個WEB應(yīng)用程序都創(chuàng)建一個對應(yīng)的ServletContext對象,它代表當(dāng)前web應(yīng)用。
ServletConfig對象中維護(hù)了ServletContext對象的引用,開發(fā)人員在編寫servlet時,可以通過ServletConfig.getServletContext方法獲得ServletContext對象。
由于一個WEB應(yīng)用中的所有Servlet共享同一個ServletContext對象,因此Servlet對象之間可以通過ServletContext對象來實(shí)現(xiàn)通訊。ServletContext對象通常也被稱之為context域?qū)ο蟆?/p>
三、ServletContext的應(yīng)用
3.1、多個Servlet通過ServletContext對象實(shí)現(xiàn)數(shù)據(jù)共享
范例:ServletContextDemo1和ServletContextDemo2通過ServletContext對象實(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對象中維護(hù)了ServletContext對象的引用,開發(fā)人員在編寫servlet時, * 可以通過ServletConfig.getServletContext方法獲得ServletContext對象。 */ ServletContext context = this.getServletConfig().getServletContext();//獲得ServletContext對象 context.setAttribute("data", data); //將data存儲到ServletContext對象中 } 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對象中取出數(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存儲到ServletContext對象中,然后運(yùn)行ServletContextDemo2就可以從ServletContext對象中取出數(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(); //獲取整個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)請求轉(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對象 RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//獲取請求轉(zhuǎn)發(fā)對象(RequestDispatcher) rd.forward(request, response);//調(diào)用forward方法實(shí)現(xiàn)請求轉(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)了請求轉(zhuǎn)發(fā)
3.4、利用ServletContext對象讀取資源文件
項(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)行解碼; * 這樣就不會出現(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資源的絕對路徑 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對象讀取WebRoot目錄下的properties配置文件 * @param response * @throws IOException */ private void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException { /** * 通過ServletContext對象讀取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對象讀取src目錄下的properties配置文件 * @param response * @throws IOException */ private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException { /** * 通過ServletContext對象讀取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):不適合裝載大文件,否則會導(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)行解碼; * 這樣就不會出現(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):不適合裝載大文件,否則會導(dǎo)致jvm內(nèi)存溢出 */ public void test3() { /** * 01.avi是一個150多M的文件,使用類加載器去讀取這個大文件時會導(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是一個非常絕妙的寫法 */ 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的輸出
對于不經(jīng)常變化的數(shù)據(jù),在servlet中可以為其設(shè)置合理的緩存時間值,以避免瀏覽器頻繁向服務(wù)器發(fā)送請求,提升服務(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ù)合理的緩存時間值,以避免瀏覽器頻繁向服務(wù)器發(fā)送請求,提升服務(wù)器的性能 * 這里是將數(shù)據(jù)的緩存時間設(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); } }
以上就是本文的全部內(nèi)容,希望對大家掌握javaweb Servlet開發(fā)技術(shù)有所幫助。
相關(guān)文章
Spring boot整合mybatis實(shí)現(xiàn)過程圖解
這篇文章主要介紹了Spring boot整合mybatis實(shí)現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08MyBatis直接執(zhí)行SQL的工具SqlMapper
今天小編就為大家分享一篇關(guān)于MyBatis直接執(zhí)行SQL的工具SqlMapper,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12