Tuesday, February 5, 2013

Head First Servlets and JSP: Chapter 7 JSP

1- all JSP pages will be converted by the container to Servlets.
2- in JSP we use
<% %> to write scriptlet: <% int x =5; %>
<%=  %> to write expressions, <%= x %> this will be converted to out.print(x);
as you can see we dont add ; in <%= x %>
<%@  %> to write directives <%@page import ="foo.*" %>

we know that the container create one instance of a servlet, and then create multiple threads.

so if you have

public class xxx extends HttpServlet {
int counter = 0;

public void doGet() {
  counter ++;

the counter value will be saved between request as it is an instance variable for the class. (sure this is not thread safe, we are just talking about saving the value).

As we mentioned before, JSP will be translated to Servlet, if you wirte something like

<% int counter =0 ;%>

this will be translated to
public void doGet() {
int counter =0;

however if you want to define a counter as instance variable you should write

<%! int counter = 0; %>

then it will be translated to

public class xxx extends HttpServlet {
int counter =0;
public void doGet() { }

you can even define a method

<%! int doubleCheck() {return true;} %>


we know that the first jsp request is slow because the container will do the compilation and transformation to servlet upon the first request.

JSP Methods
as the JSP pages will be converted to a class, 3 methods are important in this class and you can override them
jspInit(): will be called by servlet's init() method
jspDestroy(): will be called by servlet's destroy() method
jspService(): will be called by servlet's service() method.

JSP and web.xml
As JSP will be a servlet, you can define it in the web.xml

as you can see, we defined some init-param for the jsp, and we used <jsp-file>

now you can override the jspInit() method in JSP.

JSP Attributes
as we saw before, for servlet we have application attributes, session and request.
in JSP we have also PAGE attributes which can be set using pageContext

the PAGE attributes are available between JSP pages.
you can set

you can get:

in addition you can get and set all other attributes from pageContext:
pageContext.setAttribute("one", 1, PageContext.APPLICATION_SCOPE)
pageContext.setAttribute("one", 1, PageContext.SESSION_SCOPE)

Some Directive:
<%@ page ... > : to import a page
<%@ taglib ...>: to import tags
<% include file="x.html" %> : to do something like a master page.

JSP Expression Language
rather than writing something like <% application.getAttribute("mail") %>
you can use expression language, which is written like this ${}

How to disable scripting in JSP
to disable scripting in JSP you should do that in web.xml

How to disable Expression Language
to disable EL, in the whole application, add this to web.xml

if you want to disable EL in one page, you can write this

<%@ page isELIgnored = "true" %>

No comments:

Post a Comment