---
title: "java 培训日记"
author: "fhdking"
date: "2007-11-19T15:08:22Z"
tags: []
slug: "java"
draft: false
lastmod: "2007-11-19T15:08:22Z"
id: 141737
url: "https://fhdking.iteye.com/blog/141737"
---

进行了一周紧张后的学习，今天终于闲下把日记与大家分享，在这周里张老师给我们讲了好多未来我们在工作中出现的一些问题，我记得不是很好！希望大家多提建议！让我更好的掌握JAVA :D 
一、myeclipse的安装和基本使用
1、安装路径最好不带有空格；
2、将Tomcat置于myeclipse的控制之下；
3、建立Web Project，以及发布到Tomcat服务器；
4、myeclipse常用的快捷键列表如下：
   Alt + /		    代码提示
   Ctrl + shift + o	    导入包
   Ctrl + shift + f	    代码格式化
   Alt  + shift + s 	弹出使用右键source的菜单
   Alt  + shift + z 	代码包含(如try/catch)
   Alt  + shift + /     将代码注释掉
   Alt  + shift + \     取消对代码的注释

二、JSP的部分基础知识
1、指令元素：page指令，include指令，taglib指令。指令必须嵌套在<%@   %>中
2、脚本片段，在里面直接写java源代码			<%         %>
3、脚本表达式					<%=        %>
4、脚本声明						<%!        %>
5、JSP注释						<%--     --%>

三、Tomcat中重要的几个Servlet(在\conf\web.xml中查看)
   DefaultServlet（缺省Servlet）	org.apache.catalina.servlets.DefaultServlet
   作用：处理服务器中某个静态资源，例如加载静态的网页，图片。如果在conf目录下的web.xml中注释掉这个servlet，则我们发布的静态网页不会显示。（还要注释掉<servlet-mapping>）
   InvokerServlet（Servlet激活器）	org.apache.catalina.servlets.InvokerServlet
   作用：激活和调用任何其他Servlet，需要在全局的Web.xml中配置，默认被注释掉，如果去掉注释，则我们不用自己在我们的web.xml中配置我们写的servlet，服务器也会自动帮我们加载。
   JspServlet				        org.apache.jasper.servlet.JspServlet
   作用：编译和执行jsp页面

四、两个案例
（一）模拟DefaultServlet输出静态文件的内容
1、Tomcat系统的DefaultServlet的作用就是读取静态资源然后输出到客户端浏览器，为了能验证程序的效果，我们需要把系统conf\web.xml中关于它的配置注释掉；
2、新建一个Servlet，假定我们只让这个servlet拦截对Html文件的访问，就把映射路径设置为*.html；
3、在servlet里面得到浏览器请求的文件名，得到输入流，再把输入流读到数组当中，再把数组内容写入到由response对象得到的输出流ServletOutputStream中即可。
主要代码如下：
public class DefaultServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	FileInputStream fis = new FileInputStream(request.getRealPath("/") + request.getServletPath().substring(1));
		ServletOutputStream sos = response.getOutputStream();
		byte buf = new byte;
		int len = -1;
		while((len = fis.read(buf))!= -1){
			sos.write(buf);
		}
		sos.flush();
		sos.close();
		fis.close();
	}
}
小知识点：如何获取浏览器的请求名？
假如在浏览器的地址栏里面输入：http://localhost:880/Test/MyJSP.jsp
方法一：
String path1 = request.getRequestURI() 得到/Test/MyJsp.jsp 
String path2 = request.getContextPath()得到/Test 
path1.substring(path2.length())
方法二：
String path = request.getServletPath() 得到/MyJsp.jsp
path.substring(1)

（二）计数器
（1）用JSP实现记数
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<html>
  <head>
    <title>My JSP 'view.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">    
  </head>
  <%!int count = 0; %>
  <body>
    您是第<%=++count %>个访问者。<br>
  </body>
</html>

如果这样定义count：<% int count = 0 %>就不能看到效果，通过查看服务器自动生成的servlet（在work/lib内），发现这种定义是在service方法中的，而向上面那种定义是在方法外面的，就成了成员变量，在下次调用时，count值仍然不变。这样就可以实现了。但是当服务器关闭了，那么count就归0了。

（2）用servlet编写通用计数器
对单个文件写个计数器比较简单，复杂的是写一个通用的计数器，可以统计很多页面。实施原理如下：
1、使用一个CountServlet来完成计数功能；主要代码如下：
public class CountServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {	
			int count = -1;
			try {
				count = getCount(request);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			sendImage(response, count);
	}
	private void sendImage(HttpServletResponse response, int count){
		try {
			response.setContentType("image/jpeg");
			  ServletOutputStream sos = response.getOutputStream();
BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_RGB);
			  Graphics g = image.getGraphics();
			  g.setColor(Color.BLACK);
			  g.fillRect(0, 0, 80, 20);
			  g.setColor(Color.WHITE);
			  g.setFont(new Font(null, Font.PLAIN|Font.BOLD, 18));
			  g.drawString(String.valueOf(count), 0, 18);
			  g.dispose();
			  
			  ImageIO.write(image, "JPEG", sos);
			  sos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private void sendText(HttpServletResponse response, int count){
		try {
			response.setContentType("text/html;charset=GB18030");
			PrintWriter out = response.getWriter();
			out.println("document.write('本页面访问次数为" + count + "')");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private int getCount(HttpServletRequest request) throws Exception{
		  int count = 0;
		  String path = request.getRealPath("/count.txt");
		  FileInputStream fis = new FileInputStream(path);
		  
		  Properties prop = new Properties();
		  prop.load(fis);
		  
		  String fileName = request.getHeader("referer");
		  System.out.println(fileName);
		  String tmp = (String)prop.get(fileName); 
		  if(tmp!=null){
			  count = Integer.parseInt(tmp);
		  }		  
		  count++;
		  FileOutputStream fos = new FileOutputStream(path);
		  prop.put(fileName, new Integer(count).toString());
		  prop.store(fos, "success");
		  fis.close();
		  fos.close();  
		  return count;
	}
}
2、在多个页面中写入相同的一段代码，通过这段代码来访问计数Servlet并得到各自的计数值，代码如下：
<script type="text/javascript" src="/CountServlet"></script>
这段代码中src就指出了哪个访问Servlet。这段代码无非是想访问src指出的路径，然后得到一段javascript代码，这段代码把得到的计数值显示出来，类似如下的代码：

document.write("访问次数为n");

我们可以在servlet中输出上面这段代码即可。

3、需要在CountServlet中得到请求来源页面，并把这个页面的信息作为属性文件的key
得到请求页面的方法是 request.getHeader("referer")，referer是一个特殊的请求头，当通过超链接从一个页面访问另一个页面时，浏览器会自动在请求信息里面加上这个头，告知服务器它来自哪里。
<script type="text/javascript">
	document.write("访问次数为n");
</script>

五. 对日期格式化的例子
  <%
  	DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
  	df.format(new Date());
  	
  	DateFormat df2 = DateFormat.getDateInstance(DateFormat.LONG, request.getLocale());
	df2.format(new Date());
  %>
通过该例子而引出的知识点：
大知识点：抽象类的实例化方法，一是实例化其子类，二是通过getInstance方法得到
小知识点：Locale的作用（包含国家和地区的信息），通过更改浏览器语言选项来演示讲解。