javaweb Servlet開辟總結(二)。本站提示廣大學習愛好者:(javaweb Servlet開辟總結(二))文章只能為提供參考,不一定能成為您想要的結果。以下是javaweb Servlet開辟總結(二)正文
1、ServletConfig講授
1.1、設置裝備擺設Servlet初始化參數
在Servlet的設置裝備擺設文件web.xml中,可使用一個或多個<init-param>標簽為servlet設置裝備擺設一些初始化參數。
例如:
<servlet> <servlet-name>ServletConfigDemo1</servlet-name> <servlet-class>gacl.servlet.study.ServletConfigDemo1</servlet-class> <!--設置裝備擺設ServletConfigDemo1的初始化參數 --> <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的初始化參數
當servlet設置裝備擺設了初始化參數後,web容器在創立servlet實例對象時,會主動將這些初始化參數封裝到ServletConfig對象中,並在挪用servlet的init辦法時,將ServletConfig對象傳遞給servlet。進而,我們經由過程ServletConfig對象便可以獲得以後servlet的初始化參數信息。
例如:
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對象來吸收設置裝備擺設的初始化參數 */ private ServletConfig config; /** * 當servlet設置裝備擺設了初始化參數後,web容器在創立servlet實例對象時, * 會主動將這些初始化參數封裝到ServletConfig對象中,並在挪用servlet的init辦法時, * 將ServletConfig對象傳遞給servlet。進而,法式員經由過程ServletConfig對象便可以 * 獲得以後servlet的初始化參數信息。 */ @Override public void init(ServletConfig config) throws ServletException { this.config = config; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得在web.xml中設置裝備擺設的初始化參數 String paramVal = this.config.getInitParameter("name");//獲得指定的初始化參數 response.getWriter().print(paramVal); response.getWriter().print("<hr/>"); //獲得一切的初始化參數 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); } }
運轉成果以下:
2、ServletContext對象
WEB容器在啟動時,它會為每一個WEB運用法式都創立一個對應的ServletContext對象,它代表以後web運用。
ServletConfig對象中保護了ServletContext對象的援用,開辟人員在編寫servlet時,可以經由過程ServletConfig.getServletContext辦法取得ServletContext對象。
因為一個WEB運用中的一切Servlet同享統一個ServletContext對象,是以Servlet對象之間可以經由過程ServletContext對象來完成通信。ServletContext對象平日也被稱之為context域對象。
3、ServletContext的運用
3.1、多個Servlet經由過程ServletContext對象完成數據同享
典范:ServletContextDemo1和ServletContextDemo2經由過程ServletContext對象完成數據同享
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對象中保護了ServletContext對象的援用,開辟人員在編寫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對象中掏出數據 response.getWriter().print("data="+data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
先運轉ServletContextDemo1,將數據data存儲到ServletContext對象中,然後運轉ServletContextDemo2便可以從ServletContext對象中掏出數據了,如許就完成了數據同享,以下圖所示:
3.2、獲得WEB運用的初始化參數
在web.xml文件中應用<context-param>標簽設置裝備擺設WEB運用的初始化參數,以下所示:
<?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運用的初始化參數 --> <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運用的初始化參數,代碼以下:
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 = "<h1><font color='red'>abcdefghjkl</font></h1>"; 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.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停止解碼; * 如許就不會湧現中文亂碼了 */ 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設置裝備擺設文件 * “/”代表的是項目根目次 */ 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); } }
運轉成果以下:
代碼典范:應用類裝載器讀取資本文件
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("<hr/>"); test2(response); response.getWriter().println("<hr/>"); //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); } }
運轉成果以下:
4、在客戶端緩存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開辟技巧有所贊助。