1

我必须根据环境将初始化参数设置为 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)?

4

2 回答 2

3

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

@Override
public String getInitParameter(String name) {

//Get initparams here
    return "MyInitParams";
}
于 2012-12-13T13:51:56.973 回答
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
    }

}
于 2012-12-11T11:36:11.347 回答