Chapter 5. Attributes and Listeners: Being a Web App Flashcards
How can you put configuration values in your Deploy Descriptor, and fetch it from within the code?
Within your servlet, you can add an init-param, with a param-name & param-value.
Now in servlet we can call getServletConfig().getInitParameter(“param-name”);
When in the servlet lifecycle can we start getting the config values getServletConfig() ?
NOT in constructor
YES in init() method.
How can you access servlet init parameters from a JSP page?
We can attach it to the request within the servlet.
request.setAttribute(“key”, “value”);
What’s the difference between Context Params & Servlet Params?
Context Params are for the whole application
Servlet Params are just for a given servlet.
How do you define a Context Param?
Within the Deployment Descriptor, add context-param with the same param-name & param-value tags.
Important to note that it’s located within the whole web-app tag, NOT a single servlet tag.
In servlet code, how would you get Context Params?
getServletContext().getInitParameter(“ParamName”)
What’s the difference between a ServletContext and ServletConfig?
ServletContext – One for the whole application.
ServletConfig – Each servlet has a unique one. (Including JSP, they’re turned into first-class servlets)
What is a listener class useful for? Think of an example we could use…
Listening for events, and reacting to them.
Example: We want to connect to a database before any servlet is initialize, we can listen for contextInitialized event!
How do you make a listener class?
extend ServletContextListener. Implement any methods you want to listen for such as contextInitialized, or contextDestroyed.
How do you tell the container about a listener class you have?
In the deployment descripter you add a listener & listener-class tag.
How do we lock the servlet context? What is this useful for?
synchronized(getServletContext())
It’s useful if we are getting/setting things on the ServletContext to prevent race conditions.
Are HttpSession thread safe?
No, users can open a new browser window…
Attached image, will this code work? What exception will be thrown if any?
IllegalStateException
You can’t forward the request after you’ve already committed a response.