01: package example;
02:
03: import java.io.PrintWriter;
04: import java.io.IOException;
05:
06: import javax.persistence.*;
07:
08: import javax.servlet.ServletException;
09:
10: import javax.servlet.http.HttpServlet;
11: import javax.servlet.http.HttpSession;
12: import javax.servlet.http.HttpServletRequest;
13: import javax.servlet.http.HttpServletResponse;
14:
15: public class SessionServlet extends HttpServlet {
16: @PersistenceContext(name="example")
17: private EntityManager _manager;
18:
19: /**
20: * Sets the manager during initialization.
21: */
22: public void setEntityManager(EntityManager manager) {
23: _manager = manager;
24: }
25:
26: /**
27: * Handle the request.
28: */
29: public void service(HttpServletRequest request,
30: HttpServletResponse response) throws IOException,
31: ServletException {
32: response.setContentType("text/html");
33:
34: PrintWriter out = response.getWriter();
35:
36: HttpSession session = request.getSession();
37:
38: User user = (User) session.getAttribute("user");
39:
40: if (user != null) {
41: out.println("User: " + user.getName() + "<br>");
42: out.println("Quest: " + user.getQuest() + "<br>");
43: out.println("Favorite color: " + user.getColor() + "<br>");
44: return;
45: }
46:
47: String name = request.getParameter("name");
48: String quest = request.getParameter("quest");
49: String color = request.getParameter("color");
50:
51: if (name == null || name.equals("")) {
52: out.println("<form action='session'>");
53: out
54: .println("What is your name? <input name='name'></input><br>");
55: out
56: .println("What is your quest? <input name='quest'></input><br>");
57: out
58: .println("What is your favorite color? <input name='color'></input><br>");
59: out.println("</form>");
60: return;
61: }
62:
63: user = new User(name, quest, color);
64:
65: _manager.persist(user);
66:
67: session.setAttribute("user", user);
68:
69: out.println("<a href='session'>You may pass.</a>");
70: }
71: }
|