package com.mycompany.jerseymvcexam;
import javax.ejb.EJB;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.glassfish.jersey.server.mvc.Template;
@Path("board")
public class BoardResource {
@EJB
private BoardEJB board;
@GET
@Path("init")
@Produces(MediaType.TEXT_HTML)
@Template(name = "/board")
public BoardBean init() {
BoardBean res = new BoardBean();
res.setName("");
res.setComment("");
res.setArticles(board.getCurrentMessage());
return res;
}
@POST
@Path("submit")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
@Template(name = "/board")
public BoardBean submitMessage(
@FormParam("name") String name,
@FormParam("comment") String comment) {
board.addMessage(name, comment);
BoardBean res = new BoardBean();
res.setName(name);
res.setComment(comment);
res.setArticles(board.getCurrentMessage());
return res;
}
}
package com.mycompany.jerseymvcexam;
import lombok.Data;
@Data
public class BoardBean {
private String name;
private String comment;
private Message[] articles;
}
package com.mycompany.jerseymvcexam;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Message {
private Date date;
private String name;
private String comment;
}
<!DOCTYPE html output>
<html>
<head>
<title>Board</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method="POST" action="submit">
名前 : <input type="text" name="name" value="{{name}}"/>
コメント : <input type="text" name="comment" size="80"/>
<input type="submit"/>
</form>
<hr>
<ul>
{{#articles}}
<li>
{{date}} : {{name}} : {{comment}}
</li>
{{/articles}}
</ul>
</body>
</html>
package com.mycompany.jerseymvcexam;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Singleton;
@Singleton
public class BoardEJB {
private final List<Message> messageQueue;
public BoardEJB() {
this.messageQueue = java.util.Collections.synchronizedList(new LinkedList<>());
}
public void addMessage(String name, String comment) {
messageQueue.add(new Message(new Date(), name, comment));
while(messageQueue.size() > 25) {
messageQueue.remove(0);
}
}
public Message[] getCurrentMessage() {
return messageQueue.toArray(new Message[0]);
}
}
これはとりあえず
よか