Boa tarde pessoal,
Estou com um problema aqui. Tenho um trabalho de faculdade onde o objetivo é implementar um servidor web multithread em Java
com o método Get e o Get Condicional.
Já o implementei com o método Get, meu problema agora é implementar o método get condicional. Já procurei em muitos lugares orientações
de como se implementar esse método mas não encontrei nenhuma direção. Sei como ele funciona, só não sei como implementá-lo no lado servidor.
Aos que puderem me ajudar, segue o código que já implementei.
Classe HttpRequest.java
[code]package servidorwebmultithread;
import java.io.;
import java.net.;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
- To change this template, choose Tools | Templates
- and open the template in the editor.
*/
/**
*
-
@author cristiane
*/
public class HttpRequest implements Runnable{Socket socket;
static String nomeArquivo = null;public HttpRequest(Socket socket) throws Exception{
this.socket = socket;}
public void run() {
try{
processRequest();
}catch(Exception e){
Logger.getLogger(WebServer.class.getName()).log(Level.SEVERE, null, e);
}
}private void processRequest() throws Exception{
InputStreamReader input = new InputStreamReader(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());BufferedReader entradaDoCliente = new BufferedReader(input); String linhaRequisicao = entradaDoCliente.readLine(); StringTokenizer tokens = new StringTokenizer(linhaRequisicao); tokens.nextToken(); //Captura o nome do arquivo nomeArquivo = tokens.nextToken(); //É necessário acrescentar um . ao nome do arquivo para dizer que este está no diretório atual nomeArquivo = "." + nomeArquivo; //Abrir o arquivo requisitado FileInputStream inputArquivo = null; Boolean arquivoExiste = true; try{ inputArquivo = new FileInputStream(nomeArquivo); }catch(FileNotFoundException e){ arquivoExiste = false; } //Mensagem de Resposta String linhaStatus = null; String linhaContentType = null; String corpoEntidade = null; if(arquivoExiste){ linhaStatus = "HTTP/1.1 200 OK" + "\r\n"; linhaContentType = "Content-type: " + contentType(nomeArquivo) + "\r\n"; }else{ linhaStatus = "HTTP/1.1 404 Not Found" + "\r\n"; linhaContentType = "Content-Type: text/html" + "\r\n"; corpoEntidade = "<HTML><HEAD><TITLE>Objeto Não Encontrado</TITLE></HEAD> " + "<BODY><h1><b>Not Found</b></h1><br><br>Objeto Não Encontrado</BODY></HTML>"; } //Enviar a linha de Status output.writeBytes(linhaStatus); //Enviar Linha de Content-Type output.writeBytes(linhaContentType); //Enviar linha em branco para marcar o fim das linhas de cabeçalho output.writeBytes("\r\n"); //Enviar Corpo da Entidade if(arquivoExiste){ sendBytes(inputArquivo, output); inputArquivo.close(); }else{ output.writeBytes(corpoEntidade); } /*/Exibe a linha de requisição System.out.println(); System.out.println(linhaRequisicao); //Exibe as linhas de cabeçalho String linhasCabecalho = null; while((linhasCabecalho = entradaDoCliente.readLine()).length() != 0){ System.out.println(linhasCabecalho); }*/ //Fecha as cadeias e o socket output.close(); input.close(); socket.close(); }
private static void sendBytes(FileInputStream inputArquivo, OutputStream output) throws Exception{
//Buffer de 1K para comportar os bytes no caminho para o socket
byte[] buffer = new byte[1024];
int bytes = 0;
//Cópia do arquivo requisitado dentro da cadeia do socket
while((bytes = inputArquivo.read(buffer)) != -1){
output.write(buffer, 0, bytes);
}
}private static String contentType(String nomeArquivo){
if(nomeArquivo.endsWith(".htm") || nomeArquivo.endsWith(".html")){ return "text/html"; } if(nomeArquivo.endsWith(".jpeg")){ return "image/jpeg"; } if(nomeArquivo.endsWith(".jpg")){ return "image/jpg"; } if(nomeArquivo.endsWith("gif")){ return "image/gif"; } return "application/octet-stream";
}
}[/code]
Classe WebServer.java
[code]package servidorwebmultithread;
import java.net.*;
/*
- To change this template, choose Tools | Templates
- and open the template in the editor.
*/
/**
*
-
@author cristiane
*/
public final class WebServer {/**
-
@param args the command line arguments
*/
public static void main(String[] args) throws Exception{//Definição de porta
int porta = 1225;//Estabelecimento de socket para escuta
ServerSocket welcomeSocket = new ServerSocket(porta);while(true){
Socket socketConexao = welcomeSocket.accept();//Objeto para processar a mensagem de requisição HTTP
HttpRequest requisicao = new HttpRequest(socketConexao);
Thread thread = new Thread(requisicao);//Iniciar a thread
thread.start();}
}
-
}[/code]
Desde já, muito obrigada…