1 / 35

Servlets 

Servlets . Servlet - how it works. To use servlets we need:. java  a web server, such as Tomcat, that supports them EclipseEE

fairly
Download Presentation

Servlets 

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Servlets 

  2. Servlet - how it works

  3. To use servlets we need: • java  • a web server, such as Tomcat, that supports them • EclipseEE The most common problem when importing the project in EclipseEE is the JRE library on your computer is not the same as the one initially used, replace it in the java build path of the project with the one on your computer. If the HttpServlet does not resolve you need to put the servlet-api.jar in WebContent/WEB-INF/lib, you can find it in <Tomcat path>/lib.

  4. Tomcat - download from here and install it (... at home, the lab already has it)

  5. Tomcat - tell EclipseEE about it New-> Other-> Server-> Server

  6. Tomcat - browse to the Tomcat installation

  7. Tomcat - tell EclipseEE which version you want to use

  8. Tomcat - tell EclipseEE which projects should be run on this server

  9. Tomcat - the result • EclipseEE will create a duplicate of the tomcat installation in the workspace. • This duplicate is the place where your web applications (Dynamic web projects) will be deployed: .metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps [ deployment will be explained in slide 11]

  10. Create a Dynamic web Project in eclipseEE  New-> Project->web->Dynamic web Project [further reading on web projects in eclipseEE]

  11. Dynamic Web Project - structure • META-INF This directory contains the MANIFEST.MF file, which is used to map class paths for dependent JAR files . EclipseEE takes care of this. • WEB-INF • WEB-INF/classes This directory is for servlets, utility classes, and the Java compiler output directory. This is automatically populated by eclipse as usual. • WEB-INF/lib Any classes in .jar files placed in this directory will be available for your Web application. We need to add the jars ourselves. These folders will be created automatically by EclipseEE in the folder WebContent of the project. [further reading]

  12. Dynamic web Project - deployment Tomcat must be made aware of your application: • a folder must be created for the application in the <Tomcat path>/webapps  folder and the contents of the project must be pasted in there • a web.xml file must be created in the WEB-INF folder of the application to map the resources to actual URLs. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  id="WebApp_ID" version="2.5">   <display-name>dadr3</display-name>   <servlet>     <description></description>     <display-name>Servlet1</display-name>     <servlet-name>Servlet1</servlet-name>     <servlet-class>package.Servlet1</servlet-class>   </servlet>   <servlet-mapping>     <servlet-name>Servlet1</servlet-name>     <url-pattern>/Servlet1</url-pattern> <!-- this could just as well be "/Varza"  -->   </servlet-mapping>   <servlet> </web-app> But everything from this slide will be done automatically by EclipseEE .

  13. The entry point - an index file In the WebContent folder of your Dynamic web Project you can define an *.html or *.jsp file called "index". This will become the entry point of your application(when you navigate to the URL of the application the "index" file appear in your browser).     For example: <html> <head> <title>Insert title here</title> </head> <body> <form action="MyServlet" method = get> <input type= text name = text> <input type = submit value="Submit"> </form>  </body> </html> Paste this in a text file. Rename it "index.html" . Double click it. see what happens. [further reading on creating html files]

  14. Creating a servlet • RightClick->new->other->Web->Servlet    (this is the ONLY way to create a servlet if you want Eclipse to build the web.xml file) • give it a name ("MyServlet" here) and this will be the result: public class MyServlet extends HttpServlet {     public MyServlet() {         super();     } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  //the GET method puts all parameters in the URL like so //   http://localhost:30000/test_servlet/MyServlet?entityName=NAME1&mode=login } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {         //the POST method hides all parameters so the URL looks like this //   http://localhost:30000/test_servlet/MyServlet         } }

  15. Usual practices: public class MyServlet extends HttpServlet {     public MyServlet() {         super();     } private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //write your code here } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  action(request,response);   } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { action(request,response);        } }

  16. Using a servlet private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{         //you get a request and you must offer a response response.setContentType("text/html"); PrintWriter out = response.getWriter(); String parameter=(String) request.getParameter("text");         //create the response line by line out.print("<html><head><title>Some title here</title>"); out.print("</head><body>"); o ut.print("your input:  "+parameter+" "); out.print("</body></html>"); }

  17. To run a Dynamic web Project Right click the "index" file -> Run As-> Run on server Note that other parts of the project can be run separately like this as well but this is not recommended since they usually depend on input from other parts that might not be running.

  18. The challenge  • Create independent entities that can communicate with each other, using servlets. • Implement a ping protocole. 

  19. Use the centralized approach

  20. Use the centralized approach

  21. Use the centralized approach

  22. Use the centralized approach

  23. Use the centralized approach

  24. Entity IDs To reach an entity we will need to know the URL of the application (web server) that hosts it and the name of the entity ("destination" here). We will need to include the message and the sender ID. "http://Machine1:30000/?sender="+sender+          "&destination="+destination+     "&message="+message+     "&mode=receiveMessage" Remember that in the lab you should use an open port such as 30000 for Tomcat. Just change it by double clicking the Tomcat server in the server tab and modify the HTTP/1.1 port.

  25. The index - in this case, the login page <html>     <head>         <title>Insert title here</title>     </head>     <body>         Entity Name:             <form action="HubServlet" method = get>                 <input type= text name = entityName>                 <input type= hidden name =mode value= login>                 <input type = submit value="Submit">             </form>      </body> </html>

  26. The servlet public class HubServlet extends HttpServlet { private HashMap<String,ChatEntity> entities=new HashMap<String,ChatEntity>(); private void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ //on the first access create the Entity and add it to the HashMap if it //does not exist,  // if a message is being sent using the controls, add the message to // the destination entity inbox , //also show inputs for messaging, and all messages in entity inbox } [ ...  remember the code from slide 14: get and post method] }

  27. The "mode" argument String mode=(String) request.getParameter("mode"); if(mode!=null){     if(mode.equals("login")){  // create the Entity and add it to the HashMap if it does not exist     }     elseif(mode.equals("sendMessage")){ // if a message is being sent using the controls, add the message to // the destination entity inbox     }  //show complete inbox for logged entity     //show inputs for messaging  }

  28. The "mode" argument String mode=(String) request.getParameter("mode"); if(mode!=null){     if(mode.equals("login")){  // create the Entity and add it to the HashMap if it does not exist     }     elseif(mode.equals("sendMessage")){ // if a message is being sent using the controls, add the message to // the destination entity inbox     }  //show complete inbox for logged entity     //show inputs for messaging  }

  29. Mode is login // create the Entity and add it to the HashMap if it does not exist if(entities.get(entityName)==null)//is it a new entity? entities.put(entityName, new ChatEntity(entityName));//create it

  30. The "mode" argument String mode=(String) request.getParameter("mode"); if(mode!=null){     if(mode.equals("login")){  // create the Entity and add it to the HashMap if it does not exist     }     elseif(mode.equals("sendMessage")){ // if a message is being sent using the controls, add the message //to the destination entity inbox     }  //show complete inbox for logged entity     //show inputs for messaging  }

  31. Mode is sendMessage // if a message is being sent using the controls, add the message to the  // destination entity inbox //get all parameters sent from the sender  String destination=(String) request.getParameter("destination");String sender=(String) request.getParameter("sender");String message=(String) request.getParameter("message");//get the entity from the hash map and ask it to receive the message if(entities.get(destination) != null){//ignore the message if no such entity exists     entities.get(destination).receiveMessage(sender,  message);

  32. The "mode" argument String mode=(String) request.getParameter("mode"); if(mode!=null){     if(mode.equals("login")){  // create the Entity and add it to the HashMap if it does not exist     }     elseif(mode.equals("sendMessage")){ // if a message is being sent using the controls, add the message to // the destination entity inbox     } //show complete inbox for logged entity //show inputs for messaging }

  33. The html response out.print("<html>"); out.print("<head><title>"+entityName+"</title></head>"); out.print("<body>"); out.println("You are logged in as: "+entityName+"  <br>"); out.print("Received messages"); //show complete inbox for logged entity entities.get(entityName).printMessages(out); //show inputs for messaging  //create a form for sending messages out.println("<form action=HubServlet method = get>"); out.println("Destination: <input type= text name = destination><br>"); out.println("Message: <input type= text name = message><br>"); out.print("<input type= hidden name = sender value="+entityName+">"); out.print("<input type= hidden name = mode value=sendMessage>"); out.print("<input type = submit value=Submit></form> "); out.print("</body></html>"); //refresh the whole page including the messages every 5s response.setHeader("Refresh", "5");

  34. The Entity public abstract class Entity{ protected String entityID; public Entity(String entityID) {              this.entityID=entityID;          } protected abstract void              receiveMessage(String sender,String message); }

  35. The chat entity public class ChatEntity extends Entity{  // the inbox: private LinkedList<String> inbox=new LinkedList<String>(); public void printMessages(PrintWriter out){ // prints every message in the inbox to the PrintWriter out out.println("<br>"); for(String msg:inbox){ out.println(msg+"<br>"); } out.println("<br>"); } public ChatEntity(String entityID) { super(entityID); } @Override protected void receiveMessage(String sender,String message) {                 //just adds the message to it's inbox inbox.addLast(sender+" : "+message); } }

More Related