在< jsp:useBean>中使用构造函数初始化类. [英] Initialize class with constructor in <jsp:useBean>

查看:139
本文介绍了在< jsp:useBean>中使用构造函数初始化类.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过将参数传递给构造函数来初始化类.我需要范围是页面".我知道我的构造函数中有一个参数,但是如何有一个可以使用<jsp:useBean>接受参数并可以在JSP页面中调用的参数呢?

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);
}

如果没有no-arg构造函数,我们可以使用< jsp:useBean id="someId" class="mypackage.A" scope="page" />标记.但是在useBean JSP标记中,您不能调用任何构造函数.

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?

推荐答案

否.

要么使用<jsp:setProperty>

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

或使用普通的servlet:

or use a normal servlet:

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

很奇怪,您在问题上标记了[servlets],而通常不与<jsp:useBean>一起使用,因为这两种管理bean的方法相互冲突(一种是MVC级别1,另一种是MVC级别2 ).有关详细信息,另请参见我们的servlet Wiki页面.

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.

尽管如此,具有HttpServletRequest类型的bean特性还是令人讨厌.毫无疑问,有更好的方法可以实现具体的功能要求,您错误地认为所有这些都会是正确的解决方案.

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.

这篇关于在&lt; jsp:useBean&gt;中使用构造函数初始化类.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