天天看點

讀取web.xml的配置參數

1.建立Servlet:

package com.wch.sp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

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

public class RequestServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public RequestServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); 
	}
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>請登入檢視秘密檔案</TITLE></HEAD>");
		out.println("  <BODY>");
		out.println(request.getRequestURI());
		String requestURI=request.getRequestURI();
		out.print("<form action='"+requestURI+"' method='POST'>");
		out.print("帳号:<input type='text' name='username' style='width:200px;'/><br/>");
		out.print("密碼:<input type='password' name='password' style='width:200px;'/><br/>");
		out.println("<input type='submit' value='登入'>");
		out.println("</form>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{		
		response.setContentType("text/html");
		
		String username = request.getParameter("username");
		String password= request.getParameter("password");
		
		Enumeration params=this.getInitParameterNames();
		
		while(params.hasMoreElements())
		{
			String usernameParame = params.nextElement().toString();
			String passwordParame =this.getInitParameter(usernameParame);
			if(username.equals(usernameParame)&&password.equals(passwordParame))
			{
				request.getRequestDispatcher("/WEB-INF/noticde.html").forward(request, response);
				return;				
			}
		}
		
		this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
           

2.配置web.xml檔案:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	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_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <!-- 配置Servlet中,以下兩個屬性是必須配置的,name是可以任意取的,class配置的是包名 -->
    <servlet-name>FirstServlet</servlet-name>
    <servlet-class>com.wch.sp.servlet.FirstServlet</servlet-class>
    <!-- servlet中還有許多可選的配置,例如下面的初始化參數配置,一個Servlet可以配置多個初始化參數,Servlet中可以使用getInitParameter(name)
		或者是getInitParameterNames()擷取配置的參數值-->
    <init-param>
        <param-name>message</param-name>
        <param-value>utf-8</param-value>
    </init-param>
    <!--下面的标簽配置的是Servlet的加載方式,可選值為0或1,如果配置為1,Tomcat會在啟動時加載該Serlet。
    	否則,Tomcat會在有人第一次請求該Servlet的時候才加載該 Servlet。實際項目中,一些架構如Struts、JSF、Spring都是用該參數來加載架構中核心的Servlet-->
    <load-on-startup>1</load-on-startup>
</servlet>
  <servlet>
    <servlet-name>RequestServlet</servlet-name>
    <servlet-class>com.wch.sp.servlet.RequestServlet</servlet-class>
    <init-param>
 		<param-name>admin</param-name>
 		<param-value>admin</param-value>
 	</init-param>
 	<init-param>
 		<param-name>babyface</param-name>
 		<param-value>123</param-value>
 	</init-param>
  </servlet>

<!--配置Servlet的通路方式,Servlet-name就是前面配置的Servlet的名稱,url-pattern配置該Servlet的通路方式-->
<servlet-mapping>
    <servlet-name>FirstServlet</servlet-name>
<!-- 配置的Servlet的通路路徑,可以随便設定,比如說我現在通路Servlet的路徑就是:http://localhost:8080/Servlet/servlet/firstServlet -->
    <url-pattern>/servlet/firstServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
  <servlet-name>RequestServlet</servlet-name>
  <url-pattern>/servlet/RequestServlet</url-pattern>  
</servlet-mapping>
</web-app>
           

3.在WEB-INF下面建立noticde.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>noticde.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css" target="_blank" rel="external nofollow" >-->

  </head>
  
  <body>
    HELLO
  </body>
</html>
           

4.釋出項目至伺服器,啟動伺服器,通路: http://localhost:8080/Servlet/servlet/RequestServlet

結果為:

讀取web.xml的配置參數

登入後:

讀取web.xml的配置參數

總結:

         1.在web.xml配置檔案中配置Servlet的時候,可以給Servlet配置初始化參數,使用<init-param>标簽類配置。配置完畢之後,Servlet提供方法:getInitParameterNames()或者getInitParameterName(String name)方法擷取初始化參數值。這些初始化參數也可以使用ServletConfig對象擷取,Servlet提供getServletConfig()方法擷取ServletConfig對象。由ServletConfig取初始化參數與Servlet直接取方式一樣。

        2.初始化參數的好處就是可以把某些變量拿到web.xml中配置,需要修改時隻需要修改web.xml檔案中重新開機伺服器即可,而不是需要修改Servlet類

        3.由此擴充到上下文參數(<context-param>):由于<init-param>是配置在<servlet>标簽裡的,隻能由這個Servlet來讀取,是以它不是全局參數,不能被其它的Servlet讀取,這時可以配置上下文參數。擷取context-param可以使用ServletContext對象,Servlet中可以通過getServletConfig().getServletContext()來擷取一個ServletContext對象,使用ServletContext的getInitParameter()方法來擷取指定名稱的參數,通過getInitParameters()擷取所有的context-param參數名稱

繼續閱讀