`

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>
分享到:
评论

相关推荐

    [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 ...

    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 ...

    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 ...

    Android中英俄切换

    为了使应用程序在启动时根据用户设备的语言设置加载正确的语言,我们需要在`Application`类或者`BaseActivity`中进行初始化操作,读取系统的默认语言并加载相应的资源。 此外,考虑到Android系统可能需要一段时间...

    Spring实现国际化的一个小例子

    welcome=Welcome to our application! ``` - `messages_zh_CN.properties`: ``` welcome=欢迎使用我们的应用! ``` 3. **配置Spring** 在Spring的配置文件(如`applicationContext.xml`或Java配置类)中,...

    SpringBoot如何优雅地使用Swagger2

    .description("API for our Spring Boot application") .version("1.0.0") .contact(new Contact("Your Name", "yoururl.com", "your@email.com")) .license("Apache 2.0") .licenseUrl(...

Global site tag (gtag.js) - Google Analytics