Initialize class with constructor in <jsp:useBean>

陌路散爱 提交于 2019-12-10 10:20:04

问题


I am trying to initialize a class by passing a parameter to the constructor. I need the scope to be "page". I know I have one argument in my constructor, but how do I have one that accepts parameter using <jsp:useBean>, and can be called from a JSP page?

 public class A extends B {
    A(ServletRequest req) {
       super(req);
}

If there are no-arg constructor, We can use < jsp:useBean id="someId" class="mypackage.A" scope="page" /> tag. But in a useBean JSP tag, you can't invoke any constructor.

Is there any way initialize class with constructor?


回答1:


No.

Either use <jsp:setProperty>,

<jsp:useBean id="someId" class="mypackage.A" scope="page">
    <jsp:setProperty name="someId" property="request" value="${pageContext.request}" />
</jsp:useBean>

or use a normal servlet:

request.setAttribute("someId", new A(request));

It's by the way surprising that you tagged [servlets] on the question while that's usually not to be used together with <jsp:useBean> as those two approaches of managing beans are conflicting (one is MVC level 1 and other is MVC level 2). For detail, see also our servlets wiki page.

Nonetheless, having a bean property of HttpServletRequest type is fishy. There are undoubtedly better ways to achieve the concrete functional requirement for which you incorrectly thought that this all would be the right solution.



来源:https://stackoverflow.com/questions/30842354/initialize-class-with-constructor-in-jspusebean

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