简体   繁体   中英

How to configure parameters in web.xml and show on page?

I'm practicing java servlet programming recently and suffered a problem that confused me for a period of time.

Please see the code. In the following code, I tried to compute the counts the servlet has been accessed. I can pre-define the initial value in web.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

 <servlet>
   <servlet-name>Counter</servlet-name>
   <servlet-class>SimpleCounter</servlet-class>
   <init-param>
       <param-name>initial</param-name>
       <param-value>1000</param-value>
   </init-param>
 </servlet>

</web-app>

I registered a servlet named "Counter" in web.xml and configure a parameter "initial" as 1000 when servlet is loaded. And show the paramter in init() method as servlet runs:

package com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Counter")
public class SimpleCounter extends HttpServlet {

/**
 * @see HttpServlet#HttpServlet()
 */
private static final long serialVersionUID = 1L;

int count;

public void init() throws ServletException{

    //No luck with the saved state, check for an init parameter
    String initial = this.getInitParameter("initial");
    System.out.println(initial);
    try{
        count = Integer.parseInt(initial);

        //print out the parameter
        System.out.println(count);

        return;
    }catch(NumberFormatException e){
        //default to initial count of '0'
        count = 0;
    }

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
                                        throws ServletException, IOException {
    int local_count;

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    synchronized(this){
        local_count = count++;
    }

    out.println("Since loading (and with a possible initialization parameter figured in)");
    out.println("SimpleCounterServlet has been accesed " + local_count + " times.");
}

public void destroy(){
    super.destroy();
}

}

However, when servlet was loaded, the console printed out and I still cannot figure out some problems. ,但我仍然无法找出一些问题。

If i've specified the servlet annotation in my code, should I still specified in web.xml file? 如果我在代码中指定了servlet批注 ,是否仍应在web.xml文件中指定?

How do I show the parameters configured in web.xml file? 如何显示在web.xml文件中配置的参数?

cuz the example code was from a book, I'm not sure if the web.xml refers to the one under WEB-INF or the one under tomcat server as image below: 因为示例代码来自一本书,所以我不确定web.xml是指WEB-INF下的内容还是tomcat服务器下的内容,如下图所示: 在此处输入图片说明

To print the initialization parameters defined for the servlet in web.xml file, you can use the following snippet of code inside your init method.

    Enumeration<String> initializationParameters=this.getInitParameterNames();
    while(initializationParameters.hasMoreElements()){
        String parameterName=initializationParameters.nextElement();
        System.out.println("Parameter Name:"+parameterName+"    Parameter Value:"+this.getInitParameter(parameterName));
    }

Q1 : Annotations and XML are either-or, not both. Many new J2EE applications use Annotations because its easy. However there are application that use XML as well. The advantage of XML is that it can be changed without having to compile the whole application.

Q2 : Not sure what you meant, but if you map servlet in XML, there's no need to specify in Java Code.

Q3 : It refers to the web.xml inside WEB-INF .

Here I will give some detailed test for this question.

I wrote a piece of code to show the servlet information in method as follows: 方法中的servlet信息,如下所示:

String name = this.getServletName();
System.out.println("Servelet Name: " + name);

and it printed out

五月 09, 2015 4:30:02 下午 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/ServletPractice] has started  
五月 09, 2015 4:30:02 下午 org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/ServletPractice] is completed
Servelet Name: com.SimpleCounter

So I guessed in web.xml I didn't set up a correct name for the tag . 设置正确And then I changed the contents of tags and to . 的内容更改为And we should be vigilant that the servlet annotation should not be the same with content of tag . 与标签内容不应相同。 Or the web page cannot be shown.

Here's web.xml file I've updated:

<servlet>
<servlet-name>com.SimpleCounter</servlet-name>
<servlet-class>com.SimpleCounter</servlet-class> 
<init-param>
    <param-name>initial</param-name>
    <param-value>1000</param-value>
</init-param>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM