|
Java学习者論坛
我这个程序是用来统计浏览次数的小程序,
们 <welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<Servlet>
<servlet-name>AccessServlet</servlet-name> <!-- Servlet的名字 -->
<servlet-class>
com.throne212.javaweb.ch05.AccessServlet <!-- Servlet的完整类名 -->
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AccessServlet</servlet-name> <!-- Servlet的名字 -->
<url-pattern>/AccessServlet</url-pattern> <!-- Servlet的URL匹配方式 -->
</servlet-mapping>
上面是web.xml的设置,
下面是servlet代码:
package com.throne212.javaweb.ch05;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//定义AccessServlet,继承自HttpServlet
public class AccessServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置返回文本類型
response.setContentType("text/HTML;charset=UTF-8");
// 從会话中獲取到统計数目,如果第一次则为null
int count = 0;
if (request.getSession().getAttribute("count") != null) {
count = (Integer) request.getSession().getAttribute("count");
}
count++;//次数加一
request.getSession().setAttribute("count", count);//把数据放回session中去
PrintWriter out = response.getWriter();// 获取输出流,并开始打印以下信息
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println("这是第 " + count + " 次访问!");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();// 关闭输出流
}
}
下而是index.jsp和代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"request.getServerName()":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page.
</body>
</html>
在浏览器里,看不到servlet代码里设计的效果.请大家看看是那出错了.
欢迎来到Java学习者论壇,转載请注明地址:http://www.javaxxz.com. |
|