.jsp
<body>
Hello, <%= request.getAttribute("userName") %>
<form method="post" action="./HelloServlet">
please type your name:<input type="text" name="name">
<button type="submit">submit</button>
</form>
</body>
servlet
doGetとdoPost userNameがnullから空の時はuserName == “Guest”
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
String name = (String) request.getAttribute("userName");
if (name == null || "".equals(name)){
request.setAttribute("userName", "Guest");
}
String view = "/WEB-INF/view/index.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
request.setAttribute("userName", name);
doGet(request, response);
}
なるほど、servletの基本動作はわかってきました。
こういう書き方もできる。
<body>
<% String userName = (String) request.getAttribute("userName"); %>
Hello, <%= userName %>
<% if("Guest".equals(userName)) {%>>
<form method="post" action="./HelloServlet">
please type your name:<input type="text" name="name">
<button type="submit">submit</button>
</form>
<% } %>
</body>
とりあえずgit init, git add, git commit, git remote add, git pushしておきましょう。
eclipseはokなんだが、これをvagrantのtomcatで動かしたい。