SCWCD 2. servlet req - resp (cap3 - cap4)


Published on

Head First JSP and Servlet.

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

SCWCD 2. servlet req - resp (cap3 - cap4)

  1. 1. Mini Mvc Tutorial Francesco Ierna
  2. 2. Objectives <ul><li>Obiettivi: </li><ul><ul><li>1.1. Http method and his use and likely problematic
  3. 3. 1.2. Request interface, write code which give paramters from the request, http header or cookies
  4. 4. 1.3. Response to manage header, content-type, acquisire text-stream, binary stream, redirect or aggiungere cookie
  5. 5. 1.4. Lifecicle servlet
  6. 6. 2.1 Build web app with jsp, html, servlet, web.xml, tag, jar and java files
  7. 7. 2.2. servlet in web.xml
  8. 8. 2.3. error-page, init-param , mime-mapping, servlet, servlet-class, servlet-name and welcome-file </li></ul></ul></ul>
  9. 9. Es: Servlet <servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>capitolo3.FirstServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping> <ul><ul><ul><li>Client -> /FirstServlet
  10. 10. Container searchs on web.xml an url-pattern with /FirstServlet
  11. 11. Take the name and searchs a servlet-name
  12. 12. From the servlet name take the servlet-class
  13. 13. Container executes the lifecycle of the servlet </li></ul></ul></ul><ul><li>As a container recevies a request from the client, it scans the web.xml to find the servlet linked to the request and chose: </li><ul><ul><li>1. exacts match
  14. 14. 2. directory match
  15. 15. 3. extentions match
  16. 16. If we have more than one url-pattern that matches with the request from the client the container choise the url-pattern closer than our request. </li><ul><li>Es: foo/bar/* e foo/* with request foo/bar/prova -> foo/bar/* </li></ul><li>If we set load-on-startup within the servlet, the servlet will be execute in the order set. No need request from the client. If we don't set the number on load-on-startup the servlet will be executed anyway. </li></ul></ul></ul>
  17. 17. LifeCicle <ul><ul><ul><li>Load Class
  18. 18. Instanzia class -> constructor
  19. 19. Init() una sola volta alla prima richiesta se loadonstartup in web.xml non è settato </li><ul><ul><li>La servlet non prende la richiesta quando </li><ul><li>Init lancia ServletException
  20. 20. Init non ritorna una time periodo definito dal web server </li></ul></ul></ul><li>Service() ogni richiesta. Che reindirizza alla get o post in base al tipo di richiesta del client
  21. 21. Destroy() solo una volta </li></ul></ul></ul>Override metodi: <ul><ul><ul><li>Init -> consigliabile solo se si vuole inizializzare dei dati da poter recuperare nella get o post
  22. 22. Service() -> non consigliabile perchè è responsabile di scegliere fra get o post in base alla richiesta del client
  23. 23. Get post -> necessario per effettuare regole di business
  24. 24. Destroy() -> solo se si vuole rilasciare qualche risorsa
  25. 25. Attenzione ad ogni richiesta un THREAD. </li></ul></ul></ul>
  26. 26. InitParam <ul><ul><ul><li>It's allowed set init parameters linked to a servlet. We can also set paramter for the entire web-appl. Every servlet could use it.
  27. 27. Servlet: -> ServletConfig (I could take the ServletContext) </li></ul></ul></ul><servlet> <servlet-name>FirstServlet</servlet-name> <init-param> <param-name>par</param-name> <param-value>value</param-value> </init-param> <servlet-class>capitolo3.FirstServlet</servlet-class> </servlet> <ul><ul><ul><li>Context: -> ServletContext </li></ul></ul></ul><context-param> <param-name>par</param-name> <param-value>value</param-value> </context-param> Both: <ul><ul><ul><li>They have the followings methods for taking values: </li><ul><li>String getInitParameter(String), Enumaration getParameterNames() </li></ul><li>As we change it we must re-deploy the web-app
  28. 28. They've just present within the web-app's init </li></ul></ul></ul>Context-param : <ul><ul><ul><li>We must define it before a context-listener. </li></ul></ul></ul>
  29. 29. Http Methods <ul><ul><ul><li>GET -> Default HTTP Method </li><ul><li>Used when: no method in form, link, url, method =”GET”
  30. 30. Url limited
  31. 31. No body </li></ul><li>POST </li><ul><li>Used when method = “POST”
  32. 32. Unlimited and has a body
  33. 33. It's not idemp </li></ul><li>HEAD -> very similar at the get but it don't send parameter to a server. No Body. It's idemp
  34. 34. PUT -> Insert resources withing the web-app (files etc)
  35. 35. DELETE -> delete resources from the web-app
  36. 36. CONNECT -> say if we have a connection
  37. 37. OPTIONS -> say what methods we have allowed
  38. 38. TRACE -> for the tests
  39. 39. Signature:
  40. 40. protected void doXXX(HttpServletRequest req, HttpServletResponse resp) </li></ul></ul></ul>throws ServletException, IOException Tutti tranne connect. Appartengono alla classe HttpServletRequest
  41. 41. Request Object <ul><li>We can take from the request the following methods: </li><ul><ul><li>Header -> String getHeader(String), int getIntHeader(String), Enumaration getHeaders()
  42. 42. Cookie -> Cookie[] getCookies()
  43. 43. Methods -> String getMethod()
  44. 44. Body –> BufferedReader getReader() e ServletInputStream getInputStream() </li></ul></ul><li>Info about the methods:
  45. 45. For example if we've just received a request from IP over the port 22047 from : </li></ul>ContextPath--> /frigoproject (nome del progetto) LocalAddr----> LocalPort----> 8080 PathInfo-----> null RemoteAddr---> (request da parte di un client) RemoteHost---> RemotePost---> 49566 RemoteUser---> null RequestURI---> /frigoproject/UserServlet (context + servlet). Risorse RequestURL---> http://localhost:8080/frigoproject/AlimentoServlet ServerName---> localhost (nome del server anche www.) ServerPort---> 22047 ( def 8080) (porta) ServletPath--> /UserServlet (servlet) ServletInfo----> ServletName----> AlimentoServlet
  46. 46. Response <ul><li>Info about response: </li><ul><ul><li>setContentType(String) -> Content of the response (text, pdf etc)
  47. 47. ServletOutputStream sos = getOutputStream() -> take the stream from the request
  48. 48. PrintWriter writer = getWriter() -> write char into the response and give it to the client
  49. 49. addCookie(cookie) -> adding cookies to the response
  50. 50. addHeader(String,String), setHeader(String,String) -> addIntHeader(String, int) </li><ul><li>Add always header
  51. 51. setHeader if we have a header with the same name it's replace the header otherwise add the header </li></ul><li>setContextLenght(int) -> lenght of the content
  52. 52. resetBuffer() -> reset the buffer
  53. 53. reset() -> reset the buffer, deleting also the header </li></ul></ul><li>Attention! </li><ul><ul><li>We can't invoke getWriter after we've just invoked getOutputStream -> throws exception(illegalStateException)
  54. 54. We must call setContentType before getWriter to change the response's charset </li></ul></ul></ul>
  55. 55. Redirect vs Forward <ul><li>Redirect (Client): </li><ul><ul><li>Changes url . Client side
  56. 56. No commit after it. Ad es: flush.
  57. 57. Take a string. NO URL Object </li></ul></ul><li>Forward (Server): </li><ul><ul><li>No, commit after it. Ad es: flush.
  58. 58. Throught RequestDispatcher from the request or from the context
  59. 59. Take req e resp </li></ul></ul></ul>