浏览器访问Servlet
1.指定一个Servlet路径(
在web.xml :
<servlet>
<servlet-name>随意命名</servlet-name>
<servlet-class>包名.类名</servlet-class>
<init-param>
<param-name>参数名称1</param-name>
<param-value>参数值1</param-value>
</init-param>
<init-param>
<param-name>参数名称2</param-name>
<param-value>参数值2</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>随意命名</servlet-name>
<url-pattern>/Servlet路径</url-pattern>
</servlet-mapping>
)
-->浏览器访问Servlet路径
Servlet 生命周期方法:
void inti(ServletConfig) 创建之后立即执行
void service(request,respons)
void destroy() 停止之前立即执行
Servletconfig()提取对应的某个Servlet的配置信息
功能:
ServletContext getServletContext()获取Servlet上下文
String getInitParameter(String name):通过名称获取制定初始化参数的值
Enumeration getInitParameterName():获取所有初始化参数的名称;返回一个集合
Servlet特性:
单利,一个类只有一个对象,可能存在多个Servlet类!
线程不安全,但效率高
Servlet由java编写,由服务器来调用相应的方法;
/*
统计访问量
1.创建一个ServletContext对象
2.调用setServletContext方法设置count属性
3.输出访问量
**/
/*
向浏览器输出
得到一个PrintWriter流**/
PrintWriter pw = response.getWriter();
pw.print(count);
package COUNT; import java.io.IOException;
import java.io.PrintWriter; 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 Count extends HttpServlet { /**
* 统计浏览器访问量
*/
public Count() {
super();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*获取ServletContext对象*/
ServletContext servletContext = this.getServletContext();
Integer count = (Integer)servletContext.getAttribute("count");
if(count == null)
servletContext.setAttribute("count",1);
else {
servletContext.setAttribute("count", count+1);
}
/**向浏览器输出响应对象*/
PrintWriter PW = response.getWriter();
PW.print("The Count is :"+count);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}