当前位置: 代码迷 >> Web前端 >> servlet学习札记
  详细解决方案

servlet学习札记

热度:235   发布时间:2012-10-26 10:30:59.0
servlet学习笔记
开发工具:
Eclipse、MyEclipse、Oracle、Pl/SQL Developer、Dreamweaver、Editplus
相关组件:
Commons DBCP、Commons DbUtils、Commons Email、Commons FileUpload、Log4J、FCKEditor

Tcp/Ip四层结构
网络接口层 (Network Interface Layer)
网络层 (Network Layer)
传输层 (Transport Layer)
应用层 (Application Layer)

应用层常用协议:HTTP、Telnet、Ftp、SMTP、POP3

URL :http://www.sinosoft.com/CMS/index.jsp
http://代表超文本传输协议
www 代表world wild web服务
sinosoft.com 域名/Ip地址/web服务器名称
/CMS web服务器上子目录名称
/index.jsp jsp页面名称

https是http的安全版本

web服务器(Server端)
常用的文本服务器Apache、IIS、Tomcat
常用的应用服务器Tomcat、Resin、WebLogic Server、WebSphere、JBoss

浏览器(Client端)

CGI(Common Gateway Interface)
Servlet
Socket开发框架MINA和Cindy框架

ctrl+shift+f 格式化

第二章Servlet起源
实例1
新建一个java project
写两个文件WebServer.java
package com.wdd;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class WebServer {

public void serverStart(int port) {
try {
ServerSocket serversocket = new ServerSocket(port);
while (true) {
Socket socket = serversocket.accept();
new Processor(socket).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
int port = 80;
if (args.length == 1) {
port = Integer.parseInt(args[0]);
}
new WebServer().serverStart(port);
}
}
Processor.java
package com.wdd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class Processor extends Thread {
private Socket socket;
private InputStream in;
private PrintStream out;
public final static String Web_Root="d:\\wdd\\WebServer\\htdocs";
public Processor(Socket socket) {
this.socket = socket;
try {
in = socket.getInputStream();
out = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}

public void run() {
String fileName = parse(in);
sendFile(fileName);
}

public String parse(InputStream in) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String fileName = null;
try {
String httpMessage = br.readLine();
String[] content = httpMessage.split(" ");// 三个部分
// 协议的状态号、协议名称、协议版本号
if (content.length != 3) {
sendErrorMessage(400, "client query error");// 400请求错误
return null;
}
System.out.println("code:" + content[0]);
System.out.println("fileName:" + content[1]);
System.out.println("http version:" + content[2]);
fileName = content[1];
} catch (IOException e) {
e.printStackTrace();
}
return fileName;
}

public void sendErrorMessage(int errorCode, String errorMessage) {
out.println("HTTP/1.0 "+errorCode+" "+errorMessage);//200成功返回
out.println("content-type: text/html");
out.println();
out.println("<html>");
out.println("<title>Error Message");
out.println("</title>");
out.println("<body>");
out.println("<h1>ErrorCode: "+errorCode+","+errorMessage+"</h1>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void sendFile(String fileName) {
File file = new File(Processor.Web_Root+fileName);
if(!file.exists()){
sendErrorMessage(404,"File Not Find");//404 请求内容不存在
return;
}
try {
InputStream in = new FileInputStream(file);
byte content[] = new byte[(int)file.length()];
in.read(content);
out.println("HTTP/1.0 200 queryFile");//200成功返回
out.println("content.length:"+content.length);
out.println();
out.write(content);
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
监听80端口在客户端也就是浏览器输入http://localhost/ welcome.html
welcome.html 请求的文件名
控制台输出:
code:GET
fileName:/welcome.html
http version:HTTP/1.1

第三章:Servlet编程
java子平台:
Java SE标准版的Java平台 Standard Edition
Java EE J2EE企业级Enterprise Edition
Java ME是为机顶盒、移动电话和PDA之类嵌入式消费电子设备提供的Java语言平台Micro Edition
servlet是一个标准的服务器端运行的应用程序,它可以执行商务逻辑,处理http请求。
设计模式:模板设计模式

javax.servlet 定义通用的servlet接口和类
javax.servlet.http 定义servlet对于http接口和类

servlet是一个接口,GenericServlet实现了这个接口,然后httpServlet是继承GenericServlet。

编写servlet步骤
1. 新建web project
2. 建立servlet文件
3. 部署web应用程序
4. 运行输出
5. Servlet文件调试

实例3.1
HelloServlet.java

package com.chapter3.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");//返回内容类型
PrintWriter out = resp.getWriter();//得到out对象
out.println("<html>");
out.println("<head>");
out.println("<title>my first servlet.</title>");
out.println("<body>");
out.println(new Date());
out.println("Welcome");
out.println("</body>");
out.println("</head>");
out.println("</html>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.chapter3.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

设置MyEclipse
先看tomcat 在看jdk
自动配置servlet
加一个serialVersionUID

servlet生命周期
init()
service()
destroy()
实例3通过servlet获取初始化参数
具体步骤:
新建GetInitParameterServlet类
运行输出
web.xml
<servlet>
    <servlet-name>GetInit</servlet-name>
    <servlet-class>com.chapter3.servlet.GetInitParameterServlet</servlet-class>
    <init-param>
    <param-name>repeat</param-name>
    <param-value>10</param-value>
    </init-param>
  </servlet>

获取
int repeat = Integer.parseInt(this.getInitParameter("repeat"));

实例4通过servlet获取服务器的运行信息
具体步骤:
新建GetServerInfoServlet类
运行输出
方法
out.println("server name:"+request.getServerName()+"</br>");
out.println("server ip:"+request.getRemoteAddr()+"</br>");
out.println("server port:"+request.getServerPort()+"</br>");
out.println("server Protocol:"+request.getProtocol()+"</br>");
out.println("server ContextPath:"+request.getContextPath()+"</br>");
out.println("server Scheme:"+request.getScheme()+"</br>");
out.println("server Method:"+request.getMethod()+"</br>");
out.println("server RequestURI:"+request.getRequestURI()+"</br>");
out.println("server ServletPath:"+request.getServletPath()+"</br>");

server name:localhost
server ip:127.0.0.1
server port:8080
server Protocol:HTTP/1.1
server ContextPath:/ServletAndJsp
server Scheme:http
server Method:GET
server RequestURI:/ServletAndJsp/servlet/GetServerInfo
server ServletPath:/servlet/GetServerInfo

实例5通过servlet获取头信息
具体步骤:
新建GetHeaderInfoServlet类
运行输出

Enumeration e = request.getHeaderNames();
String name = null;
while(e.hasMoreElements()){
name = (String)e.nextElement();
out.println("name:"+name);
out.println("value:"+request.getHeader(name)+"</br>");

}
name:host value:localhost:8080
name:user-agent value:Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101130 Firefox/3.6.13
name:accept value:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
name:accept-language value:zh-cn,zh;q=0.5
name:accept-encoding value:gzip,deflate
name:accept-charset value:GB2312,utf-8;q=0.7,*;q=0.7
name:keep-alive value:115
name:connection value:keep-alive
name:cache-control value:max-age=0


  相关解决方案