5/20/2009

ServeltContextListener

ServletContextListener handles ServletContextEvents.
ServletContextEvent notifies the creation or deletion of context.

Methods:
contextInitialized(ServletContextEvent sce)
contextDestroyed(ServletContextEvent sce)

The listener is for setting common information in the application.
The information set in it can be used in everypage.
In a distributed environment, a ServletContext is created in each JVM, and therefore setting global information in the ServletContext attributes is not recommended.


<Sample>
web.xml
    <listener>
        <display-name>Context Listener</display-name>
        <listener-class>listener.ListenerSample1</listener-class>
    </listener>
_________

ListenerSample.java
public class ListenerSample1 implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.setAttribute("message", "Good Morning");
    }
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        context.removeAttribute("message");
    }
}
_________

sample.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<body>
<c:out value="${applicationScope.message}" />
</body>
</html>

<Result>http://localhost:8080/SCWCD/sample.jsp
Good Morning

Listener

Listeners are used for notifying ivents in the web applicaion.
Listeners must be defined in the web.xml except listeners that implement HttpSessionBindingListener and HttpSessionActivationListener are excluded

Example
web.xml
<listener>
<listener-class>sample.MyListener1</listener-class>
</listener>

1/31/2009

Filter

javax.servlet.Filter intercepts a request and manupulates a ServletRequest object or a ServletResponse object.
e.g.
・Filter can intercepts a request to the application and encode a string.
・Total management using Filters

web.xml definition
You have to define filters on the web.xml.
e.g.
<filter>
    <filter-name>MyFilter</filter-name>
    <filter-class>filter.MyFilter</filter-class>
    <init-param>
            <param-name>EncodeName</param-name>
            <param-value>Shift_JIS</param-value>
    </init-param>
</filter>

<filter-mapping>
    <filter-name>MyFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

filter-name : The name of the Filter class
fiter-class : The fully qualified name of the Filter class
init-param : Initial parameter. It can be reached by FilterConfig.
url-pattern : Specifies the URL. An asterisk (*) can be used.
dispatcher : Specifies REQUEST,FORWARD,INCLUDE,ERROR. The default is REQUEST.



Methods in the Filter interface
public void init(FilterConfig config)

public void doFilter(ServletRequest request,
    ServletResponse response, FilterChain chain)

public void destroy()

<Sample>
public class MyFilter1 {
    private FilterConfig config = null;
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)req;
        String url = request.getRequestURI();

        /* Do something, for example, counting up in a database */
    
        /* to the next filter */
        chain.doFilter(req,res);
    }
    public void destroy() {}
}

    <filter>
        <filter-name>MyFilter1</filter-name>
        <filter-class>filter.MyFilter1</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>MyFilter1</filter-name>
        <url-pattern>/MyFilter1</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>

1/13/2009

Cookie

javax.servlet.http.Cookie

A client connects to a server.

The server adds a cookie to the response.

The client saves the cookie.

The client connects to the server again.

The server identifies the client by the cookie.

Add a cookie to the response.
HttpServletResponse#addCookie
e.g.
Cookie cook= new Cookie(name, value);
cok.setMaxAge(60*60*24*180);
res.addCookie(cok);

Get Cookie objects
HttpServletRequest#getCookies
All cookies the client sends with this request are stored in the array.

Encoding
The argument "value" of the Cookie can be encoded by using java.net.URLEncoder#encode(String s, String enc).
In the requested resource, use java.net.URLDecoder#decode(String s, String enc) to decode it.

<Sample>
    Cookie cook= new Cookie("message",
    URLEncoder.encode("こんにちは", "utf-8"));

<Sample>
    String str = null;
    Cookie[] cook= request.getCookies();
    if (cook!= null) {
        for (int i = 0; i < cok.length; i++) {
            if (cok[i].getName().equals("message")) {
                str = URLDecoder.decode(cok[i].getValue(), "utf-8");
                break;
            }
        }
    }

1/07/2009

ServletContext

A javax.servlet.ServletContext object is created per application.

If you set the "distributable" tag in the web.xml of an application, which means the application can be distributed to multiple JVMs, there will be one context instance for each virtual machine.

In a distributed environment, using attributes of a context object for global information is not recommended. Using a database is recommended.

The javax.servlet.ServletConfig#getServletContext method returns a reference to the ServletContext.

<Sample>
public void doGet(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
        String parameter =
            this.getServletConfig().getServletContext()
            .getInitParameter("dateformat");
        SimpleDateFormat fmt = new SimpleDateFormat(parameter);
        PrintWriter out = res.getWriter();
        out.println("<html><body>");
        out.println(fmt.format(new Date()));
        out.println("</body></html>"); 
}

In JSP files, one of the implicit objects called "application" can be used.
<Sample>
    application.getInitParameter("dateformat");

In classes that implement the ServletContextListener, use a ServletContextEvent object.
<Sample>
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
    }

Context initial parameters setting

You can define init parameters in the web.xml of an application.
You can use multiple context-param tags.

<context-param>
    <param-name>dateformat</param-name>
    <param-value>yyyy/MM/dd</param-value>
</context-param>

1/06/2009

RequestDispatcher

The javax.servlet.RequestDispathcer interface can forward a request to another resource.

Getting a RequestDispatcher object
ServletRequest#getRequestDispatcher(String path)
Specify the relative path. 
If the relative path starts with "/", it's relative to the context root.
e.g. /Sample1
e.g. Sample1

ServletContext#getRequestDispatcher(String path)
Specify the relative path to the context root.
e.g. /Sample1

void forward(ServletRequest request, ServletResponse response)
Forwards a request to the specified resource.

void include(ServletRequest request, ServletResponse response)
Includes the specified resource in the response.

The forward method forwards a request or includes content directly on the server side, which is different to the HttpServletResponse#sendRedirect method.

1/04/2009

HttpSession

HTTP has no session mechanisim

The ways to follow sessions:

Use cookies

URL rewriting
    This way supports browsers that disable cookies.

SSL (Secure Sockets Layer) session

In Java programs, the javax.servlet.http.HttpSession interface is used to create sessions.

How to get a session object
    HttpServletRequest#getSession
        Returns the current session.
        If there is no current session, it creates a new one.
    HttpServletRequest#getSession(boolean create)
        Returns the current session.
        If there is no current session and create is true, it creates a new one.
        If create is false, a new session cannot be created.

Session attributes
    HttpSession#setAttribute(String name, Object value)
    Binds an object to this session.
    HttpSession#getAttribute(String name)
    Gets the object bound in this session.
    HttpSession#getAttributeNames() returns an Enumeration type object.

Session time out
    HttpSession#setMaxInactiveInterval(int interval)
    Specifies the time out value in seconds.
    A negative value means no time out.
OR
    In the web.xml, specify the time out value in minutes.
<session-config>
        <session-timeout>
            20
        </session-timeout>
    </session-config>
A negative value or 0 means no time out.

Destroying session objects
Invoke HttpSession#invalidate
All objects bound in this session will be destroyed.

javax.servlet.http.HttpSessionListener
When a session is created or destroyed, these events are notified to the classes that implement this listener.

HttpSession objects are not thread safe.