Download presentation
Presentation is loading. Please wait.
1
Servlet
2
Servlet Config and Sevlet Context
3
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
4
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>
5
Advantage you don't need to edit the servlet file.
6
Methods public String getInitParameter(String name)
public Enumeration getInitParameterNames() public String getServletName() public ServletContext getServletContext() public ServletConfig getServletConfig()
7
Example For one parameter : String s1=getServletConfig.getInitParameter (“topic");
8
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)); }
9
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.
10
<context-param> <param-name>Topic</param-name> <param-value>AJT-Servlet-Context</param-value> </context-param>
11
Advantage Easy to maintain if any information is shared to all the servlet. we don't need to modify the servlet.
12
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
13
ServletContext Method
public void setAttribute(String name,Object object) public Object getAttribute(String name) public void removeAttribute(String name) public ServletContext getServletContext()
14
Example String s1=getServletContext.getInitParameter(“topic");
15
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)); }
16
HttpServletRequest and HttpServletResponse interface
17
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.
18
It includes : Role of Form data Form data and parameters Headers
19
Role of Form data Carttype=books Form data
20
Form data and parameters
Parsing of a form is done automatically. public String getParameter(String name) public String[] getParameterValues(String name) public Enumeration getParameterNames()
21
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)
22
HttpServletResponse Set Http Response header, set content –type.
getWriter () or getOutputStream() to erite the content.
23
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)
24
Session Handling
25
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.
26
Session Tracking Techniques
Cookies Hidden Form Field URL Rewriting HttpSession
27
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
28
How Cookie Works? public void addCookie(Cookie ck)
public Cookie[] getCookies():
29
Types of Cookie Non-persistent cookie
It is valid for single session only. Persistent cookie It is valid for multiple session .
30
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)
31
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);
32
Get Cookies Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++) { out.print("<br>"+ck[i].getName()+" "+ck[i].getValue()); }
33
Servlet Cookie Program
34
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">
36
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>"); out.print("<input type='submit' value='go'>"); out.print("</form>");
37
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&??
39
Ex: out.print("<a href='servlet2?uname="+n+"'>visit</a>");
40
HttpSession interface
container creates a session id for each user.The container uses this id to identify the particular user
42
Methods public HttpSession getSession()
public HttpSession getSession(boolean create) public String getId() public long getCreationTime() public long getLastAccessedTime() public void invalidate()
43
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");
44
EVENT HANDLING
45
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.
46
Servlet Events Request Level events : ServletContextLevel Events:
ServletRequestListener ServletRequestAttributeListener ServletContextLevel Events: ServletContextListener ServletContextAttributeListener ServletSession level Events: HttpSessionListener, HttpSessionActivationListener, HttpSessionAttributeListener, HttpSessionBindingListener
47
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)
48
Session Level Events A class is notified about the servlet session event when : Creating a session Adding, removing, replacing attributes Destroying a session
49
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)
50
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)
51
HttpSessionBindingEvent
Constructor : Public HttpSessionBindingEvent (HttpSession s, String name, Object value) Methods : getSession() getName() getValue() Bind object --- HttpSession.setAttribute() Unbind object --- HttpSession.removeAttribute()
52
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
54
Filter API Filter FilterChain FilterConfig
55
1) Filter interface public void init(FilterConfig config)
2) public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain) 3) public void destroy()
56
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.
57
2) Filter Config public String getFilterName()
public String getInitParameter(String name) public Enumeration getInitParameterNames() public ServletContext getServletContext()
58
3) Filter Chain responsible to invoke the next filter or resource in the chain. public void doFilter(HttpServletRequest request, HttpServletResponse response)
59
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>
60
THANK YOU
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.