<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Li Guoliang &#187; Servlet</title>
	<atom:link href="http://liguoliang.com/tag/servlet/feed/" rel="self" type="application/rss+xml" />
	<link>http://liguoliang.com</link>
	<description>ActionScript Flex Java JEE PHP...</description>
	<lastBuildDate>Mon, 21 May 2012 17:04:30 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Servlet实践 2-1</title>
		<link>http://liguoliang.com/2009/servlet%e5%ae%9e%e8%b7%b5-2-1/</link>
		<comments>http://liguoliang.com/2009/servlet%e5%ae%9e%e8%b7%b5-2-1/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 12:21:45 +0000</pubDate>
		<dc:creator>Guoliang</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Servlet]]></category>

		<guid isPermaLink="false">http://liguoliang.com/2009/02/757/</guid>
		<description><![CDATA[实践
<a name="_Toc222299869">2.1 </a>需求及用例
创建一个简单的计算器, 当用户输入整数时, 输出其平方值. 但用户需要登录才能进行操作, 用户的登录信息放在web.xml中, 每次登录用户可以使用该计算器三次, 三次使用结束后, 提示用户推出后重新登录继续使用.




User Case 用例


登录系统




B<p class='read-more'><a href='http://liguoliang.com/2009/servlet%e5%ae%9e%e8%b7%b5-2-1/'>More...</a></p><p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></description>
			<content:encoded><![CDATA[<p>实践</p>
<h3><a name="_Toc222299869">2.1 </a>需求及用例</h3>
<p>创建一个简单的计算器, 当用户输入整数时, 输出其平方值. 但用户需要登录才能进行操作, 用户的登录信息放在web.xml中, 每次登录用户可以使用该计算器三次, 三次使用结束后, 提示用户推出后重新登录继续使用.<br />
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="37%">
<p>User Case 用例</p>
</td>
<td width="62%">
<p>登录系统</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Brief description</p>
</td>
<td valign="top" width="62%">
<p>登录系统</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Scope/Level</p>
</td>
<td width="26%">
<p>AthenaES/User goal</p>
</td>
<td width="24%">
<p>Primary actor/role</p>
</td>
<td width="11%">
<p>Root</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Minimal &amp; Success Guarantees 保证</p>
</td>
<td valign="top" width="62%">
<p>Minimal: The system logs how far it may get              <br />Success:登录成功</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Preconditions 前提</p>
</td>
<td valign="top" width="62%">
<p>无</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Triggers 引发条件</p>
</td>
<td valign="top" width="62%">
<p>用户打开登录界面</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Main Success Scenario 成功场景</p>
</td>
<td valign="top" width="62%">
<p>1. 系统提示用户输入用户名及密码              <br />2. 用户输入用户名及密码               <br />3. 系统核对用户名及密码               <br />4. 系统提示用户登录成功</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Extension 扩展 #1</p>
</td>
<td valign="top" width="62%">
<p>3a: 系统无法核实用户身份, 提示其用户名或密码错误, 并提示用户重新输入</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Notes and Issues</p>
</td>
<td valign="top" width="62%">
<p>无</p>
</td>
</tr>
</tbody>
</table>
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="37%">
<p>User Case 用例</p>
</td>
<td width="62%">
<p>计算平方</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Brief description</p>
</td>
<td valign="top" width="62%">
<p>计算平方</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Scope/Level</p>
</td>
<td width="26%">
<p>AthenaES/User goal</p>
</td>
<td width="24%">
<p>Primary actor/role</p>
</td>
<td width="11%">
<p>Root</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Minimal &amp; Success Guarantees 保证</p>
</td>
<td valign="top" width="62%">
<p>Minimal: The system logs how far it may get              <br />Success: 成功显示结果</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Preconditions 前提</p>
</td>
<td valign="top" width="62%">
<p>Actor is logged in</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Triggers 引发条件</p>
</td>
<td valign="top" width="62%">
<p>用户点击”计算”</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Main Success Scenario 成功场景</p>
</td>
<td valign="top" width="62%">
<p>1. 确认用户使用次数未达到上限              <br />2. 用户输入整数               <br />3. 用户点击”计算”               <br />4. 系统确认输入合法               <br />5. 系统计算平方值, 系统将用户使用次数加一, 系统显示结果, 提示用户使用次数.               <br />用户重复步骤1~5 , 直到用户关闭程序或使用次数达到上限</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Extension 扩展 #1</p>
</td>
<td valign="top" width="62%">
<p>1a: 用户使用次数达到上限, 系统提示用户重新登陆后继续使用</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Extension 扩展 #2</p>
</td>
<td valign="top" width="62%">
<p>4a: 系统检测到用户输入不合法, 系统提示用户重新输入 用户重新进行2~4</p>
</td>
</tr>
<tr>
<td width="37%">
<p>Notes and Issues</p>
</td>
<td valign="top" width="62%">
<p>无</p>
</td>
</tr>
</tbody>
</table>
<h3><a name="_Toc222299870">2. 2 </a>数据分析:</h3>
<p><a name="_Toc222299870"></a><b>     <br />1. ServltContext</b><b>层次的数据: </b>由于用户名及最大限制次数等信息在整个Servlet进程中都会被使用, 因此使用Context的Listener来实现.</p>
<p><b>2. Session</b><b>层次的数据: </b>用户本次登录已使用次数应记录在Seesion中, 在当前Session中使用</p>
<p><b>3. Request</b><b>层次的数据: </b>用户输入的数值尽在当前Request中使用</p>
<h3><a name="_Toc222299871">2. 3 </a>具体实现</h3>
<p><a name="_Toc222299871"></a><br />
<table cellspacing="0" cellpadding="0" border="1">
<tbody>
<tr>
<td valign="top" width="945">
<p><b><i>Calc</i></b><b><i>主页面实现:</i></b></p>
</td>
</tr>
<tr>
<td valign="top" width="945">
<p><b>首先检查</b><b>Session</b><b>是否存在</b><b>, </b><b>不存在则跳转到登录界面</b><b>.                <br /></b><b>若</b><b>Session</b><b>存在</b><b>, </b><b>则通过</b><b>session.getAttribute()</b><b>获得该用户在当前</b><b>Session</b><b>中的使用次数</b><b>, </b><b>如果为</b><b>Null, </b><b>则设置为零</b><b>, </b><b>并</b><b>setAttribute.                <br /></b><b>如果不为</b><b>Null, </b><b>则判断是否小于</b><b>MAX_CALCULATION_TIMES_PER_SESSION, </b><b>如果大于三次则提示其退出登录重新登录继续使用</b><b>.                <br /></b><b>小于</b><b>MAX_CALCULATION_TIMES_PER_SESSION</b><b>则呼叫</b><b>proccessRequet()</b><b>方法输出计算器</b><b>. </b><b>该方法将会调用</b><b>calculator()</b><b>方法</b><b>, </b><b>该方法将返回输入值的平方</b><b>,</b><b>同时将</b><b>Session</b><b>中的使用次数加一</b><b>.                <br /></b><b>重要方法</b><b>:                <br /></b><b>request.getSession(false);//</b><b>获得</b><b>Session, </b><b>如果不存在</b><b>, </b><b>则返回</b><b>null                <br />session.getAttribute(ACCESS_COUNT);                 <br />session.setAttribute(ACCESS_COUNT, accessCount);                 <br />request.getSession().invalidate(); //</b><b>清空</b><b>session</b><b></b></p>
</td>
</tr>
<tr></td>
</pre>
</td>
<p>&lt;/&gt;</tr>
</tbody>
</table>
<pre class="java" name="code">package com.insprise.servletStu;
//省略import
public class Calc extends HttpServlet {
	public static final String MAX_CALCULATIONAS_PER_SESSION = “maxNumber”; // 最大使用次数的Key
	public static int MAX_CALCULATION_TIMES_PER_SESSION; // 最大使用次数
	public static final String CURRENT_USER = “currentUser”; // 当前用户
	public static final String URL_MAIN = “./Calc”; // 主页面
	public static final String URL_LOGIN = “./Login”; // 登录页面
	public static final String URL_LOGOUT = “./Logout”; // 注销页面
	private static final String ACCESS_COUNT = “accessCount”; // 使用次数
	private static final String INPUT_INT = “inputInt”;
	private static Logger log = Logger.getLogger(Calc.class);
	private static final int MAX_INT = 46340; // Math.sqrt(Integer.MAX_VALUE)

	private HttpSession session;
	private Integer accessCount; // 使用次数

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		session = request.getSession(false);
		if (validatUser(session)) { // 已登录
			accessCount = (Integer) session.getAttribute(ACCESS_COUNT);
			if (accessCount == null) { // 如果Session中不存在accessCount, 则表明其为新登录用户,
				// 赋值为0;
				accessCount = 0;
				session.setAttribute(ACCESS_COUNT, accessCount);
			}
			if (checkUseTimes(accessCount)) { // 已登录, 且使用次数在限制之内, 进行操作.
				proccessRequet(request, response);

			} else { // 已登录, 但使用次数操过限制,提示用户重新登陆.
				accessOverTime(request, response);
			}
		} else { // 未登录
			response.sendRedirect(URL_LOGIN);
		}
	}

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

	// 检查用户是否已登录
	private boolean validatUser(HttpSession s) {
		if (session != null) {
			return true;
		}
		return false;
	}

	// 检查用户使用次数是否超过限制
	private boolean checkUseTimes(Integer number) {
		//省略
	}

	// 使用次数超过限制之后 提示其登录;
	private void accessOverTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().invalidate();
		response.getWriter().println(&quot;本次登录已使用完毕, 请重新<a href="\&quot;&quot;" ?\? + URL_LOGIN>登录</a>&quot;);
		return;
	}

	// 获得输入数值, 计算结果, 返回信息
	private void proccessRequet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Integer i;
		String title = &quot;求整数平方&quot;;

		response.setContentType(&quot;text/html&quot;);
		response.setCharacterEncoding(&quot;utf-8&quot;);
		// 不使用缓存 在点击推出后 按后退按钮时 不会出现缓存中的内容.
		response.setHeader(&quot;Cache-Control&quot;, &quot;no-store&quot;);
		response.setDateHeader(&quot;Expires&quot;, 0);
		response.setHeader(&quot;Pragma&quot;, &quot;no-cache&quot;);

		PrintWriter out = response.getWriter();
		out.println(ServletUtilities.headwithTitle(title));
		out.println(&quot;
<h3>&quot; + title + &quot;</h3>
<hr />&quot;);
		out.println(&quot;

当前用户: &quot; + session.getAttribute(CURRENT_USER) + &quot; <a href="\&quot;&quot;" ?\? + URL_LOGOUT>[退出]</a>

&quot;);
		String numberString = request.getParameter(INPUT_INT);
		if (numberString != null) {
			try {
					out.println(&quot;
<h2>&quot; + i + &quot; 的平方是: &quot; + calculator(i) + &quot;</h2>

&quot;);
					log.info(&quot;累计第[&quot; + accessCount + &quot;]次使用, 本次计算的参数为: &quot; + i);

			} catch (Exception e) {
	out.println(&quot;您可能输入的不是整数 或您输入的整数绝对值过大
<h2>请输入: 一个绝对值小于&quot; + MAX_INT + &quot; 的整数</h2>

&quot;);
			}
		}
		out.println(&quot;

您总共可以使用 &quot; + MAX_CALCULATION_TIMES_PER_SESSION + &quot;次, 您已累计使用:&quot; + accessCount + &quot;次&quot;);
		// 最后一次运行时, 停止输出Form;
		if (accessCount.equals(MAX_CALCULATION_TIMES_PER_SESSION)) {
			out.println(&quot;已达到最大使用次数限制, 请退出后重新登陆&quot;);
			return;
		}
		printForm(out);
		out.println(&quot;</form>

&quot;);
	}

	// 计算
	private int calculator(int i) {
		accessCount = new Integer(accessCount.intValue() + 1); // 使用次数增加一次
		session.setAttribute(&quot;accessCount&quot;, accessCount);
		return i * i;
	}
	// 打印一个Form
	private void printForm(PrintWriter out) {
		out.print(&quot;
<hr />
<form action="\&quot;\&quot;" method="post">&quot;);
		out.println(&quot;请输入一个整数: &quot;);
		out.println(&quot;
<input name=" + INPUT_INT + " />&quot;);
		out.println(&quot;
<input type="submit" value="\" 计算\?? />
<input type="\" value="\" 重置\?? reset\?? />&quot;);
	}
}</pre>
<p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></content:encoded>
			<wfw:commentRss>http://liguoliang.com/2009/servlet%e5%ae%9e%e8%b7%b5-2-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Servlet学习总结 &#8211; Servlet Reference</title>
		<link>http://liguoliang.com/2009/servlet%e5%ad%a6%e4%b9%a0%e6%80%bb%e7%bb%93-servlet-reference/</link>
		<comments>http://liguoliang.com/2009/servlet%e5%ad%a6%e4%b9%a0%e6%80%bb%e7%bb%93-servlet-reference/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 12:12:45 +0000</pubDate>
		<dc:creator>Guoliang</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Servlet]]></category>

		<guid isPermaLink="false">http://liguoliang.com/2009/02/756/</guid>
		<description><![CDATA[Servlet Reference<p class='read-more'><a href='http://liguoliang.com/2009/servlet%e5%ad%a6%e4%b9%a0%e6%80%bb%e7%bb%93-servlet-reference/'></a></p><p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://liguoliang.com/wp-content/uploads/2009/02/2009213145618.jpg"><img title="2009-2-13 14-56-18" style="border-right: 0px; border-top: 0px; display: inline; border-left: 0px; border-bottom: 0px" height="468" alt="2009-2-13 14-56-18" src="http://liguoliang.com/wp-content/uploads/2009/02/2009213145618-thumb.jpg" width="713" border="0" /></a> </p>
<p>很简单的几个概念, 其他还是OO.</p>
<h4><a name="_Toc222299864">A: Request</a>常用方法</h4>
<p>request中获取参数<br />
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="294">
<p>方法</p>
</td>
<td width="648">
<p>说明</p>
</td>
</tr>
<tr>
<td width="294">
<p><a name="OLE_LINK2"></a><a name="OLE_LINK1">getParameter(String name);</a></p>
</td>
<td width="648">
<p>获得request中参数名name对应的值, 如果不存在该参数, 则返回Null – 注意: <b>名称大小写敏感</b></p>
</td>
</tr>
<tr>
<td width="294">
<p>GetParameterNames</p>
</td>
<td width="648">
<p>返回一个枚举对象, 包含了所在request中的所有参数名, 如果request没有参数, 该方法返回一个空的枚举</p>
</td>
</tr>
<tr>
<td width="294">
<p>GetParameterValues(String name)</p>
</td>
<td width="648">
<p>返回一个Sting[], 包含参数所对应的所有的值, 如果参数不存在,则返回Null.</p>
</td>
</tr>
<tr>
<td width="294">
<p>getParameterMap</p>
</td>
<td width="648">
<p>返回一个Map对象, 以参数名称为Key(String), 参数对应值为Value(类型String[])</p>
</td>
</tr>
<tr>
<td width="294">
<p>getSession()</p>
</td>
<td width="648">
<p>获得当前Session</p>
</td>
</tr>
</tbody>
</table>
<p>Response中输出信息<br />
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="294">
<p>方法</p>
</td>
<td width="648">
<p>说明</p>
</td>
</tr>
<tr>
<td width="294">
<p>setContentType(String type)</p>
</td>
<td width="648">
<p>声明返回数据的MIME类型</p>
</td>
</tr>
<tr>
<td width="294">
<p>setCharacterEncoding(String charset)</p>
</td>
<td width="648">
<p>声明Response的编码</p>
</td>
</tr>
<tr>
<td width="294">
<p>getWriter();</p>
</td>
<td width="648">
<p>返回一个PrintWriter, 可通过该对象的print 或printlin方法向客户端发送字符串数据流</p>
</td>
</tr>
<tr>
<td width="294">
<p>sendRedirect(String location)</p>
</td>
<td width="648">
<p>设置转向 – 转到某地址</p>
</td>
</tr>
</tbody>
</table>
<h4><a name="_Toc222299865">B: Session</a>常用方法:</h4>
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="294">
<p>方法</p>
</td>
<td width="648">
<p>说明</p>
</td>
</tr>
<tr>
<td width="294">
<p>getServletContext()</p>
</td>
<td width="648">
<p>获得Session所在的ServletContext对象</p>
</td>
</tr>
<tr>
<td width="294">
<p>getAttribute(String name)</p>
</td>
<td width="648">
<p>返回该Session中name对应的Attribute对象, 如果没有则返回null</p>
</td>
</tr>
<tr>
<td width="294">
<p>getAttributeNames()</p>
</td>
<td width="648">
<p>返回一个枚举, 包括Seesion中所有的Attribut 对应的name, </p>
</td>
</tr>
<tr>
<td width="294">
<p>setAttribute(String name, Object value)</p>
</td>
<td width="648">
<p>在Session中加入Attribute</p>
</td>
</tr>
<tr>
<td width="294">
<p>invalidate()</p>
</td>
<td width="648">
<p>销毁Session</p>
</td>
</tr>
</tbody>
</table>
<h4><a name="_Toc222299866">C: ServeletContext</a>常用方法</h4>
<table cellspacing="0" cellpadding="0" border="0">
<tbody>
<tr>
<td width="294">
<p>方法</p>
</td>
<td width="648">
<p>说明</p>
</td>
</tr>
<tr>
<td width="294">
<p>getInitParameter(String name)</p>
</td>
<td width="648">
<p>返回一个String, 包含对应的初始化参数, 如果不存在则返回null, init参数可在web.xml中使用&lt;context-param&gt;设定</p>
</td>
</tr>
<tr>
<td width="294">
<p>getInitParameterNames()</p>
</td>
<td width="648">
<p>返回由所有的init参数名称组成的枚举, 如果不存在任何init参数, 则返回空的枚举</p>
</td>
</tr>
<tr>
<td width="294">
<p>getAttribute(String name)</p>
</td>
<td width="648">
<p>返回运行时设定相应的Attribute 对象, 如不存在则返回null</p>
</td>
</tr>
<tr>
<td width="294">
<p>getAttributeNames()</p>
</td>
<td width="648">
<p>返回一个枚举, 包含所有Attribute的name, 如果不存在任何Attribue, 则返回一个空的枚举</p>
</td>
</tr>
<tr>
<td width="294">
<p>setAttribute(String name, Object object)</p>
</td>
<td width="648">
<p>在运行时增加Attribute</p>
</td>
</tr>
<tr>
<td width="294">
<p>removeAttribute(String name)</p>
</td>
<td width="648">
<p>删除对应name的Attribute</p>
</td>
</tr>
</tbody>
</table>
<h4><a name="_Toc222299867">D: Servlet</a>框架理解</h4>
<p>Servlet通过IoC(Inversion of Control意为控制反转)将代码交给框架来执行. 因此只需要在Servlet类中扩展HttpServlet, 覆盖doGet, doPost等方法, 就可成功创建并执行一个Servlet. 在有客户Request时, 将由Service方法分析Request, 并交由对应方法处理, 如Get交由doGet方法处理.</p>
<p>Listener: Servlet中的listener类似于AS中的Event kind, 在Listener支持的事件 – 如Servlet初始化完毕, Session初始化, Request Destory,等, 在这些事件发生后, 将自动运行相应的方法(IoC)</p>
<p>如果需要Listener或Filter, 则在编写好相应的类之后, 加入到web.xml描述文件中.</p>
<p><b>Servlet </b><b>的数据层次:</b>    <br />1. ServletContext: Application初始化时会呼叫Listener contextInitialized(), 可以在该方法中获得或设定ServletContext生命周期内的数据. 如可以通过getInitParameter来获取web.xml中定义好的初始化参数, 也可以通过setAttribute方法设定Attribute, 这些Attribute将在整个Servlet生命周期内有效.</p>
<p>2. HttpSession: 当获得Session之后, 可以进行setAttribute等方法设定Session’的Attribute – 在该Session中有效</p>
<p>3. HttpRequest: 在doGet, doPost等方法中, 可以通过request. get Parameter(String name)等方法来获得request中的数据, 这些数据仅对当前的这个Request有效</p>
<p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></content:encoded>
			<wfw:commentRss>http://liguoliang.com/2009/servlet%e5%ad%a6%e4%b9%a0%e6%80%bb%e7%bb%93-servlet-reference/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>web.xml中&lt;context-param&gt;与&lt;init-param&gt;的差别及各自的读取方式</title>
		<link>http://liguoliang.com/2009/webxml%e4%b8%adcontext-param%e4%b8%8einit-param%e7%9a%84%e5%b7%ae%e5%88%ab%e5%8f%8a%e5%90%84%e8%87%aa%e7%9a%84%e8%af%bb%e5%8f%96%e6%96%b9%e5%bc%8f/</link>
		<comments>http://liguoliang.com/2009/webxml%e4%b8%adcontext-param%e4%b8%8einit-param%e7%9a%84%e5%b7%ae%e5%88%ab%e5%8f%8a%e5%90%84%e8%87%aa%e7%9a%84%e8%af%bb%e5%8f%96%e6%96%b9%e5%bc%8f/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 11:40:37 +0000</pubDate>
		<dc:creator>Guoliang</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[context-param]]></category>
		<category><![CDATA[init-param]]></category>
		<category><![CDATA[Servlet]]></category>
		<category><![CDATA[ServletContext]]></category>

		<guid isPermaLink="false">http://liguoliang.com/2009/02/748/</guid>
		<description><![CDATA[使用ServletContext.getInitParameter()方法 可以获得web.xml中的<context -param>参数 - 使用范围很广, 能getServletContext就可以使用.

在Servlet的init()函数中使用this.getInitParameter()获得web.xml的<init -param>参数 - 较为局限的参数. 注意逻辑上的层次划分</init></context><p class='read-more'><a href='http://liguoliang.com/2009/webxml%e4%b8%adcontext-param%e4%b8%8einit-param%e7%9a%84%e5%b7%ae%e5%88%ab%e5%8f%8a%e5%90%84%e8%87%aa%e7%9a%84%e8%af%bb%e5%8f%96%e6%96%b9%e5%bc%8f/'></a></p><p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></description>
			<content:encoded><![CDATA[<p>事由: 最近几天看了点Servlet, 打算写一个小程序, 需要在application启动时从web.xml中加载一个参数, 由于仅在Login这个Servlet中使用, 于是我是这样实现的:    </p>
<pre class="xml" name="code">  <servlet>
    <description></description>
    <display-name>Login</display-name>
    <servlet-name>Login</servlet-name>
    <servlet-class>com.insprise.servletstu.Login</servlet-class>
    <init-param>
      <description>maxNumber</description>
<param-name>maxNumber</param-name>
<param-value>3</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>Login</servlet-name>
    <url-pattern>/Login</url-pattern>
  </servlet-mapping>
  <servlet></pre>
<p>然后在Login中重写init()方法, 如下:</p>
<pre class="java" name="code">Calc.MAX_CALCULATION_TIMES_PER_SESSION = Integer.parseInt(this.getInitParameter(Calc.MAX_CALCULATIONAS_PER_SESSION));</pre>
<p>功能以实现, 将最大值从web.xml中读取出来, 赋值给一个Global的变量.</p>
<p>===============================承上启下的分割线==============================================</p>
<p>但随着学习的深入, 发现容器并不一定会保持Servlet一直存活, 也许会在Request介绍后Destory掉Login Servlet, 然后如果再次Request Login, 则会重新init(), 于是重新读取web.xml, 重新赋值&#8211;明显第一次有效的, 后面的都是无用功.</p>
<p>从逻辑上分析, 该最大值应属于ServletContext级别的数据, 于是应使用Listener, 监听Application初始化, 在Application初始化时读取.</p>
<p>于是我没有改动web.xml, 设置了监听函数:</p>
<pre class="java" name="code">    public void contextInitialized(ServletContextEvent sce) {
        log.info(&quot;Context Started!&quot; + sce.getServletContext());
        ServletContext context = sce.getServletContext();
        Calc.MAX_CALCULATION_TIMES_PER_SESSION = Integer.parseInt(context.getInitParameter(Calc.MAX_CALCULATIONAS_PER_SESSION));
    }</pre>
<p>但不论如何都会有NullPoint的错误. 于是意识到该应在web.xml使用&lt;context-param&gt;设定参数, 而非某个&lt;Servlet&gt;下的&lt;init-param&gt;标签. 修改后的web.xml: </p>
<pre class="xml" name="code"> <context-param>
<param-name>maxNumber</param-name>
<param-value>3</param-value>
</context-param></pre>
<p>=====================================总结性的分割线============================================ </p>
<p>总而言之:<br />
  <br />使用ServletContext.getInitParameter()方法 可以获得web.xml中的&lt;context-param&gt;参数 &#8211; 使用范围很广, 能getServletContext就可以使用.</p>
<p>在Servlet的init()函数中使用this.getInitParameter()获得web.xml的&lt;init-param&gt;参数 &#8211; 较为局限的参数. 注意逻辑上的层次划分</p>
<p><p>

----------Post from: <a href="http://liguoliang.com">@LiGuoliang.com, 欢迎回来~</a>----------</p></p>
]]></content:encoded>
			<wfw:commentRss>http://liguoliang.com/2009/webxml%e4%b8%adcontext-param%e4%b8%8einit-param%e7%9a%84%e5%b7%ae%e5%88%ab%e5%8f%8a%e5%90%84%e8%87%aa%e7%9a%84%e8%af%bb%e5%8f%96%e6%96%b9%e5%bc%8f/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

