我正在使用Eclipse IDE,一个简单的HelloServlet.java文件和一个简单的index.jsp文件。当我运行本地服务器时,程序启动但以下代码不执行:
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Init Firing: ");
}
我打开了Console选项卡,我收到的最后一个语句是:INFO:服务器启动时间为1442 ms。我可以做些什么来启动init方法?
答案 0 :(得分:0)
容器只会在调用时调用servlet的init()方法,而不是在容器启动时调用。
如果您想在容器启动时启动,可以按照call method on server startup
的建议使用ContextListener。此代码适用于我
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("xyz="+config.getInitParameter("xyz"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
和web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>jsp</display-name>
<servlet>
<servlet-name>mySL</servlet-name>
<servlet-class>mine.MySL</servlet-class>
<init-param>
<param-name>xyz</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mySL</servlet-name>
<url-pattern>/MySL</url-pattern>
</servlet-mapping>
</web-app>
当服务器启动时,没有任何反应,因为调用servlet时会调用init()方法。
在第一个servlet调用(例如,在浏览器中打开http://myserver.mydomain:8080/myapp/MySL之类的内容),您将获得
xyz=123
doGet
在第二个servlet调用中,您将获得
doGet
请注意,这是旧方式&#34;声明事物。如今,Servlet配置可以使用注释进行。注意不要将注释与同一servlet的XML声明混合。
带注释的Servlet看起来像这样
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = { "/OtherSL" }, initParams = { @WebInitParam(name = "abc", value = "456", description = "some parameter") })
public class OtherSL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("abc=" + config.getInitParameter("abc"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}