Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CPAN423 Enterprise Java Programming Lecture #2: More on Servlets Tracking users using Sessions and Cookies: HTTP is stateless protocol, meaning that the server doesn’t maintain contextual information about a client. The client opens a separate connection to the web server each time it needs to request a document from that server. Cookies are textual information sent by the server to the client. The next time the client visit the same page, the cookies information are sent back to the server. The server can use this information to identify a user. The server can then perform different tasks, like customizing the website, store the user choices, or remember the user password. Cookies have some limitations: In general browsers can accept 20 cookies per site and total of 300 cookies. The size of each cookie is limited to 4 kilobytes. Users can turn cookies off due to privacy issues; therefore the web application should not use cookies extensively, especially for sensitive information. Servlets provide HttpSessin API interface that enable programmer to keep tracking of users using sessions. The session object is stored on the serve side and can help you to keep track of your web site visitors. Data can be put in the session and retrieved from it, much like a Hashtable. A different set of data is kept for each visitor to the site. Persistent Servlet State: The ServletConetxt interface provide methods for storing persistence data that can be shared by all the Servlets and JSP files in the same web application. The methods setAttribute and getAttribute of this interface allows us to store and restore data that are associated with a specific key. Data stored in a ServletContext object are not tied to a particular user and are available through the method getServletContext of ServletConfig interface In JSP the data stored in the ServletContext are available in the implicit object application. Sending and Receiving Email with Servlet The Java Mail API provides a group of classes and interfaces to send and receive email. To install the Mail API with Resin, you need to download the Mail API and the JAF from sun’s Java website. Unzip the two packages and store the 1 jar files in the Resin-ee.x.x.x\lib folder. You need to restart the server for the changes to take effect. Also you can use SmtpClient class from the package sun.net.smtp included in the JDK to send email using a valid SMTP server. See the Java documentation for details about the mail APIs. Examples Ex1:Session tracking example using Servlet The user in this example must invoke an HTML form called idForm.html that has the following content: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Session track form</title> </head> <body> <form method="post" action="SaveSession"> Type your name: <input type="text" name="username" /><br /> <input type="submit" /> <input type="reset" /> </form> </body> </html> This form will be submitted to a servlet called SaveSession. The following configuration should be added to web.xml for this servlet: <servlet> <servlet-name>SaveServletEx</servlet-name> <servlet-class>SaveSessionServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern> /SaveSession</url-pattern> <servlet-name>SaveServletEx</servlet-name> </servlet-mapping> 2 Following is the source code for SaveSessionServlet : import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class SaveSessionServlet extends HttpServlet { public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); String name = req.getParameter( "username" ); /* store the user name in the seesion object. The user name is stored as a value for an attribute called theName */ HttpSession session= req.getSession(true); session.setAttribute("theName",name); PrintWriter out=res.getWriter(); out.println("<a href='NextServlet'>click this "+session.getAttribute("theName")+"</a>"); } } The SaveSessionServlet saves the user's name in the session, and puts a link to another servlet called NextServlet. The following configuration should be added to web.xml for this NextServlet: <servlet> <servlet-name>NextServletEx</servlet-name> <servlet-class>NextServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern> /NextServlet</url-pattern> 3 <servlet-name>NextServletEx</servlet-name> </servlet-mapping> Following is the source code for NextServlet: import javax.servlet.*; import javax.servlet.http.*; import java.util.*; import java.io.*; public class NextServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); String name = req.getParameter( "username" ); /* store the user name in the seesion object. The user name is stored as a value for an attribute called theName */ HttpSession session= req.getSession(true); PrintWriter out=res.getWriter(); out.println("Hello "+session.getAttribute("theName")); } } Ex2:cookies example using Servlet In this example we will use an HTML form called cookie.html to send user information to a servlet called cookieServlet. cookie.html has the following content: 4 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Cookies Example</title> </head> <body> <form method="post" action="http://localhost:8080/cpan423/cookieServlet"> <p>User name<input type="text" name="uname" size="20"></p> <p>User password<input type="password" name="upassword" size="20"></p> <p>Store Cookie <input type="checkbox" name="remember" value="1"></p> <p> </p> <p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p> </form> </body> </html> The Servlet cookieServlet gets the user information and send them back as a cookie to the client. The next time the client request the cookieServlet, all the available cookies will be displayed as an HTML table. import java.io.*; import java.util.*; import javax.servlet.http.*; import javax.servlet.*; public class cookieServlet extends HttpServlet { Cookie[] myCookie; public void doPost ( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); /* get the user information and store them in a variables. Remember variable will store the value of the remeber check box. */ String name=req.getParameter("uname"); String password=req.getParameter("upassword"); String remember=req.getParameter("remember"); if (remember==null) remember=""; boolean found=false; 5 // get all the avaliabile cookies from the request object myCookie=req.getCookies(); /* check if the user information is already stored in the cookie */ if (myCookie!=null) { for(int i=0;i<myCookie.length;i++) { if (myCookie[i].getName().equals(name)) found=true; } } /* If the user information is not send to the client , create a cookie object that expire after 2 minutes, and send it to the client */ if ((found==false) && (remember.equals("1"))) { Cookie c=new Cookie(name,password) c.setMaxAge(120); res.addCookie(c); } pw.println("<head><body>"); pw.println("<h1>Welcome "+name+"</h1>"); ; /* display any existing cookie in a tablular format */ if (myCookie!=null) { pw.println("<table border=\"1\"><tr><th>cookie name</th><th>cookie value</th></tr>"); for(int i=0;i<myCookie.length;i++) { pw.println("<tr><td>"+myCookie[i].getName()+"</td><td>"+myCookie [i].getName()+ "</td>"+"</tr>"); } pw.println("</table>"); } pw.println("<a href=\"http://localhost:8080/cpan423/cookie.html\">Re login again</a>"); pw.println("</body></html>"); pw.close(); 6 } } The servlet files should be saved in the folder: resinx.x.x\webapps\cpan423\WEB-INF\lasses. The HTML file should be saved in the folder: resin-x.x.x\webapps\pan423 Notice that you need to add the following servlet configuration to the web.xml file: <servlet> <servlet-name>cookieServlet</servlet-name> <servlet-class>cookieServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern> /cookieServlet</url-pattern> <servlet-name>cookieServlet</servlet-name> </servlet-mapping> Ex3: using the ServletContext We will write two Servlets that store and share the number of hits in the entire application. The first servlet is called Servlet1.java and has the following content: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Servlet1 extends HttpServlet { int count; public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); if (getServletContext().getAttribute("visitorCount")==null) count=0; else { Integer val= (Integer)getServletContext().getAttribute("visitorCount"); count=val.intValue(); 7 } getServletContext().setAttribute("visitorCount",new Integer(++count)); out.println("<html><title>Servlet 1</title>"); out.println("<body> Number of hits in this application so far is : "+getServletContext().getAttribute("visitorCount").toString()+"</body>"); out.println("</html>"); } } The second servlet is called Servlet2.java and has the following content: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Servlet2 extends HttpServlet { int count; public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); if (getServletContext().getAttribute("visitorCount")==null) count=0; else { Integer val= (Integer)getServletContext().getAttribute("visitorCount"); count=val.intValue(); } getServletContext().setAttribute("visitorCount",new Integer(++count)); out.println("<html><title>Servlet 2</title>"); out.println("<body> Number of hits in this application so far is : "+getServletContext().getAttribute("visitorCount").toString()+"</body>"); out.println("</html>"); } } The number of hits in this example is stored in a key called visitorCount. The first time a client access this application (does not matter which page), count is set to zero. For each page visit in this application, count is incremented by one and stored back into the ServletContext. 8 The servlet files (Servlet1.java and Servlet2.java) should be saved in the folder: resin-x.x.x\webapps\Cpan423\WEB-INF\lasses. You need to add the following servlet configuration to web.xml: <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>Servlet1</servlet-class> </servlet> <servlet-mapping> <url-pattern>/Servlet1</url-pattern> <servlet-name>Servlet1</servlet-name> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>Servlet2</servlet-class> </servlet> <servlet-mapping> <url-pattern> /Servlet2</url-pattern> <servlet-name>Servlet2</servlet-name> </servlet-mapping> Ex4: Sending email using SmtpClient We will create a servlete that send an email using SmtpClient. The servlet is called sendmail.java and has the following content: import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import sun.net.smtp.SmtpClient; public class sendemail extends HttpServlet { String msgFrom,msgTo,msgSubject, message; PrintWriter out ; public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { 9 res.setContentType("text/html"); out = res.getWriter(); msgFrom= req.getParameter("semail"); msgTo= req.getParameter("remail"); msgSubject=req.getParameter("subject"); message=req.getParameter("message"); if (!sendMail()) { res.sendError(res.SC_INTERNAL_SERVER_ERROR, "An error occurs while attempting to access the mail server"); return; } out.println("The floowing is a confirmation that the following email has been sent"); out.println("sender: "+msgFrom); out.println("<br/>receiver: "+msgTo); out.println("<br/>message: "+message); out.close(); } public boolean sendMail() { PrintStream ps; SmtpClient send; try { send = new SmtpClient("smtp.humberc.on.ca"); send.from(msgFrom); send.to(msgTo); ps = send.startMessage(); ps.println("From: " + msgFrom); ps.println("To: " + msgTo); ps.println("Subject: " + msgSubject); ps.println("----------------"); ps.println("\n"); ps.println(message); ps.println("\r\n"); ps.println("----------------"); ps.flush(); ps.close(); send.closeServer(); } catch(IOException e) { out.println(e.toString()); return false; } 10 return true; } } Below is an HTML form called sendmail.html that will be used to invoke sendmail Servlet and pass the required information. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>sending email example</title> </head> <body> <form action="http://localhost:8080/cpan423/sendemail" method="post"> Sender email address: <input type="text" name="semail" size="35"> <br/> Receiver email address: <input type="text" name="remail" size="35"> <br/> Subject <input type="text" name="subject" size="35"> <br/> Message <textarea name="message" cols="50" rows="4"></textarea> </p> <br/> <input type="submit" value="Send Email"> </p> <input type="reset" > </p> </form> </body> </html> The servlet file (sendemail.java) should be saved in the folder: resin-x.x.x\webapps\Cpan423\WEB-INF\lasses. The html file sendemail.html should be saved under the folder resin-x.x.x\webapps\Cpan423 You need to configure the servlet in your web.xml by adding servlet/servlet-mapping entry as shown below: <servlet> <servlet-name>sendemailServlet</servlet-name> <servlet-class>sendemail</servlet-class> 11 </servlet> <servlet-mapping> <url-pattern> /sendemail</url-pattern> <servlet-name>sendemailServlet</servlet-name> </servlet-mapping> Ex5: Sending email using Java Mail API The servlet in this example uses Java Mail API to send an email: import javax.mail.*; import javax.mail.internet.*; import javax.servlet.*; import javax.servlet.http.*; public class SendMailAPI extends HttpServlet { private String smtpHost= "smtp.humber.ca"; // Initialize the servlet with the hostname of the SMTP server // we'll be using the send the messages public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, java.io.IOException { String from = request.getParameter("from"); String to = request.getParameter("to"); String cc = request.getParameter("cc"); String bcc = request.getParameter("bcc"); String subject = request.getParameter("subject"); String text = request.getParameter("text"); String status; try { // Create the JavaMail session java.util.Properties properties = System.getProperties(); properties.put("mail.smtp.host", smtpHost); Session session = Session.getInstance(properties, null); 12 // Construct the message MimeMessage message = new MimeMessage(session); // Set the from address Address fromAddress = new InternetAddress(from); message.setFrom(fromAddress); // Parse and set the recipient addresses Address[] toAddresses = InternetAddress.parse(to); message.setRecipients(Message.RecipientType.TO,toAddresses); Address[] ccAddresses = InternetAddress.parse(cc); message.setRecipients(Message.RecipientType.CC,ccAddresses); Address[] bccAddresses = InternetAddress.parse(bcc); message.setRecipients(Message.RecipientType.BCC,bccAddresses); // Set the subject and text message.setSubject(subject); message.setText(text); Transport transport=session.getTransport("smtp"); // You need to place you own user ID and Passowrd transport.connect(smtpHost,"user","password"); transport.send(message); status = "Your message was sent."; } catch (AddressException e) { status = "There was an error parsing the addresses."; } catch (SendFailedException e) { status = "There was an error sending the message."+e.toString(); } catch (MessagingException e) { status = "There was an unexpected error."+e.toString(); } // Output a status message response.setContentType("text/html"); java.io.PrintWriter writer = response.getWriter(); writer.println("<html><head><title>Status</title></head>"); writer.println("<body><p>" + status + "</p></body></html>"); writer.close(); } 13 } Below is an HTML form called SendMailAPI.html that will be used to invoke SendMailAPI servlet: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>sendmail</title></head> <body> <h1>sendmail</h1> <form action='http://localhost:8080/cpan423/SendMailApi' method='post'> From:<input type='text' name='from' size='60'><br/> To:<input type='text' name='to' size='60'><br/> CC:<input type='text' name='cc' size='60'><br/> BCC:<input type='text' name='bcc' size='60'><br/> Subject:<input type='text' name='subject' size='80'><br/> <textarea name='text' rows='8' cols='64'></textarea><br/> <input type='submit' value='send'> <input type='reset'> </form> </body> </html> The servlet file (SendeMailAPI.java) should be saved in the folder: resin-x.x.x\webapps\Cpan423\WEB-INF\lasses. The html file SendMailAPI.html should be saved under the folder resinx.x.x\webapps\Cpan423 You need to configure the servlet in your web.xml by adding servlet/servlet-mapping entry as shown below: <servlet> <servlet-name>SendMailAPI</servlet-name> <servlet-class>SendMailAPI</servlet-class> </servlet> <servlet-mapping> 14 <url-pattern> /SendMailApi</url-pattern> <servlet-name>SendMailAPI</servlet-name> </servlet-mapping> 15