Servlet.

Slides:



Advertisements
Similar presentations
Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
Advertisements

7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
Dispatching, monitoring, filtering
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Servlet Session Tracking. 2 Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information: Information.
Servlets CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
Session-02.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
HTTP HyperText Transfer Protocol Stateless request/response client-server protocol Requests: Method: GET, POST, HEAD, TRACE, OPTIONS, PUT, DELETE.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
CSC 2720 Building Web Applications
Web Application Basic Scopes Application Session Request Page 1.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
® IBM Software Group © 2007 IBM Corporation Servlet Listeners
JSP Filters 23-Oct-15. JSP - FILTERS A filter is an object that can transform a request or modify a response. Filters are not servlets; they don't actually.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)
® IBM Software Group © 2007 IBM Corporation Best Practices for Session Management
® IBM Software Group © 2007 IBM Corporation Servlet Filtering
SE-2840 Dr. Mark L. Hornick1 Servlet Threads and Sessions.
Servlet Filters JAVA Enterprise Edition. Servlet Filters Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
©SoftMooreSlide 1 Session Tracking with Servlets.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
Servlets 4 Lec 30 Web Design and Development. Looking Back… Response Redirection  Sending a standard redirect  Sending a redirect to an error page Request.
Cookies in Servlet A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value,
Session Tracking Parts of this presentation was provided by SSE.
Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory.
1 Servlets – Part 2 Representation and Management of Data on the Web.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
Servlet V.B.Sanghavi. Overview of Servlet to create web application resides at server side and generates dynamic web page V.B.Sanghavi.
JSP Implicit Objects CS 422 Dick Steflik.
Servlet Sessions and Cookies
Servlets.
Java Servlets By: Tejashri Udavant..
JavaServer Pages (JSP)
Java Servlets.
Pre assessment Questions
Session Tracking in Servlets
Pre-assessment Questions
Servlet API and Lifecycle
Java Servlets 9/18/2018.
Distributed Computing, M. L. Liu
Sessions.
Server Side Programming: Java Servlets
SESSION TRACKING.
Servlet Session Tracking
Distributed Computing, M. L. Liu
Servlets & JSP.
CS320 Web and Internet Programming Cookies and Session Tracking
Servlets.
Handling State in Web Applications
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
CS3220 Web and Internet Programming Cookies and Session Tracking
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Session Tracking Techniques
MVC for Servlets 23-Feb-19.
Knowledge Byte In this section, you will learn about:
CS3220 Web and Internet Programming Cookies and Session Tracking
MVC for Servlets 29-Apr-19.
Pre-assessment Questions
MVC for Servlets 5-Jul-19.
Servlet Session Tracking: Session API
Presentation transcript:

Servlet

Servlet Config and Sevlet Context

Config public interface ServletConfig implemented by the servlet container to initialize a single servlet using init() initialization parameters to the servlet using the web.xml

Example <servlet> <servlet-name>Hello</servlet-name> <servlet-class> Hellopkg.Hello</servlet-class> <init-param> <param-name>topic</param-name> <param-value>Servlet-config</param- value> </init-param> </servlet>

Advantage you don't need to edit the servlet file.

Methods public String getInitParameter(String name) public Enumeration getInitParameterNames() public String getServletName() public ServletContext getServletContext() public ServletConfig getServletConfig()

