---
title: "培训日记（路径问题）"
author: "fhdking"
date: "2007-11-20T11:03:01Z"
tags: []
categories: ["非技术"]
slug: "untitled"
draft: false
lastmod: "2007-11-20T11:03:01Z"
id: 141978
url: "https://fhdking.iteye.com/blog/141978"
---

二、一个显示所有访问者的IP及访问次数的Servlet
运用的知识点如下：
1、存储IP使用什么类型比较好？这个变量定义在哪里比较好？
2、复习了HashMap的迭代知识
代码如下：

```
用HashMap统计IP的访问次数
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IpList extends HttpServlet {
	private Map map = new HashMap();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String ip = request.getRemoteAddr();
		int time = 0;
		if(map.containsKey(ip)) {
			time = Integer.parseInt((String) map.get(ip));
		}
		time++;
		map.put(ip, Integer.valueOf(time).toString());
		Set ipset = map.keySet();
		Iterator iter = ipset.iterator();
		while(iter.hasNext()) {
			String ip1 = (String)iter.next();
			out.println(ip1 + ":" + map.get(ip1) + "<br>");
		}
		out.flush();
		out.close();
	}
}

```

三、servlet的线程安全问题
servlet是多线程的，所以有多个线程访问同一个对象时要考虑线程安全。

```
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;
public class ServletThread extends HttpServlet {
	private int count = 0;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		synchronized (this) {
			count++;
			try {
				Thread.sleep(500);
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println(count + "访问" + Thread.currentThread());
		}
	}
}

```

四、相对路径和绝对路径
1、web应用程序中指定相对和绝对路径
  （1）服务器的根				            http://localhost:8080/
  （2）web工程(web应用程序)的根		        http://localhost:8080/Test/
几个常用的与路径有关的方法的相对路径和绝对路径的总结：

Html文件中的链接	开头有/(绝对路径)	http://localhost:8080/
	开头无/（相对路径）	Html文件自身所在的路径
servlet(URL)Request.getRequestDispatcher(URL)
只能转发到本web应用程序	开头有/(绝对路径)	http://localhost:8080/Test/
	开头无/（相对路径）	相对于Servlet的映射路径
ServletContext.getRequestDispatcher(URL)
可转发到本服务器其他web应用程序	开头有/(绝对路径)	http://localhost:8080/Test/
	开头无/（相对路径）	不能使用
Response.sendRedirect(URL)
可以重定向到任何URL	开头有/(绝对路径)	http://localhost:8080/
	开头无/（相对路径）	相对于Servlet的映射路径
2．请求转发与请求重定向的区别

	请求转发	请求重定向
浏览器发出请求	一次	两次
能不能得到请求参数	能.	不能
地址栏的变化	不变	变
目的地的范围	本服务器内的WEB应用程序	也可以是其它服务器主机