javax.servlet.ServletException: bean [name] not found within scope

旧街凉风 提交于 2019-11-26 16:16:21

问题


I'm getting this error:

javax.servlet.ServletException: bean not found within scope

on a page with this at the top.

<jsp:useBean id="bean" type="com.example.Bean" scope="request" />

The class exists in the classpath, it worked this morning, and I don't get what not found within scope means.

How is this caused and how can I solve it?


回答1:


You need the class attribute instead of the type attribute.

The following:

<jsp:useBean id="bean" type="com.example.Bean" scope="request" />

does basically the following behind the scenes:

Bean bean = (Bean) pageContext.getAttribute("bean", PageContext.REQUEST_SCOPE);

if (bean == null) {
    throw new ServletException("bean not found within scope");
}

// Use bean ...

While the following:

<jsp:useBean id="bean" class="com.example.Bean" scope="request" />

does basically the following behind the scenes:

Bean bean = (Bean) pageContext.getAttribute("bean", PageContext.REQUEST_SCOPE);

if (bean == null) {
    bean = new Bean();
    pageContext.setAttribute("bean", bean, PageContext.REQUEST_SCOPE);
}

// Use bean ...

If it has worked before and it didn't work "in a sudden", then it means that something which is responsible for putting the bean in the scope has stopped working. For example a servlet which does the following in the doGet():

request.setAttribute("bean", new Bean());
request.getRequestDispatcher("page.jsp").forward(request, response);

Maybe you've invoked the JSP page directly by URL instead of invoking the Servlet by URL. If you'd like to disable direct access to JSP pages, then put them in /WEB-INF and forward to it instead.




回答2:


You must add

<jsp:useBean id="givingFormBean" type="some.packg.GivingForm" scope="request" />

Because by default the bean is looked on the page scope



来源:https://stackoverflow.com/questions/270444/javax-servlet-servletexception-bean-name-not-found-within-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!