Skip to content

MikkelHelsing/Java-HTTP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

51 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java-HTTP

Building an HTTP routing system with inspiration from Express.js.

Load order

Middleware and routes will be loaded in the order they are specified, and all dynamics using annotations will be loaded last. Meaning if a middleware is important at the start, add it in code at the beginning before the use of listen.
It is therefore also important to add predefined middlewares like Session, at the start to ensure it gets ran before other middleware.

Functionality

Creating New HTTP Server & Router

JXpress jXpress = new JXpress();

Start server:

jXpress.listen(int port);

Print Route Tree:

Can also be done for individual routers

jXpress.printRouteTree();

Set 404 route

jXpress.set404((request, response) -> void);

Basic

GET

jXpress.get(String path, (request, response) -> void);

POST

jXpress.post(String path, (request, response) -> void);

PUT

jXpress.put(String path, (request, response) -> void);

DELETE

jXpress.delete(String path, (request, response) -> void);

Routing

The router has the same functionality as the main JXpress

Creating a route:

Router router = new Router();
// Add it to the pool of routes
jXpress.use(String path, router);

File and Folder Provider

File

jXpress.use(String path, new FileReader(Path pathToFile));

Web Folder

jXpress.webFolder(String path, String folderPath);

Public Folder

Will provide all files and sub-folders files on the base path of "/".

jXpress.publicFolder(String folderPath);

Middleware

Custom

jXpress.use((request, response) -> void);

Middleware using annotations

Creating a class as such, it will automatically get added to the worker pool

//path, the one used below is the default value
@Middleware(path = "/")
public class className extends Worker

@Middleware
public class className extends Worker

Listen to events

On Request Closing

The "onClose" function will be called just before the connection is closed.

// Implement the interface
public class <MiddlewareName> extends Worker implements IRequestOnClose

// Start listening
@Override
public void handle(Request request, Response response) {
        response.listenOnClose(this::onClose);
}

Routes using annotations

Creating a class as such, it will automatically get added to the route pool

//path, method, provides all optional, the ones used below are the default values
@Route(path = "/", method = Method.GET, provides = "text/plain")
public class className implements IRequestHandler

@Route
public class className implements IRequestHandler

Request

Method

request.getMethod();

Body

// Get the body as string
request.getRawBody();
// Get the body as byte[]
request.getByteBody();
// Get the body as Json using GSON
request.getJsonBody(Class<?> jsonClass);

Cookies

// Get a cookie
request.getCookie(String key);
// Get all cookies
request.getCookies();

Headers

// Get a header
request.getHeader(String key);
// Get all headers
request.getHeaders();

Parameters

Parameters are send in the url eg. website.com/user ?id=1,2,4&role=admin

// Get a parameter
request.getParameter(String key);
// Get all parameters
request.getParameters();

Middleware Data

A way of keeping track of data throughout handling of requests.

Add data

request.setMiddlewareData(String key, Object data);

Retrieving data

// Get a single value
request.getMiddlewareData(String key);
// Get the entire HashMap
request.getAllMiddlewareData();

Response

Send

Once a message is sent, the stream automatically closes

// Sending data
response.send(String message)
/* Or will use toString */
response.send(Object object)

Close

To stop the stream prematurely use

response.close()

Response Code

// Get the current response code, defaults to 200
response.getResponseCode();
// Set response code
response.setResponseCode(int code);

Content Type

response.setContentType(String type)

Headers

response.addHeader(String header, String value);
response.addHeader(String header, List<String> values);

Cookies

response.addCookie(String key, String value);

Using Cookie Builder

This ensures the cookie format conforms to the HTTP standard.

response.addCookie(CookieBuilder cookieBuilder);

Options:

cookieBuilder.httpOnly();
cookieBuilder.secure();
cookieBuilder.partitioned();
cookieBuilder.expires(LocalDateTime dateTime);
cookieBuilder.maxAge(int maxAge);
cookieBuilder.domain(String domain);
cookieBuilder.path(String path);
cookieBuilder.sameSite(SameSite sameSite);

Example:

response.addCookie(new CookieBuilder("cookieBuilder", "test").maxAge(100).sameSite(CookieBuilder.SameSite.LAX));

Predefined Middleware

Session

Will automatically add or retrieve a session and store it in the middleware data.
The session id is automatically sent to the client to store as a cookie.
Session cookie should remove itself once browser is closed, be aware this depends on the browser implementation.

Adding it

jXpress.use(new Session());

Accessing it

// Getting the session
Session session = (Session) request.getMiddlewareData("session");
// Setting data in the session
session.setSessionData(String key, Object data);
// Retrieving data from the session
session.getSessionData(String key);
// Getting the session key
String sessionKey = (String) request.getMiddlewareData("sessionKey");

File Reader

Exposes a file on a path:

jXpress.use(String path, new FileReader(Path pathToFile));

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published