在Servlet中设置初始化参数

时间:2012-12-11 10:26:09

标签: java servlets initialization

我必须根据环境将初始化参数设置为servlet,不是通过web.xml而是通过代码, 但我的servlet版本不是3.0,所以我不能使用它 http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#setInitParameter%28java.lang.String,%20java.lang.String%29

我没有访问servlet代码所以我正在编写一个扩展它的新servlet,我想通过java代码添加初始化参数..有什么建议吗?

<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>abc</servlet-class>
<init-param>
<param-name>abc</param-name>
<param-value>localhost:2001</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

有没有办法通过扩展servlet abc并将属性设置为servlet配置(覆盖init())来执行上述操作(添加init-params)?

2 个答案:

答案 0 :(得分:3)

我覆盖了GenericServlet的方法getInitParameter,我能够解决我的问题..

@Override
public String getInitParameter(String name) {

//Get initparams here
    return "MyInitParams";
}

答案 1 :(得分:1)

查看以下代码是否可以帮助您

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
public class HelloWorld extends HttpServlet {
    private static final long serialVersionUID = 1L;

    ServletContext context;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloWorld() {
        super();
        // TODO Auto-generated constructor stub
    }

    public void init(ServletConfig config) throws ServletException {
        // Do required initialization
        Properties prop = new Properties();
        try {
            prop.load(getServletContext().getResourceAsStream(
                    "/WEB-INF/properties/sample.properties"));
            context.setAttribute("abc", prop.getProperty("abc"));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e);
        }
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}