借助之前写的带filter的留言板。目录结构图如下:
1.写表单。index.jsp主要代码如下:
<body>
<%String demo = new String("demo");
application.setAttribute("demo", demo); %>
<form action = "commentServlet" method = "post">
username:<input type = "text" name = "username"><br>
comment:<textarea name = "comment">
</textarea><br>
<input type = "submit">
</form>
</body>
2.处理action转向的commentServlet。因为写了过滤器,所以程序先处理过滤器。在过滤器中写了一些读写过滤器初始化参数的读写操作。
public class commentFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// 第一种获取初始化参数: 结果如下
// 信息: Starting Servlet Engine: Apache Tomcat/6.0.13
// init started
// world
// gay
// ketty
// ILIKE
// init started
// 2013-12-10 10:32:03 org.apache.coyote.http11.Http11Protocol start
/*
* String hello = filterConfig.getInitParameter("hello"); String hey =
* filterConfig.getInitParameter("hey"); String hi =
* filterConfig.getInitParameter("hi"); String hehe =
* filterConfig.getInitParameter("hehe");
* System.out.println(hello+"\n"+hey+"\n"+hi+"\n"+hehe);
*/
String demo0 = new String("demo000000000");
ServletContext context = filterConfig.getServletContext();
context.setAttribute("demo0", demo0);
// 第二种获取初始化参数信息: 结果如下
// Starting Servlet Engine: Apache Tomcat/6.0.13
// init started
// hello: world
//
// hey: gay
//
// hehe: ILIKE
//
// hi: ketty
//
// init started
Enumeration values = filterConfig.getInitParameterNames();
while (values.hasMoreElements()) {
String name = (String) values.nextElement();
String value = filterConfig.getInitParameter(name);
System.out.println(name + ": " + value + "\n");
}
}
}
过滤器配置如下:
<!--加filter 手动配置filter如下 -->
<filter>
<filter-name>commentf</filter-name>
<filter-class>com.my.filter.commentFilter</filter-class>
<init-param>
<param-name>hello</param-name>
<param-value>world</param-value>
</init-param>
<init-param>
<param-name>hey</param-name>
<param-value>gay</param-value>
</init-param>
<init-param>
<param-name>hi</param-name>
<param-value>ketty</param-value>
</init-param>
<init-param>
<param-name>hehe</param-name>
<param-value>ILIKE</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>commentf</filter-name>
<url-pattern>/commentServlet</url-pattern>
</filter-mapping>
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//加filter
ServletContext context = getServletContext();
String contextvalue =(String)context.getAttribute("demo0");
System.out.println(contextvalue);
req.getRequestDispatcher("MyJsp.jsp").forward(req, resp);
}
4.最后到达的MyJsp代码如下:
<body>
username: <%=request.getAttribute("username") %><br>
comment:<%= request.getAttribute("comment")%>
<%=application.getAttribute("demo") %>
<%=application.getAttribute("demo0") %>
</body>
总结:实现了读取Init-parm中的参数,并且servletContext 对象全局范围内传参数读写也实现了。