1 package example; 2 3 import java.io.PrintWriter ; 4 import java.io.IOException ; 5 6 import javax.persistence.*; 7 8 import javax.servlet.ServletException ; 9 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 22 public void setEntityManager(EntityManager manager) 23 { 24 _manager = manager; 25 } 26 27 30 public void service(HttpServletRequest request, 31 HttpServletResponse response) 32 throws IOException , ServletException 33 { 34 response.setContentType("text/html"); 35 36 PrintWriter out = response.getWriter(); 37 38 HttpSession 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 name = request.getParameter("name"); 50 String quest = request.getParameter("quest"); 51 String 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 |