zoukankan      html  css  js  c++  java
  • How to put an object on the request in a servlet

     

    Many times when you're working with Java servlets and JSP's, you'll want to forward some piece of information from your servlet to your JSP without having to put that piece of information into thesession. For instance, in many applications you may not have a user session, and in other cases where you do have a session, you may just not want to put a bunch of junk in there.

    In either of these cases, it's very simple to put a piece of information onto the request (an instance ofHttpServletRequest). Here's some sample Java servlet code where I demonstrate this technique:

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
      // do whatever you need to here ...
    
      // my jsp needs access to the uri the user specified, so i'll get it here
      // in the servlet, then put it on the request, where the jsp can access it.
      String uri = request.getRequestURI();
      request.setAttribute("URI", uri);
    
      // now forward on to the jsp page
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageURL);
      dispatcher.forward(request,response);
    }
    

      

    As you can see from that sample servlet code, it's very easy to put something on the request. You just use the setAttribute method, like this:

    request.setAttribute("YOUR_KEY", yourVariable);
    

      

    Accessing the request attribute in the JSP

    Next, in your JSP code, it's very simple to access the attribute you just set on the request. Here's some sample JSP code that demonstrates this:

    <%
      String theUri = (String)request.getAttribute("URI");
    %>
    

      

    As you can see, all you have to do in your JSP is use the getAttribute method of the implicit requestobject, and then cast your object back to its original value. In my case, my object was a String, so I cast it back to a String here in the JSP.

    That's all you have to do to put an object on the request from a servlet, and then access the object from within your JSP. As a final note, remember that the "request" doesn't live very long, so if you need an object to last over many subsequent pages, you'll probably want to put that object in the user's sessioninstead.

  • 相关阅读:
    836. Rectangle Overlap
    背包问题---01背包最优方案总数(原理剖析代码实现)
    背包问题---01背包(原理,伪代码,编程实现)
    DP---基本思想 具体实现 经典题目 POJ1160 POJ1037
    DP---(POJ1159 POJ1458 POJ1141)
    DP--HDU 1003(最大子串和)
    DP----入门的一些题目(POJ1088 POJ1163 POJ1050)
    DFS(DP)---POJ 1014(Dividing)
    博弈---斐波那契博弈
    元素相加交换另解&puts的一个用法
  • 原文地址:https://www.cnblogs.com/hephec/p/4586843.html
Copyright © 2011-2022 走看看