Servlet参数与属性

Ver*_*nah 3 java servlets

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

说我有一个形式:

<form action=www.ermehgerdpuppies.com/Gatekeeper id = puppyForm> 
    <select name=puppyList>
    <option value=cutePuppyServlet_12>CutePuppy
    <option value=uglyPuppyServlet_14>UglyPuppy
</select></form>
Run Code Online (Sandbox Code Playgroud)

我提交此表单,该表单可以访问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);  
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

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

request.getParameter("puppyList");
Run Code Online (Sandbox Code Playgroud)

要么

request.getAttribute("merPuppy");
Run Code Online (Sandbox Code Playgroud)

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

Bra*_*don 6

使用内部servlet参数的优点:

  • 如果需要,嵌套的servlet可以在没有父servlet的情况下独立存在.
  • 开发人员更了解参数(我不知道为什么,但我很少看到使用的请求属性)
  • 代码较少,因为容器隐式地从客户端传入它们.

使用请求属性的优点:

  • 包含,转发等将包括它们,因为请求不会更改,但其URL可能会更改.
  • 这就是属性实际意味着什么,消息传递在组件之间传递.因此,您正在坚持servlet设计.

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