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