-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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");
});
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"));
});
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");
});
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"));
});