JavaWeb-获取网站访问数量并且获得初始化参数
2015-10-16 09:21
651 查看
JavaWeb-获取网站访问数量并且获得初始化参数
要点:在web.xml设置初始化参数
如何获取初始化参数
重写init方法
首先在web.xml设置初始化值
[code]<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <context-param> <param-name>count</param-name> <param-value>1234</param-value> </context-param> <servlet> <servlet-name>HitServlet</servlet-name> <servlet-class>com.org.web.HitWebDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>HitServlet</servlet-name> <url-pattern>/Hit</url-pattern> </servlet-mapping> </web-app>
ServletContext对象包含在ServletConfig对象之中,ServletConfig对象在servlet初始化时提供servlet对象
getInitParameter()方法概述:public java.lang.String getInitParameter(java.lang.String name)
返回上下文定义的变量的值,如果变量不存在,返回null。
HitWebDemo.java
[code]package com.org.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; 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 HitWebDemo extends HttpServlet { private int count; @Override public void init(ServletConfig config) throws ServletException { ServletContext servletContext = config.getServletContext(); count = Integer.parseInt(servletContext.getInitParameter("count")); // 获取初始化参数值 } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { count++; // 访问的数量 resp.setContentType("text/html;charset=gb2312"); // 解决中文乱码问题 PrintWriter out = resp.getWriter(); out.println("<h3>您是第" + count + "位访客</h3>"); out.close(); } }
相关文章推荐
- iOS应用架构谈 view层的组织和调用方案
- iOS应用架构谈 开篇
- 对于流程优化的处理器架构
- 两款JS脚本判断手机浏览器类型跳转WAP手机网站
- 网站关键词优化--浅析如何6为网站选取关键词
- 如何搭建自己的个人技术博客网站
- 常用技术类网站链接
- 软件、网站测试
- WEB技术之四层架构
- puppet组织架构
- IM服务器的架构
- 网站所有页面都在新窗口打开
- css进阶学习网站
- 论微观微观设计平台制造步骤的官方网站
- [高可用性] 负载均衡,会话保持,session同步(转)
- 如何 阻止员工 访问 找工作网站 变态的方法 也适合禁用其它网站
- 如何 阻止员工 访问 找工作网站 变态的方法 也适合禁用其它网站
- 精品软件推荐 网站流量提升工具
- 精品软件推荐 网站流量提升工具
- 列式存储hbase系统架构学习