Skip to content

Commit 80bcfab

Browse files
committed
Add Examples / edit README / remove tests
1 parent 48f2536 commit 80bcfab

File tree

8 files changed

+290
-226
lines changed

8 files changed

+290
-226
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,6 @@
2424
hs_err_pid*
2525

2626
*.idea
27-
*.iml
27+
*.iml
28+
29+
/src/tests

README.md

Lines changed: 133 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
2+
13
![Java Express Logo](https://image.ibb.co/mCdxtm/java_express.png)
24

35
Small clone of the node-js express framework written in pure Java 8.
@@ -11,25 +13,26 @@ If you have downloaded the lastest [release](https://github.com/Simonwep/java-ex
1113
Express app = new Express();
1214

1315
app.get("/", (req, res) -> {
14-
res.send("Hello World");
16+
res.send("Hello World");
1517
});
1618

1719
app.listen(3000);
1820
```
1921
First of all we've create an new Express instance, named `app` then we create an root context `/` for the request-method `get`.
2022
Quick reference:
2123
* [URL Basics](#url-basics)
22-
* [URL Parameter](#url-parameter)
23-
* [URL Querys](#url-querys)
24-
* [Cookies](#cookies)
25-
* [Form Data](#form-data)
24+
* [URL Parameter](#url-parameter)
25+
* [URL Querys](#url-querys)
26+
* [Cookies](#cookies)
27+
* [Form Data](#form-data)
2628
* [HTTP - Request and Response object](#http---request-and-response-object)
27-
* [Response Object](#response-object)
28-
* [Request Object](#request-object)
29+
* [Response Object](#response-object)
30+
* [Request Object](#request-object)
2931
* [Middleware](#middleware)
30-
* [Tutorial](#tutorial)
32+
* [Create own middleware](#create-own-middleware)
3133
* [License](#license)
3234

35+
Every following code can be also found in [this package](https://github.com/Simonwep/java-express/tree/master/src/examples).
3336
# URL Basics
3437

3538
## URL Parameter
@@ -38,9 +41,9 @@ Sometime you want to create dynamic URL where some parts of the URL's are not st
3841
Example request: `GET` `/posts/john/all`:
3942
```java
4043
app.get("/posts/:user/:type", (req, res) -> {
41-
String user = req.getParam("user"); // Contains 'john'
42-
String type = req.getParam("type"); // Contains 'all'
43-
res.send("User: " + user + ", type: " + type); // Send: "User: john, type: all"
44+
String user = req.getParam("user"); // Contains 'john'
45+
String type = req.getParam("type"); // Contains 'all'
46+
res.send("User: " + user + ", type: " + type); // Send: "User: john, type: all"
4447
});
4548
```
4649

@@ -50,9 +53,9 @@ If you make an request which contains querys, you can access the querys over `re
5053
Example request: `GET` `/posts?page=12&from=john`:
5154
```java
5255
app.get("/posts", (req, res) -> {
53-
String page = req.getQuery("page"); // Contains '12'
54-
String from = req.getQuery("from"); // Contains 'John'
55-
res.send("Page: " + page + ", from: " + from); // Send: "Page: 12, from: John"
56+
String page = req.getQuery("page"); // Contains '12'
57+
String from = req.getQuery("from"); // Contains 'John'
58+
res.send("Page: " + page + ", from: " + from); // Send: "Page: 12, from: John"
5659
});
5760
```
5861

@@ -62,18 +65,18 @@ With `req.getCookie(NAME)` you can get an cookie by his name, and with `res.setC
6265
Example request: `GET` `/setcookie`:
6366
```java
6467
app.get("/setcookie", (req, res) -> {
65-
Cookie cookie = new Cookie("username", "john");
66-
res.setCookie(cookie);
67-
res.send("Cookie has been set!");
68+
Cookie cookie = new Cookie("username", "john");
69+
res.setCookie(cookie);
70+
res.send("Cookie has been set!");
6871
});
6972
```
7073

7174
Example request: `GET` `/showcookie`:
7275
```java
7376
app.get("/showcookie", (req, res) -> {
74-
Cookie cookie = req.getCookie("username");
75-
String username = cookie.getValue();
76-
res.send("The username is: " + username); // Prints "The username is: john"
77+
Cookie cookie = req.getCookie("username");
78+
String username = cookie.getValue();
79+
res.send("The username is: " + username); // Prints "The username is: john"
7780
});
7881
```
7982

@@ -82,22 +85,22 @@ Over `req.getFormQuery(NAME)` you receive the values from the input elements of
8285
Example HTML-Form:
8386
```html
8487
<form action="http://localhost/register" method="post">
85-
<input type="text" name="email" placeholder="Your E-Mail">
86-
<input type="text" name="username" placeholder="Your username">
87-
<input type="submit">
88+
<input type="text" name="email" placeholder="Your E-Mail">
89+
<input type="text" name="username" placeholder="Your username">
90+
<input type="submit">
8891
</form>
8992
```
9093
**Attention: Currently, File-inputs don't work, if there is an File-input the data won't get parsed!**
9194
Now type, for the example below, `john` in username and `john@gmail.com` in the email field.
9295
Java code to handle the post request and access the form elements:
9396
```java
9497
app.post("/register", (req, res) -> {
95-
String email = req.getFormQuery("email");
96-
String username = req.getFormQuery("username");
97-
// Process data
98-
99-
// Prints "E-Mail: john@gmail.com, Username: john"
100-
res.send("E-Mail: " + email + ", Username: " + username);
98+
String email = req.getFormQuery("email");
99+
String username = req.getFormQuery("username");
100+
// Process data
101+
102+
// Prints "E-Mail: john@gmail.com, Username: john"
103+
res.send("E-Mail: " + email + ", Username: " + username);
101104
});
102105
```
103106

@@ -107,13 +110,13 @@ app.post("/register", (req, res) -> {
107110
Over the response object, you have serveral possibility like setting cookies, send an file and more. Below is an short explanation what methods exists:
108111
```java
109112
app.get("/res", (req, res) -> {
110-
// res.send(); // Send empty response
111-
// res.send("Hello World"); // Send an string
112-
// res.send("chart.pdf"); // Send an file
113-
// res.setStatus(200); // Set the response status
114-
// res.getStatus(); // Returns the current response status
115-
// res.setCookie(new Cookie(...)); // Send an cookie
116-
// res.isClosed(); // Check if already something has been send to the client
113+
// res.send(); // Send empty response
114+
// res.send("Hello World"); // Send an string
115+
// res.send("chart.pdf"); // Send an file
116+
// res.setStatus(200); // Set the response status
117+
// res.getStatus(); // Returns the current response status
118+
// res.setCookie(new Cookie(...)); // Send an cookie
119+
// res.isClosed(); // Check if already something has been send to the client
117120
});
118121
```
119122
The response object calls are comments because **you can only call the .send(xy) once each request!**
@@ -122,22 +125,22 @@ The response object calls are comments because **you can only call the .send(xy)
122125
With the request object you receive serveral data from the client which can be easily parsed by the given functions:
123126
```java
124127
app.get("/req/", (req, res) -> {
125-
// req.getURI(); // Request URI
126-
// req.getHost(); // Request host (mostly localhost)
127-
// req.getMethod(); // Request method (here GET)
128-
// req.getContentType(); // Request content type, is here null because it's an GET request
129-
// req.getBody(); // Request body inputstream
130-
// req.getUserAgent(); // Request user-agent
131-
// req.getParam("parameter"); // Returns an url parameter
132-
// req.getQuery("queryname"); // Returns an url query by key
133-
// req.getFormQuery("formqueryname"); // Returns an form input value
134-
// req.getFormQuerys(); // Returns all form querys
135-
// req.getCookie("user"); // Returns an cookie by name
136-
// req.getCookies(); // Returns all cookies
137-
// req.hasAuthorization(); // Check if the request contains an authorization header
138-
// req.getAuthorization(); // Returns the authorization header
139-
// req.getMiddlewareContent("name"); // Returns data from middleware
140-
// req.pipe(new OutputStream() {...}); // Pipe the body to an outputstream
128+
// req.getURI(); // Request URI
129+
// req.getHost(); // Request host (mostly localhost)
130+
// req.getMethod(); // Request method (here GET)
131+
// req.getContentType(); // Request content type, is here null because it's an GET request
132+
// req.getBody(); // Request body inputstream
133+
// req.getUserAgent(); // Request user-agent
134+
// req.getParam("parameter"); // Returns an url parameter
135+
// req.getQuery("queryname"); // Returns an url query by key
136+
// req.getFormQuery("formqueryname"); // Returns an form input value
137+
// req.getFormQuerys(); // Returns all form querys
138+
// req.getCookie("user"); // Returns an cookie by name
139+
// req.getCookies(); // Returns all cookies
140+
// req.hasAuthorization(); // Check if the request contains an authorization header
141+
// req.getAuthorization(); // Returns the authorization header
142+
// req.getMiddlewareContent("name"); // Returns data from middleware
143+
// req.pipe(new OutputStream() {...}); // Pipe the body to an outputstream
141144
});
142145
```
143146

@@ -157,52 +160,97 @@ Or create an inline-middleware:
157160
```java
158161
// Global context, you can also pass an context if you want
159162
app.use((req, res) -> {
160-
// Handle data
163+
// Handle data
161164
});
162165
```
163-
## Tutorial
166+
## Create own middleware
164167

165168
Now we take a look how we can create own middlewares. Here we create an simple PortParser which parse / extract the port-number for us:
166169
```java
167170
public class PortMiddleware implements HttpRequest, ExpressFilter {
168171

169-
/**
170-
* From interface HttpRequest, to handle the request.
171-
*/
172-
@Override
173-
public void handle(Request req, Response res) {
174-
175-
// Get the port
176-
int port = req.getURI().getPort();
177-
178-
// Add the port to the request middleware map
179-
req.addMiddlewareContent(this, port);
180-
181-
/**
182-
* After that you can use this middleware by call:
183-
* app.use(new PortMiddleware());
184-
*
185-
* Than you can get the port with:
186-
* int port = (Integer) app.getMiddlewareContent("PortParser");
187-
*/
188-
}
189-
190-
/**
191-
* Defines the middleware.
192-
*
193-
* @return The middleware name.
194-
*/
195-
@Override
196-
public String getName() {
197-
return "PortParser";
198-
}
172+
/**
173+
* From interface HttpRequest, to handle the request.
174+
*/
175+
@Override
176+
public void handle(Request req, Response res) {
177+
178+
// Get the port
179+
int port = req.getURI().getPort();
180+
181+
// Add the port to the request middleware map
182+
req.addMiddlewareContent(this, port);
183+
184+
/**
185+
* After that you can use this middleware by call:
186+
* app.use(new PortMiddleware());
187+
*
188+
* Than you can get the port with:
189+
* int port = (Integer) app.getMiddlewareContent("PortParser");
190+
*/
191+
}
192+
193+
/**
194+
* Defines the middleware.
195+
*
196+
* @return The middleware name.
197+
*/
198+
@Override
199+
public String getName() {
200+
return "PortParser";
201+
}
199202
}
200203
```
201204
No we can, as we learned above, include it with:
202205
```java
203206
// Global context, you can also pass an context if you want
204207
app.use(new PortMiddleware());
205208
```
209+
## Existing Middlewares
210+
There are already some basic middlewares included:
211+
212+
#### Static File serving
213+
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.
214+
Example:
215+
```java
216+
app.use(new Static("examplepath\\test_statics"));
217+
```
218+
Now you can access every files in the `test_statics` over the root adress `\`.
219+
#### Cookie Session
220+
Java Express also includes an simple cookie-session middleware:
221+
```java
222+
// You should use an meaningless cookie name for serveral security reasons, here f3v4.
223+
// Also you can specify the maximum age of the cookie from the creation date, here 3000.
224+
app.use(new CookieSession("f3v4", 9000));
225+
```
226+
To use a session cookie we need to get the data from the middleware which is actually an `SessionCookie`:
227+
```java
228+
// Cookie session example
229+
app.get("/session", (req, res) -> {
230+
231+
/**
232+
* CookieSession named his data "Session Cookie" which is
233+
* an SessionCookie so we can Cast it.
234+
*/
235+
SessionCookie sessionCookie = (SessionCookie) req.getMiddlewareContent("SessionCookie");
236+
int count;
237+
238+
// Check if the data is null, we want to implement an simple counter
239+
if (sessionCookie.getData() == null) {
240+
241+
// Set the default data to 1 (first request with this session cookie)
242+
count = (Integer) sessionCookie.setData(1);
243+
244+
} else {
245+
// Now we know that the cookie has an integer as data property, increase it
246+
count = (Integer) sessionCookie.setData((Integer) sessionCookie.getData() + 1);
247+
}
248+
249+
// Send an info message
250+
res.send("You take use of your session cookie " + count + " times.");
251+
});
252+
```
253+
206254
# License
207255

208-
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
256+
This project is licensed under the MIT License - see the [LICENSE.md](https://choosealicense.com/licenses/mit/) file for details
File renamed without changes.
File renamed without changes.

0 commit comments

Comments
 (0)