Java Servlet获得HTTP请求消息的内容
2009-10-25 16:35:22 来源:WEB开发网两个java类一个jsp:
ServerAccept负责监听接口8091,当客户端与端口建立连接时,该类通过一个新线程启动ServerEchoRequest类处理请求内容,并保存在目录下的request.text中。
1.ServerAccept:
/**
*
* @author lucifer
*/
import java.net.*;
import java.io.*;
public class ServerAccept implements Runnable{
final static int LISTEN_PORT = 8091;
public void run(){
ServerSocket server = null;
try{
server = new ServerSocket(LISTEN_PORT);
System.out.PRintln("正在等待连接");
}
catch(IOException e){
System.out.println("不能连接到端口:" +
LISTEN_PORT + ":" +
e.getMessage());
System.exit(0);
}
while(true){
try{
new Thread(new ServerEchoRequest(server.accept())).start();
System.out.println("启用一个连接");
}
catch(IOException e){
System.out.println("不能接受数据:" + e.getMessage());
}
}
}
public static void main(String[] args){
new Thread(new ServerAccept()).start();
}
}
2.ServerEchoRequest:
/**
*
* @author lucifer
*/
import java.io.*;
import java.net.*;
public class ServerEchoRequest implements Runnable{
Socket m_socket = null;
final static int MAX_BUFF = 4000;
private final static int TIMEOUT = 3000;
public ServerEchoRequest(Socket socket)throws SocketException{
m_socket = socket;
}
public void run(){
try{
getClient(m_socket);
}
catch(IOException e){
System.out.println(e);
System.exit(0);
}
catch(ClassNotFoundException ex){
System.out.println(ex);
System.exit(0);
}
}
protected void getClient(Socket socket)throws IOException,ClassNotFoundException{
DataInputStream in = new DataInputStream(m_socket.getInputStream());
String s;
File f =new File("request.text");
PrintWriter fileout = new PrintWriter(new FileWriter(f));
while((s = in.readLine())!=null){
System.out.println(s);
fileout.println(s);
fileout.flush();
}
}
}
3.JSP页:
<%--
Document : index
Created on : 2009-10-9, 19:13:43
Author : lucifer
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form method="post" action="http://localhost:8091" enctype="multipart/form-data">
<input type="text" name="fileID" size="20"><br>
<input type="file" name="FileData" size="20"><br>
<input type="submit" name="submitfile" value="Upload">
</form>
</body>
</html>
更多精彩
赞助商链接