Skip to content

Route Handling: What can you do when responding to a request?

Joshua Segal edited this page Mar 3, 2021 · 1 revision

There are several functions you can use inside a route handler that come in handy.

Sending data from a file

Sometimes, you just don't feel in the mood to send text. You want to send a file, whether that's a HTML file, or an image, or even a video.

In this situation, you can use the response.readContentFromFile(fileName)

import com.devsegal.jserve.HTTPServer;
import com.devsegal.jserve.ResponseHeaders;
import java.util.Map;

HTTPServer server = new HTTPServer(8080);

server.setupOriginalServerPath("path/to/server/folder"); // Where all files (by default) originate from. This excludes asset files, like css files, where you'd want to use the setupPublicAssetFolder method instead.

server.route("/homepage", "GET", (request, response) -> {
  
  try {
      response.setResponseHeaders(new ResponseHeaders("text/html", "close"); 
  } catch(ResponseStatusNullException e) {
      e.printStackTrace();
  } 
  
  response.readContentFromFile("index.html");
});

Accessing headers

You can get a request's headers using the request.getHeaders method.

import com.devsegal.jserve.HTTPServer;
import com.devsegal.jserve.ResponseHeaders;
import java.util.Map;

HTTPServer server = new HTTPServer(8080);

server.route("/homepage", "GET", (request, response) -> {
  Map<String, String> headers = request.getHeaders();
  System.out.println("User agent: " + headers.get("User-Agent"));
});

Accessing a url's parameters

If you want to get data from the url, like this websitename.com/helloworld?id=992, and get id for example, you can do so using the getParameters method of the request.

import com.devsegal.jserve.HTTPServer;
import com.devsegal.jserve.ResponseHeaders;
import java.util.Map;

HTTPServer server = new HTTPServer(8080);

server.route("/helloworld", "GET", (request, response) -> {
  Map<String, String> parameters = request.getParameters();
  System.out.println(parameters.get("key");
});

Accessing POST request data

If you want to access the data sent with a POST request, you can access it using the getPostData method of the request.

import com.devsegal.jserve.HTTPServer;
import com.devsegal.jserve.ResponseHeaders;
import java.util.Map;

HTTPServer server = new HTTPServer(8080);

server.route("/homepage", "GET", (request, response) -> {
  Map<String, String> postData = request.getPostData();
  System.out.println("Password: " + postData.get("password"));
});