KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > SessionServlet


1 package example;
2
3 import java.io.PrintWriter JavaDoc;
4 import java.io.IOException JavaDoc;
5
6 import javax.persistence.*;
7
8 import javax.servlet.ServletException JavaDoc;
9
10 import javax.servlet.http.HttpServlet JavaDoc;
11 import javax.servlet.http.HttpSession JavaDoc;
12 import javax.servlet.http.HttpServletRequest JavaDoc;
13 import javax.servlet.http.HttpServletResponse JavaDoc;
14
15 public class SessionServlet extends HttpServlet JavaDoc {
16   @PersistenceContext(name="example")
17   private EntityManager _manager;
18
19   /**
20    * Sets the manager during initialization.
21    */

22   public void setEntityManager(EntityManager manager)
23   {
24     _manager = manager;
25   }
26
27   /**
28    * Handle the request.
29    */

30   public void service(HttpServletRequest JavaDoc request,
31               HttpServletResponse JavaDoc response)
32     throws IOException JavaDoc, ServletException JavaDoc
33   {
34     response.setContentType("text/html");
35     
36     PrintWriter JavaDoc out = response.getWriter();
37
38     HttpSession JavaDoc session = request.getSession();
39
40     User user = (User) session.getAttribute("user");
41
42     if (user != null) {
43       out.println("User: " + user.getName() + "<br>");
44       out.println("Quest: " + user.getQuest() + "<br>");
45       out.println("Favorite color: " + user.getColor() + "<br>");
46       return;
47     }
48
49     String JavaDoc name = request.getParameter("name");
50     String JavaDoc quest = request.getParameter("quest");
51     String JavaDoc color = request.getParameter("color");
52
53     if (name == null || name.equals("")) {
54       out.println("<form action='session'>");
55       out.println("What is your name? <input name='name'></input><br>");
56       out.println("What is your quest? <input name='quest'></input><br>");
57       out.println("What is your favorite color? <input name='color'></input><br>");
58       out.println("</form>");
59       return;
60     }
61
62     user = new User(name, quest, color);
63
64     _manager.persist(user);
65
66     session.setAttribute("user", user);
67
68     out.println("<a HREF='session'>You may pass.</a>");
69   }
70 }
71
Popular Tags