Example For one parameter : String s1=getServletConfig.getInitParameter (“topic");

For multiple parameters : Enumeration<String> e=config.getInitParameterNames();                 String str="";       while(e.hasMoreElements()) {      str=e.nextElement();       out.print("<br>Name: "+str);       out.print("value:"+config.getInitParameter (str));      }  

Context public interface ServletContext implemented by the servlet container for all servlet to communicate with its servlet container like a application global variable mechanism for a single web application The ServletContext object is contained within the ServletConfig object.

<context-param> <param-name>Topic</param-name> <param-value>AJT-Servlet-Context</param-value> </context-param>

Advantage Easy to maintain if any information is shared to all the servlet. we don't need to modify the servlet.

Usage to get configuration information from the web.xml file to set, get or remove attribute from the web.xml file provide inter-application communication

ServletContext Method public void setAttribute(String name,Object object) public Object getAttribute(String name) public void removeAttribute(String name) public ServletContext getServletContext()  

Example String s1=getServletContext.getInitParameter(“topic");

For more elements Enumeration<String> e=getServletContext().getInitParameterNames();                 String str="";       while(e.hasMoreElements()) {      str=e.nextElement();       out.print("<br>Name: "+str);       out.print("value:"+getServletContext.getInitParameter(str));      }  

HttpServletRequest and HttpServletResponse interface

HttpServletRequest GET and POST method Servlet container recognizes request and passes to particular method. To encapsulate all Http-based Req. info., including headers and req.methods.

It includes : Role of Form data Form data and parameters Headers

Role of Form data http://commerce.rediff.com/commerce/v2/displaybag.jsp?carttype=books Carttype=books ------- Form data

Form data and parameters Parsing of a form is done automatically. public String getParameter(String name) public String[] getParameterValues(String name) public Enumeration getParameterNames()

Http Header Client - send info. Regarding which software is being used, what file types the browser is capable of receiving etc. -getHeader(String name) -getHeaders(String name) -getHeaderNames() -getIntHeader(int n) -getDateHeader(long date)

HttpServletResponse Set Http Response header, set content –type. getWriter () or getOutputStream() to erite the content.

Response Header addHeader(String name, String value) containsHeader(String name) setHeader(String name, String value) setIntHeader(String name, int value) setDateHeader(String name, long date)

Session Handling

Session Collection of HTTP requests shared between a client and web server over a period of time. Set the lifetime of a session. Stateless protocol :HTTP Example : Shopping Cart Client --- > provide a unique identifier for it.

Session Tracking Techniques Cookies Hidden Form Field URL Rewriting HttpSession

Cookie small piece of information that is persisted between the multiple client requests. a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number

How Cookie Works? public void addCookie(Cookie ck) public Cookie[] getCookies():

Types of Cookie Non-persistent cookie It is valid for single session only. Persistent cookie It is valid for multiple session .

Constructor and Methods Cookie Cookie(String name, String value) public void setMaxAge(int expiry) public String getName() public String getValue() public void setName(String name) public void setValue(String value)

Create and delete cookies Cookie ck=new Cookie("user",“abc");  response.addCookie(ck); //adding cookie in the response   Cookie ck=new Cookie("user",""); ck.setMaxAge(0);   response.addCookie(ck); 

Get Cookies Cookie ck[]=request.getCookies(); for(int i=0;i<ck.length;i++) {    out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());   }

Servlet Cookie Program

Hidden Form Field hidden (invisible) textfield is used for maintaining the state of an user Better-need not to be depend on browser.(maintained at server) <input type="hidden" name="uname" value="Vimal Jaiswal">

out.print("<form action='servlet2'>");     out.print("<input type='hidden' name='uname' value='"+n+"'>");          out.print("<input type='submit' value='go'>");  out.print("</form>");  

URL Rewriting we append a token or identifier to the URL of the next Servlet or the next resource. It will work only with links. url?name1=value1&name2=value2&??

Ex: out.print("<a href='servlet2?uname="+n+"'>visit</a>");

HttpSession interface container creates a session id for each user.The container uses this id to identify the particular user

Methods public HttpSession getSession() public HttpSession getSession(boolean create) public String getId() public long getCreationTime() public long getLastAccessedTime() public void invalidate()

Ex: In first servlet--- HttpSession session=request.getSession();          session.setAttribute("uname",n);   In second servlet--- HttpSession session=request.getSession();  String n=(String)session.getAttribute("uname");  

EVENT HANDLING

Changing the state of an object. Ex: counting total and current logged-in users, creating tables of the database at time of deploying the project, creating database connection object etc.

Servlet Events Request Level events : ServletContextLevel Events: ServletRequestListener ServletRequestAttributeListener ServletContextLevel Events: ServletContextListener ServletContextAttributeListener ServletSession level Events: HttpSessionListener, HttpSessionActivationListener, HttpSessionAttributeListener, HttpSessionBindingListener

ServletContextListener & ServletContextAttriuteListener Methods public void contextInitialized (ServletContextEvent e) public void contextDestroyed (ServletContextEvent e) Public void attributeAdded(ServletContextAttributeEvent ab) Public void attributeRemoved(ServletContextAttributeEvent ab) Public void attributeReplaced(ServletContextAttributeEvent ab)

Session Level Events A class is notified about the servlet session event when : Creating a session Adding, removing, replacing attributes Destroying a session

HttpSessionListener and HttpSessionActivationListener 1) Notified when session is created or destroyed. 2) Notified about activation or passivation of a session. 1)Public void sessionCreated(HttpSessionEvent se) 1)Public void sessionDestroyed(HttpSessionEvent se) 2)public void sessionDidActive(HttpSessionEvent se) 2)public void sessionWillPassivate(HttpSessionEvent se)

SessionAttributeListener To get notification about the changes made to the attribute list of session Public void attributeAdded(HttpSessionBindingEvent se) Public void attributeRemoved(HttpSessionBindingEvent se) Public void attributeReplaced(HttpSessionBindingEvent se)

HttpSessionBindingEvent Constructor : Public HttpSessionBindingEvent (HttpSession s, String name, Object value) Methods : getSession() getName() getValue() Bind object --- HttpSession.setAttribute() Unbind object --- HttpSession.removeAttribute()

ServletFilter object that is invoked at the preprocessing and postprocessing of a request. to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. servlet filter is pluggable ---> less maintenance

Filter API Filter FilterChain FilterConfig

1) Filter interface public void init(FilterConfig config) 2) public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain) 3) public void destroy()

doFilter method Examining the request Carrying out i/p filtering by wrapping the req. object Carrying out o/p filtering by wrapping the res. Object Invoking the next filter in the filter chain by calling chain.doFilter() or blocking.

2) Filter Config public String getFilterName() public String getInitParameter(String name) public Enumeration getInitParameterNames() public ServletContext getServletContext()

3) Filter Chain responsible to invoke the next filter or resource in the chain. public void doFilter(HttpServletRequest request, HttpServletResponse response)

How to define a filter? <web-app> <filter> <filter-name>...</filter-name>   <filter-class>...</filter-class>   </filter>       <filter-mapping>   <url-pattern>...</url-pattern>   </filter-mapping>   </web-app>  

THANK YOU