gpt4 book ai didi

java - Servlet 中注入(inject)的 bean 中出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-01 12:50:40 25 4
gpt4 key购买 nike

我有两个 servlet:ServletUtils 和 ServletAditional。
ServletAditional 使用 ServletUtils 中名为 isAllowed 的方法来检查用户是否可以访问该网页。问题是,每次 ServletAditional 尝试使用此方法都会以由 bean UserCalculation 引起的 NullPointer 异常结束,该异常为 null。
在 Debug模式下快速查看 servlet 后,我​​发现 ServletUtils 中的 init 方法从未被调用。我尝试在登录时设置 bean,甚至在登录 init 中强制 init,但 bean 仍然为 null。
我的问题是,有没有一种方法可以初始化 ServletUtils 并设置 bean,而不必重新编写每个 servlet?

ServletUtils:

public class ServletUtils extends HttpServlet{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private UserCalculation userCalculation;
protected User user;

public void setUserCalculation(UserCalculation userCalculation) {
this.userCalculation = userCalculation;
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
//does nothing, not necessary
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//does nothing, not necessary
}

@Override
public void init(ServletConfig config) {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
this.userCalculation = (UserCalculation) ctx.getBean("UserCalculation");
}

public boolean isAllowed(int idRole) throws ServletException, IOException{
User user=(User) getSessionAttribute("user");
return userCalculation.checkRole(user, idRole);
}
}

Servlet附加:

public class ServletAdicional extends ServletUtils {
private static final long serialVersionUID = 1L;
private int role=1;
private AditionalService service;

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

if (!isLogedIn()){
redirectLogin();
}
else if (isAllowed(role)){
setDefaultAttributes();
redirectTo("CalculateAditionals");
}
else{
redirectToErrorPage();
}
}
@Override
public void init(ServletConfig config) {
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(config.getServletContext());
this.service = (AditionalService) ctx.getBean("AditionalService");
}
}

错误消息显示:

Servlet.service() for servlet [aditionalReport] in context with path [/ElectronicaProject] threw exception
java.lang.NullPointerException
at electronicaProject.servlets.ServletUtils.isAllowed(ServletUtils.java:82)
at electronicaProject.servlets.ServletAditional.doGet(ServletAditional.java:31)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)

最佳答案

这很简单。由于您在两个类中都重写了 init() 方法,因此永远不会调用 ServletUtilsinit() 方法,并且 userCalculation 从未初始化。

了解更多信息

<小时/>

尝试

public class ServletAdicional extends ServletUtils {
@Override
public void init(ServletConfig config) {
super.init(config);
...
}
}
<小时/>

让我们看一个简单的程序来理解它。

interface Init {
public void init();
}

class ServletUtils implements Init {
@Override
public void init() {
System.out.println("inside ServletUtils's init method");
}
}

class ServletAdicional extends ServletUtils {
@Override
public void init() {
System.out.println("inside ServletAdicional's init method");
}
}

public static void main(String[] args) throws Exception {

Init init = new ServletAdicional();
init.init();
}

输出:

inside ServletAdicional's init method
<小时/>

一些要点:

  • 也在 ServletUtils 类中调用 super.init(config);
  • 如果不是单例,请尽量避免在 Servlet 中使用实例成员,例如 user,因为它被视为针对 Servlet 的多个请求的共享对象。
  • 如果您不想提供任何实现,他们不会覆盖这些方法。
  • 如果需要,请勿将 HttpServletRequestHttpServletResponse 作为 Servlet 的实例成员,然后将其作为方法参数传递。

关于java - Servlet 中注入(inject)的 bean 中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com