-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPlainForm.java
More file actions
89 lines (76 loc) · 3.13 KB
/
PlainForm.java
File metadata and controls
89 lines (76 loc) · 3.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package rsp.app;
import rsp.component.ComponentStateSupplier;
import rsp.component.ComponentView;
import rsp.component.definitions.Component;
import rsp.component.View;
import rsp.dsl.Html;
import rsp.dsl.Tag;
import rsp.jetty.WebServer;
import java.util.Objects;
import static rsp.dsl.Html.*;
/**
* An example with plain web pages:
* <ul>
* <li>a page with an input form</li>
* <li>a page with representation of the entered data</li>
* </ul>
*/
public class PlainForm {
static void main(final String[] args) {
final var server = new WebServer(8080, httpRequest -> new Component<Name>() {
@Override
public ComponentStateSupplier<Name> initStateSupplier() {
return (_, _) ->
switch (httpRequest.method) {
case GET -> new EmptyName();
case POST -> new FullName(Objects.requireNonNull(httpRequest.queryParameters.parameterValue("firstname")),
Objects.requireNonNull(httpRequest.queryParameters.parameterValue("lastname")));
default -> throw new IllegalStateException("Unexpected HTTP mehtod: " + httpRequest.method);
};
}
@Override
public ComponentView<Name> componentView() {
return _ -> pagesView();
}
});
server.start();
server.join();
}
public sealed interface Name {}
public record FullName(String firstName, String secondName) implements Name {
public FullName(final String firstName, final String secondName) {
this.firstName = Objects.requireNonNull(firstName);
this.secondName = Objects.requireNonNull(secondName);
}
@Override
public String toString() {
return firstName + " " + secondName;
}
}
public record EmptyName() implements Name {}
private static View<Name> pagesView() {
return state -> html(
head(HeadType.PLAIN, title("Plain Form Pages")),
body(
state instanceof FullName ? formResult((FullName)state) : form()
)
);
}
private static Tag form() {
return div(
h2(text("HTML Form")),
Html.form(attr("action", "page0"), attr("method", "post"),
label(attr("for", "firstname"), text("First name:")),
input(attr("type", "text"), attr("name","firstname"), attr("value", "First")),
br(),
label(attr("for", "lastname"), text("Last name:")),
input(attr("type", "text"), attr("name","lastname"), attr("value", "Last")),
br(),
input(attr("type", "submit"), attr("value", "Submit"))),
p("If you click the 'Submit' button, the form-data will be sent to page0."));
}
private static Tag formResult(FullName state) {
return div(h2(text("HTML Form result")),
div(p("The submitted name is " + state)));
}
}