Initialize class with constructor in <jsp:useBean>

4.7k views Asked by At

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

There are 1 answers

0
BalusC On BEST ANSWER

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.