Servlet参数与属性 [英] Servlet Parameters vs Attributes

查看:107
本文介绍了Servlet参数与属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天的问题是,如果我使用网守servlet将页面转发给其他servlet,最好让第二个servlet引用参数或创建属性来引用它们吗?

My question today is, if I'm using a gatekeeper servlet to forward pages to other servlets, is it better to let the second servlet refer to the parameters or create attributes for them to refer to?

说我有一个表格:

<form action=www.ermehgerdpuppies.com/Gatekeeper id = puppyForm> 
    <select name=puppyList>
    <option value=cutePuppyServlet_12>CutePuppy
    <option value=uglyPuppyServlet_14>UglyPuppy
</select></form>

我提交此表格到达Gatekeeper servlet:

I submit this form which gets to the Gatekeeper servlet:

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

        if (request.getParameterMap().containsKey("puppyList"))
        {
            String qString = request.getParameter("puppyList");
            String[] qsArray = qString.split("_");
            request.setAttribute("merPuppy", qsArray[1]);
            RequestDispatcher rd = getServletContext().getRequestDispatcher(qsArray[0]);
            rd.forward(request, response);  
        }
    }

然后转到cutePuppyServlet(对于这个例子,它转到cutePuppy)

Which then goes to the cutePuppyServlet (for this example, it goes to cutePuppy)

现在在我的cutePuppyServlet.java中,我可以用这种方式引用数据:

Now in my cutePuppyServlet.java, I can either refer to the data this way:

request.getParameter("puppyList");

OR

request.getAttribute("merPuppy");

有了参数,我可以检查它是否存在,以防止一切都搞砸了。我的问题是,哪个更易于维护?我应该坚持转发参数还是应该创建属性?

With parameter, I can check if it exists in order to prevent blowing everything up. My question is, which is better for maintainability? Should I just stick with forwarding the parameter or should I create an attribute?

推荐答案

使用内部servlet参数的优点:

Advantages of using a parameter for the inner servlet:


  • 如果需要,嵌套的servlet可以独立存在而没有父servlet。

  • 开发人员更了解参数(我不知道为什么,但我很少看到使用的请求属性)

  • 减少代码,因为容器隐式地从客户端传入它们。

使用请求属性的优点:


  • 包含,转发等等,因为请求不会改变,但它的URL可能会改变。

  • 这就是属性实际意味着什么,消息在组件之间传递。因此,您坚持使用servlet设计。

在一天结束时,它并不重要。我会选择属性,因为我更关心以标准方式做事(即使它是一个无人关心或遵循的标准),而不是快速做。

At the end of the day, it's not going to matter much. I would pick attributes because I care more about doing things the standard way (even if it is a standard that nobody cares about or follows) than doing it quickly.

这篇关于Servlet参数与属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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