public class web {
public static void main(String args[]){
try{Service service=new Service();
ServerSocket server=new ServerSocket(80);
service.setServerSocket(server);
service.start();
}
catch(Exception e){
System.out.println(7);
}
}}
class Service extends Thread{
ServerSocket socket;
Socket ser;
String path;File file;String context="";
public void setServerSocket(ServerSocket socket){
this.socket=socket;
}
public void run(){
try{
ser=socket.accept();
Service service=new Service();
service.setServerSocket(socket);
service.start();
InputStream in=ser.getInputStream();
InputStreamReader r=new InputStreamReader(in);
BufferedReader br=new BufferedReader(r);
String readLine=br.readLine();
while(readLine!=null&&!readLine.equals("")){
if(readLine.startsWith("GET"))
path=readLine.substring(4,readLine.length()-9);
System.out.println("获取到的数据"+readLine);
readLine=br.readLine();
}
OutputStream output=ser.getOutputStream();
String html="HTTP/1.1 200 ok\n\n";
output.write(html.getBytes());
System.out.println(path);
if(path.endsWith(".do")){
path=path.substring(1,path.length()-3);
path="test."+path;
System.out.println("ok"+path);
Servlet servlet=(Servlet)Class.forName(path).newInstance();//Servlet是自己写的的类
Response response=new Response();
response.setOutputStream(output);
servlet.service( response);
}
else{
path="D:/web_ceshi"+path;
if(path!=null)
file=new File(path);
int t=0;
if(file!=null&&file.exists()){
FileInputStream fileinput=new FileInputStream(file);
ByteArrayOutputStream bytearray=new ByteArrayOutputStream();
while((t=fileinput.read())!=-1){
bytearray.write(t);
}
output.write(bytearray.toString().getBytes());
fileinput.close();
}
}
output.close();
in.close();
}
catch(Exception e){
System.out.println(1);
}
}
}
public class first implements Servlet{
public void service( Response arg1) {
// TODO Auto-generated method stub
try{
arg1.getOutputStream().write("ok".getBytes());}
catch(IOException e){
System.out.println("error");
}
}
}
interface Servlet{
public void service(Response arg1);
}
class Response{
OutputStream output;
public void setOutputStream(OutputStream output){
this.output=output;
}
public OutputStream getOutputStream(){
return output;
}
}
serversocket实现动态网页
最新推荐文章于 2022-01-12 23:24:45 发布