`

Configuration of the web.xml in our application

阅读更多
As we all known, the configuration of web.xml is the file that our application tells servlets what to do. there are many elements defined in web.xml, next I will tell what's the function of every element.
1, <context-param>
The optional context-param element declares a Web Application's servlet context initialization parameters. You set each context-param within a single context-param element, using <param-name> and <param-value> elements. You can access these parameters in your code using the javax.servlet.ServletContext.getInitParameter() and javax.servlet.ServletContext.getInitParameterNames() methods.
Element                Required/        Optional Description
<param-name>    Required           The name of a parameter.
<param-value>    Required           The value of a parameter.
<description>       Optional            A text description of a parameter


2,<filter> & <filter-mapping>
The <filter> element declares a filter, defines a name for the filter, and specifies the Java class that executes the filter.The <filter-mapping> element specifies which filter to execute based on a URL pattern or servlet name. The <filter-mapping> element must immediately follow the <filter> element(s).
引用
import javax.servlet.*;
public class Filter1Impl implements Filter
{
    private FilterConfig filterConfig;

    public void doFilter(ServletRequest req,
        ServletResponse res, FilterChain fc)
        throws java.io.IOException, javax.servlet.ServletException
    {
      // Execute a task such as logging.
      //...

      fc.doFilter(req,res); // invoke next item in the chain --
                            // either another filter or the
                            // originally requested resource.

    }

    public FilterConfig getFilterConfig()
    {
      // Execute tasks
      return filterConfig;
    }

    public void setFilterConfig(FilterConfig cfg)
    {
      // Execute tasks
      filterConfig = cfg;
    }
}


3,<listener>
The event declaration defines the listener class that is invoked when the event occurs.There are several servlet based event, so you should extend this event, and then when the event happens, your listener class will be excuted.
引用
/**
* UserCounterListener class used to count the current number
* of active users for the applications.  Does this by counting
* how many user objects are stuffed into the session.  It Also grabs
* these users and exposes them in the servlet context.
*/
public class UserCounterListener implements ServletContextListener,
                                            HttpSessionAttributeListener {
    public static final String COUNT_KEY = "userCounter";
    public static final String USERS_KEY = "userNames";
    public static final String EVENT_KEY = HttpSessionContextIntegrationFilter.ACEGI_SECURITY_CONTEXT_KEY;
    private final transient Log log = LogFactory.getLog(UserCounterListener.class);
    private transient ServletContext servletContext;
    private int counter;
    private Set users;

    public synchronized void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();
        servletContext.setAttribute((COUNT_KEY), Integer.toString(counter));
    }

    public synchronized void contextDestroyed(ServletContextEvent event) {
        servletContext = null;
        users = null;
        counter = 0;
    }

    synchronized void incrementUserCounter() {
        counter =
            Integer.parseInt((String) servletContext.getAttribute(COUNT_KEY));
        counter++;
        servletContext.setAttribute(COUNT_KEY, Integer.toString(counter));

        if (log.isDebugEnabled()) {
            log.debug("User Count: " + counter);
        }
    }

    synchronized void decrementUserCounter() {
        int counter =
            Integer.parseInt((String) servletContext.getAttribute(COUNT_KEY));
        counter--;

        if (counter < 0) {
            counter = 0;
        }

        servletContext.setAttribute(COUNT_KEY, Integer.toString(counter));

        if (log.isDebugEnabled()) {
            log.debug("User Count: " + counter);
        }
    }

    synchronized void addUsername(Object user) {
        users = (Set) servletContext.getAttribute(USERS_KEY);

        if (users == null) {
            users = new HashSet();
        }

        if (log.isDebugEnabled()) {
            if (users.contains(user)) {
                log.debug("User already logged in, adding anyway...");
            }
        }

        users.add(user);
        servletContext.setAttribute(USERS_KEY, users);
        incrementUserCounter();
    }

    synchronized void removeUsername(Object user) {
        users = (Set) servletContext.getAttribute(USERS_KEY);

        if (users != null) {
            users.remove(user);
        }

        servletContext.setAttribute(USERS_KEY, users);
        decrementUserCounter();
    }

    /**
    * This method is designed to catch when user's login and record their name
     * @see javax.servlet.http.HttpSessionAttributeListener#attributeAdded(javax.servlet.http.HttpSessionBindingEvent)
     */
    public void attributeAdded(HttpSessionBindingEvent event) {
        log.debug("event.name: " + event.getName());
        if (event.getName().equals(EVENT_KEY)) {
            SecurityContext securityContext = (SecurityContext) event.getValue();
            User user = (User) securityContext.getAuthentication().getPrincipal();
            addUsername(user);
        }
    }

    /**
    * When user's logout, remove their name from the hashMap
     * @see javax.servlet.http.HttpSessionAttributeListener#attributeRemoved(javax.servlet.http.HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent event) {
        if (event.getName().equals(EVENT_KEY)) {
            SecurityContext securityContext = (SecurityContext) event.getValue();
            User user = (User) securityContext.getAuthentication().getPrincipal();
            removeUsername(user);
        }
    }

    /**
     * @see javax.servlet.http.HttpSessionAttributeListener#attributeReplaced(javax.servlet.http.HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent event) {
        // I don't really care if the user changes their information
    }
}


4,<servlet> & <servlet-mapping>
the servlet element configs the actions when servlet context starts,and <servlet-mapping> defines which class to excute when the defined action creates.
引用
<servlet>
      <servlet-name>dwr-invoker</servlet-name>
      <servlet-class>uk.ltd.getahead.dwr.DWRServlet</servlet-class>
      <init-param>
            <param-name>debug</param-name>
            <param-value>true</param-value>
      </init-param>
</servlet>
    <servlet-mapping>
        <servlet-name>dwr-invoker</servlet-name>
        <url-pattern>/dwr/*</url-pattern>
    </servlet-mapping>
分享到:
评论

相关推荐

    Introduction.to.Android.Application.Development(4th,2013.12) pdf

    Running the Snake Application in the Android Emulator 66 Building Your First Android Application 68 Creating and Configuring a New Android Project 69 Core Files and Directories of the Android ...

    [Go语言入门(含源码)] The Way to Go (with source code)

    The Way to Go,: A Thorough Introduction to the Go Programming Language 英文书籍,已Cross the wall,从Google获得书中源代码,分享一下。喜欢请购买正版。 目录如下: Contents Preface......................

    The way to go

    1.2.3 Targets of the language....................................................................................5 1.2.4 Guiding design principles........................................................

    外文翻译 stus MVC

    On the Web, the browser has to re-query the server to discover modification to the state of the application. Another noticeable change is that the view uses different technology for implementation ...

    GWT in Action

    You’ll learn the details of using the GWT module’s XML configuration file to, among other things, inject resources, alter the project layout, invoke class replacement and generation, and include ...

    Java邮件开发Fundamentals of the JavaMail API

    In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to ...

    EurekaLog_7.5.0.0_Enterprise

    12)..Changed: VCL/CLX/FMX now will assign Application.OnException handler when low-level hooks are disabled EurekaLog 7.2 Hotfix 6 (7.2.6.0), 14-July-2015 1)....Added: csoCaptureDelphiExceptions ...

    Proxy Pattern Informatization Research Based On SaaS

    Above we discuss the basic functions of informatization platform in proxy industry, the remainder of this article will detail the system architecture that can help us plan and build SaaS application....

    UE(官方下载)

    The benefit of a column maker is that it can help you to format your text/code, or in some cases to make it easier to read in complex nested logic. Quick Open UltraEdit and UEStudio provide multiple ...

    VB.NET Developer's Guide(4574).pdf

    3.In the Properties window, click the Itemsproperty, then click the ellipsis. 4.In String Collection Editor, type the first item, then press Enter. 5.Type the next items, pressing Enterafter each item...

    Odoo 11 Development Essentials 3 Edition(epub)

    Chapter 4, Models – Structuring the Application Data, discusses the Model layer in detail, introducing the framework's Object-Relational Mapping (ORM), the different types of models available, and ...

    Professional C# 3rd Edition

    The Role of C# in the .NET Enterprise Architecture 24 Summary 26 Chapter 2: C# Basics 29 Before We Start 30 Our First C# Program 30 The Code 30 Compiling and Running the Program 31 Contents A Closer ...

Global site tag (gtag.js) - Google Analytics