java - Removing redundant code from http server, filehandler -
i have set webserver, time being localhost, @ port 8080 testing.
public class webserver { static int port = 8080; //not final port static string ip = "127.0.0.1"; // not final ip public static void main(string[] args) throws ioexception { inetsocketaddress = new inetsocketaddress(ip, port); //localhost - 127.0.0.1 httpserver server = httpserver.create(i, 0); server.createcontext("/tester", new testhandler("index.html")); server.createcontext("/startpage", new pageshandler()); server.createcontext("/online", new onlinehandler()); server.createcontext("/logfile", new logfilehandler()); server.setexecutor(null); server.start(); } i have seperate handler each of page references, basicly same thing. example pageshandler()
static class pageshandler implements httphandler { string content = "public/"; @override public void handle(httpexchange he) throws ioexception { file file = new file(content + "index.html"); byte[] bytestosend = new byte[(int) file.length()]; try { bufferedinputstream bis = new bufferedinputstream(new fileinputstream(file)); bis.read(bytestosend, 0, bytestosend.length); } catch (ioexception ie) { ie.printstacktrace(); } he.sendresponseheaders(200, bytestosend.length); try (outputstream os = he.getresponsebody()) { os.write(bytestosend, 0, bytestosend.length); } } } this makes me have lot of redundant code, dont see need for. question is. guessing there way parse handler filename, instead of hardcodeded filename in file file,
but how go doing that? constructor of handler string parameter filename do? so
public pageshandler(string filename){ } and in main this:
server.createcontext("/tester", new testhandler("index.html")); and if not how go reducing rudandant code ?
Comments
Post a Comment