Created
July 1, 2018 07:24
-
-
Save orekyuu/58ff5b91445e13b85d9442331d1919dd to your computer and use it in GitHub Desktop.
SPA仮実装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<%@ page import="java.util.stream.Stream" %> | |
<%@ page import="java.util.Objects" %> | |
<%@ page import="java.util.List" %> | |
<%@ page import="java.io.IOException" %> | |
<%@ page import="java.util.function.BiConsumer" %> | |
<%@ page contentType="text/html;charset=UTF-8" language="java" %> | |
<html> | |
<head> | |
<title>真・SPA</title> | |
</head> | |
<body> | |
<h1>信じられるか?これ1枚のjspなんだぜ・・・</h1> | |
<a href="#page1">ページ1</a> | |
<a href="#page2">ページ2</a> | |
<% | |
Cookie[] cookies = request.getCookies(); | |
final String path = Stream.of(cookies).filter(cookie -> Objects.equals(cookie.getName(), "path")).map(Cookie::getValue).findFirst().orElse("/"); | |
out.println(path); | |
class Page { | |
final String path; | |
final BiConsumer<JspWriter, ServletRequest> renderer; | |
public Page(String path, BiConsumer<JspWriter, ServletRequest> renderer) { | |
this.path = path; | |
this.renderer = renderer; | |
} | |
public boolean isMatch(String path) { | |
return Objects.equals(this.path, path); | |
} | |
} | |
List<Page> pages = List.of( | |
new Page("/", new BiConsumer<JspWriter, ServletRequest>() { | |
@Override | |
public void accept(JspWriter jspWriter, ServletRequest servletRequest) { | |
try { | |
jspWriter.println("<h1>Top page</h1>"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}), | |
new Page("/page1", new BiConsumer<JspWriter, ServletRequest>() { | |
@Override | |
public void accept(JspWriter jspWriter, ServletRequest servletRequest) { | |
try { | |
jspWriter.println("<h1>Page1</h1>"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}), | |
new Page("/page2", new BiConsumer<JspWriter, ServletRequest>() { | |
@Override | |
public void accept(JspWriter jspWriter, ServletRequest servletRequest) { | |
try { | |
jspWriter.println("<h1>Page2</h1>"); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
}) | |
); | |
final JspWriter writer = out; | |
final HttpServletRequest req = request; | |
pages.stream() | |
.filter(p -> p.isMatch(path)).findFirst().ifPresent(p -> p.renderer.accept(writer, req)); | |
%> | |
<script> | |
window.onhashchange = function (ev) { | |
console.log(ev); | |
var anchor = location.hash; | |
var path = anchor; | |
if (anchor === null) { | |
path = ""; | |
} else { | |
path = location.hash.substring(1); | |
} | |
document.cookie = "path=/" + path + ";"; | |
location = "/"; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment