Skip to content

Commit bca0932

Browse files
committed
Update README - v0.0.7
1 parent f7863d8 commit bca0932

File tree

1 file changed

+129
-63
lines changed

1 file changed

+129
-63
lines changed

README.md

Lines changed: 129 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11

22

3-
![Java Express Logo](https://image.ibb.co/mCdxtm/java_express.png)
3+
![Java Express Logo](https://preview.ibb.co/c1SWkx/java_express.png)
44

55

66
[![License MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://choosealicense.com/licenses/mit/)
77

8-
# Getting Started
98
**This project is currently in progress, feel free to [contribute](https://github.com/Simonwep/java-express/graphs/contributors) / [report](https://github.com/Simonwep/java-express/issues) issues! :)**
109

10+
**[0.0.7-alpha](https://github.com/Simonwep/java-express/releases/tag/0.0.7) is ready, check it out!**
11+
1112
```java
1213
Express app = new Express();
1314

@@ -25,21 +26,22 @@ Express app = new Express(Utils.getYourIp());
2526
```
2627
Default is localhost, so you can access, without setting the hostname, only from your local pc.
2728

28-
Docs:
29+
Docs (v0.0.7-beta):
2930
* [Routing](#routing)
30-
* [Direct](#direct)
31-
* [With Router](#with-router)
31+
* [Direct](#direct)
32+
* [With Router](#with-router)
3233
* [URL Basics](#url-basics)
3334
* [URL Parameter](#url-parameter)
3435
* [URL Parameter Listener](#url-parameter-listener)
3536
* [URL Querys](#url-querys)
3637
* [Cookies](#cookies)
3738
* [Form Data](#form-data)
38-
* [HTTP - Request and Response](#http---request-and-response-object)
39+
* [HTTP - Main Classes](#http---main-classes)
3940
* [Response Object](#response-object)
4041
* [Request Object](#request-object)
4142
* [Middleware](#middleware)
4243
* [Create own middleware](#create-own-middleware)
44+
* [Using local variables](#local-variables)
4345
* [License](#license)
4446

4547
Every following code can be also found in [this package](https://github.com/Simonwep/java-express/tree/master/src/examples).
@@ -59,7 +61,7 @@ app.get("/about", (req, res) -> res.send("About"));
5961
app.get("/user/login", (req, res) -> res.send("Please login!"));
6062
app.get("/user/register", (req, res) -> res.send("Join now!"));
6163

62-
app.listen();
64+
app.listen();
6365
```
6466
It also directly supports directly methods like `POST` `PATCH` `DELETE` and `PUT` others need to be created manually:
6567
```java
@@ -74,7 +76,7 @@ app.put("/user", (req, res) -> res.send("Add an user!"));
7476
// Example fot the CONNECT method
7577
app.on("/user", "CONNECT", (req, res) -> res.send("Connect!"));
7678

77-
app.listen();
79+
app.listen();
7880
```
7981

8082
## With Router
@@ -90,14 +92,16 @@ indexRouter.get("/about", (req, res) -> res.send("About"));
9092

9193
// Define router for user pages
9294
ExpressRouter userRouter = new ExpressRouter();
93-
userRouter.get("/user/login", (req, res) -> res.send("User Login"));
94-
userRouter.get("/user/register", (req, res) -> res.send("User Register"));
95-
userRouter.get("/user/:username", (req, res) -> res.send("You want to see: " + req.getParam("username")));
95+
userRouter.get("/", (req, res) -> res.send("User Page"));
96+
userRouter.get("/login", (req, res) -> res.send("User Login"));
97+
userRouter.get("/register", (req, res) -> res.send("User Register"));
98+
userRouter.get("/:username", (req, res) -> res.send("You want to see: " + req.getParam("username")));
9699

97-
// Add roter
98-
app.use(indexRouter);
99-
app.use(userRouter);
100+
// Add router and set root paths
101+
app.use("/", indexRouter);
102+
app.use("/user", userRouter);
100103

104+
// Start server
101105
app.listen();
102106
```
103107

@@ -141,7 +145,7 @@ app.onParam("id", (req, res) -> {
141145
Now, this function will be called every time when an context is requested which contains the `id` parameter placeholder.
142146

143147
## URL Querys
144-
If you make an request which contains querys, you can access the querys over `req.getQuery(NAME)`.
148+
If you make an request which contains querys, you can access the querys over `req.getQuery(NAME)`.
145149

146150
Example request: `GET` `/posts?page=12&from=john`:
147151
```java
@@ -191,52 +195,93 @@ app.post("/register", (req, res) -> {
191195
String email = req.getFormQuery("email");
192196
String username = req.getFormQuery("username");
193197
// Process data
194-
198+
195199
// Prints "E-Mail: [email protected], Username: john"
196-
res.send("E-Mail: " + email + ", Username: " + username);
200+
res.send("E-Mail: " + email + ", Username: " + username);
197201
});
198202
```
199203

200-
# HTTP - Request and Response object
204+
# HTTP - Main Classes
205+
## Express
206+
This class represents the entire HTTP-Server:
207+
```java
208+
app.get(String context, HttpRequest handler); // Add an GET request handler
209+
app.post(String context, HttpRequest handler); // Add an POST request handler
210+
app.patch(String context, HttpRequest handler); // Add an PATCH request handler
211+
app.put(String context, HttpRequest handler); // Add an PUT request handler
212+
app.delete(String context, HttpRequest handler); // Add an DELETE request handler
213+
app.all(HttpRequest handler); // Add an handler for all methods and contexts
214+
app.all(String context, HttpRequest handler); // Add an handler for all methods but for an specific context
215+
app.all(String context, String method, HttpRequest handler); // Add an handler for an specific method and context
216+
app.use(String context, String method, HttpRequest handler); // Add an middleware for an specific method and context
217+
app.use(HttpRequest handler); // Add an middleware for all methods but for an specific context
218+
app.use(String context, HttpRequest handler); // Add an middleware for all methods and contexts
219+
app.use(String context, ExpressRouter router); // Add an router for an specific root context
220+
app.use(ExpressRouter router); // Add an router for the root context (/)
221+
app.onParam(String name, HttpRequest handler); // Add an listener for an specific url parameter
222+
app.getParameterListener(); // Returns all parameterlistener
223+
app.get(String key); // Get an environment variable
224+
app.set(String key, String val); // Set an environment variable
225+
app.isSecure(); // Check if the server uses HTTPS
226+
app.setExecutor(Executor executor); // Set an executor service for the request
227+
app.listen(); // Start the async server on port 80
228+
app.listen(ExpressListener onstart); // Start the async server on port 80, call the listener after starting
229+
app.listen(int port); // Start the async server on an specific port
230+
app.listen(ExpressListener onstart, int port); // Start the async server on an specific port call the listener after starting
231+
app.stop(); // Stop the server and all middleware worker
232+
```
201233

202234
## Response Object
203235
Over the response object, you have serveral possibility like setting cookies, send an file and more. Below is an short explanation what methods exists:
236+
(We assume that `res` is the `Response` object)
237+
204238
```java
205-
app.get("/res", (req, res) -> {
206-
// res.send(); // Send empty response
207-
// res.send("Hello World"); // Send an string
208-
// res.send("chart.pdf"); // Send an file
209-
// setContentType(MediaType._txt); // Set the content type, default is txt/plain
210-
// getContentType(); // Returns the current content type
211-
// res.setStatus(Status._200); // Set the response status
212-
// res.getStatus(); // Returns the current response status
213-
// res.setCookie(new Cookie(...)); // Send an cookie
214-
// res.isClosed(); // Check if already something has been send to the client
215-
});
239+
res.getContentType(); // Returns the current content type
240+
res.setContentType(MediaType type); // Set the content type with enum help
241+
res.setContentType(String type); // Set the content type
242+
res.isClosed(); // Check if the response is already closed
243+
res.getHeader(String key); // Get the value from an header field via key
244+
res.setHeader(String key, String val); // Add an specific response header
245+
res.send(String str); // Send an string as response
246+
res.send(Path path); // Send an file as response
247+
res.send(); // Send empty response
248+
res.redirect(String location); // Redirect the request to another url
249+
res.setCookie(Cookie cookie); // Add an cookie to the response
250+
res.sendStatus(Status status); // Set the response status and send an empty response
251+
res.getStatus(); // Returns the current status
252+
res.setStatus(Status status); // Set the repose status
216253
```
217254
The response object calls are comments because **you can only call the .send(xy) once each request!**
218255

219256
## Request Object
220-
With the request object you receive serveral data from the client which can be easily parsed by the given functions:
257+
Over the `Request` Object you have access to serveral request stuff (We assume that `req` is the `Request` object):
258+
221259
```java
222-
app.get("/req/", (req, res) -> {
223-
// req.getURI(); // Request URI
224-
// req.getHost(); // Request host (mostly localhost)
225-
// req.getMethod(); // Request method (here GET)
226-
// req.getContentType(); // Request content description, is here null because it's an GET request
227-
// req.getBody(); // Request body inputstream
228-
// req.getUserAgent(); // Request user-agent
229-
// req.getParam("parameter"); // Returns an url parameter
230-
// req.getQuery("queryname"); // Returns an url query by key
231-
// req.getFormQuery("formqueryname"); // Returns an form input value
232-
// req.getFormQuerys(); // Returns all form querys
233-
// req.getCookie("user"); // Returns an cookie by name
234-
// req.getCookies(); // Returns all cookies
235-
// req.hasAuthorization(); // Check if the request contains an authorization header
236-
// req.getAuthorization(); // Returns the authorization header
237-
// req.getMiddlewareContent("name"); // Returns data from middleware
238-
// req.pipe(new OutputStream() {...}); // Pipe the body to an outputstream
239-
});
260+
req.getAddress(); // Returns the INET-Adress from the client
261+
req.getMethod(); // Returns the request method
262+
req.getPath(); // Returns the request path
263+
req.getQuery(String name); // Returns the query value by name
264+
req.getHost(); // Returns the request host
265+
req.getContentLength(); // Returns the content length
266+
req.getContentType(); // Returns the content type
267+
req.getMiddlewareContent(String name); // Returns the content from an middleware by name
268+
req.getFormQuerys(); // Returns all form querys
269+
req.getParams(); // Returns all params
270+
req.getQuerys(); // Returns all querys
271+
req.getFormQuery(String name); // Returns the form value by name
272+
req.getHeader(String key); // Returns the value from an header field by name
273+
req.getParam(String key); // Returns the url parameter by name
274+
req.getApp(); // Returns the related express app
275+
req.getCookie(String name); // Returns an cookie by his name
276+
req.getCookies(); // Returns all cookies
277+
req.getIp(); // Returns the client IP-Address
278+
req.getUserAgent(); // Returns the client user agent
279+
req.getURI(); // Returns the request URI
280+
req.getAuthorization(); // Returns the request authorization
281+
req.hasAuthorization(); // Check if the request has an authorization
282+
req.pipe(OutputStream stream, int buffersize); // Pipe the request body to an outputstream
283+
req.pipe(Path path, int buffersize); // Pipe the request body to an file
284+
req.getBody(); // Returns the request inputstream
240285
```
241286

242287
# Middleware
@@ -251,21 +296,21 @@ For example an middleware for all [request-methods](https://developer.mozilla.or
251296
```java
252297
// Global context, matches every request.
253298
app.use((req, res) -> {
254-
// Handle data
299+
Handle data
255300
});
256301
```
257302
You can also filter by [request-methods](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) and contexts:
258303
```java
259304
// Global context, you can also pass an context if you want
260305
app.use("/home", "POST", (req, res) -> {
261-
// Handle request by context '/home' and method 'POST'
306+
Handle request by context '/home' and method 'POST'
262307
});
263308
```
264309
In addition to that yo can use `*` which stands for every **context** or **request method**:
265310
```java
266311
// Global context, you can also pass an context if you want
267312
app.use("/home", "*", (req, res) -> {
268-
// Handle request which matches the context '/home' and all methods.
313+
Handle request which matches the context '/home' and all methods.
269314
});
270315
```
271316
## Create own middleware
@@ -312,24 +357,39 @@ No we can, as we learned above, include it with:
312357
app.use(new PortMiddleware());
313358
```
314359
## Existing Middlewares
315-
There are already some basic middlewares included, you can access these via static methods provided from `Express`.
360+
There are already some basic middlewares included, you can access these via static methods provided from `Middleware`.
316361

317-
#### Static File serving
318-
If you want to allocate some files, like js-librarys or css files you can use the [static](https://github.com/Simonwep/java-express/blob/master/src/express/middleware/Static.java) middleware. But you can also provide other files like mp4 etc.
362+
#### Provide static Files
363+
If you want to allocate some files, like js-librarys or css files you can use the [static](https://github.com/Simonwep/java-express/blob/master/src/express/middleware/Middleware.java) middleware. But you can also provide other files like mp4 etc.
319364
Example:
320365
```java
321-
app.use(Express.statics("examplepath\\test_statics"));
366+
app.use(Middleware.statics("examplepath\\myfiles"));
322367
```
323-
Now you can access every files in the `test_statics` over the root adress `\`. If you want you can specify which files can be accessed:
368+
Now you can access every files in the `test_statics` over the root adress `\`. I'ts also possible to set an configuration for the FileProvider:
324369
```java
325-
app.use(Express.statics("examplepath\\test_statics", "html", "css", "js"));
370+
FileProviderOptionsoptions = new FileProviderOptions();
371+
options.setExtensions("html", "css", "js"); // By default, all are allowed.
372+
/*
373+
* Activate the fallbacksearch.
374+
* E.g. if an request to <code>/js/code.js</code> was made but the
375+
* requested ressource cannot be found. It will be looked for an file called <code>code</code>
376+
* and return it.
377+
*
378+
* Default is false
379+
*/
380+
options.setFallBackSearching(true);
381+
options.setHandler((req, res) -> {...}); // Can be used to handle the request before the file will be returned.
382+
options.setLastModified(true); // Send the Last-Modified header, by default true.
383+
options.setMaxAge(10000); // Send the Cache-Control header, by default 0.
384+
options.setDotFiles(DotFiles.DENY); // Deny access to dot-files. Default is IGNORE.
385+
app.use(Middleware.statics("examplepath\\myfiles", new FileProviderOptions())); // Using with StaticOptions
326386
```
327387
#### Cookie Session
328-
Java Express also includes an simple cookie-session middleware:
388+
There is also an simple cookie-session implementation:
329389
```java
330390
// You should use an meaningless cookie name for serveral security reasons, here f3v4.
331391
// Also you can specify the maximum age of the cookie from the creation date and the file types wich are actually allowed.
332-
app.use(Express.cookieSession("f3v4", 9000));
392+
app.use(Middleware.cookieSession("f3v4", 9000));
333393
```
334394
To use a session cookie we need to get the data from the middleware which is actually an `SessionCookie`:
335395
```java
@@ -343,7 +403,7 @@ app.get("/session", (req, res) -> {
343403
SessionCookie sessionCookie = (SessionCookie) req.getMiddlewareContent("sessioncookie");
344404
int count;
345405

346-
// Check if the data is null, we want to implement an simple counter
406+
Check if the data is null, we want to implement an simple counter
347407
if (sessionCookie.getData() == null) {
348408

349409
// Set the default data to 1 (first request with this session cookie)
@@ -354,11 +414,17 @@ app.get("/session", (req, res) -> {
354414
count = (Integer) sessionCookie.setData((Integer) sessionCookie.getData() + 1);
355415
}
356416

357-
// Send an info message
417+
Send an info message
358418
res.send("You take use of your session cookie " + count + " times.");
359419
});
360420
```
361-
421+
## Local Variables
422+
Java-express also supports to save and read local variables over the Express instance:
423+
Example:
424+
```java
425+
app.set("my-data", "Hello World");
426+
app.get("my-data"); // Returns "Hello World"
427+
```
362428
# License
363429

364-
This project is licensed under the MIT License - see the [LICENSE.md](https://choosealicense.com/licenses/mit/) file for details
430+
This project is licensed under the MIT License - see the [LICENSE.md](https://choosealicense.com/licenses/mit) file for details

0 commit comments

Comments
 (0)