有没有办法在servlet请求中获取用户数据?

时间:2017-08-24 19:40:42

标签: javascript java servlets portlet


我是新来的,但是这些页面多次阅读。我有一个复杂的问题,我不是英语,所以请原谅我,如果我不能理解的话。 我将一个portlet写入旧的Oracle Portal 10g服务器。在portlet中,javascript函数使用ajax将一些数据发布到servlet。 我想在调用servlet时识别用户。我能从portlet会话传递一些东西吗?就像在portlet中一样,有一个PortletRenderRequest,我可以获得该用户的用户名和权限。
我的理论portlet功能简而言之:它是一个表单,如果有人填写它,并将数据与javascript ajax发送到servlet,我想检查一下,发件人有权将数据插入数据库(以及她/她是什么名称)。现在它工作,portlet获取用户数据并写入输入隐藏元素值,javascript读取它,并发送邮件,但这很容易被破解,并且可怕的解决方案。

现在理论上它看起来像这样:
portlet.jsp:

<%
    PortletRenderRequest pReq = (PortletRenderRequest)request.getAttribute(HttpCommonConstants.PORTLET_RENDER_REQUEST);  
    String userNev = pReq.getUser().getName();
    session.setAttribute("username",userNev);
    System.out.println("session ID in JSP: "+session.getId());
%>
<button class="btn" type="button">Upload data</button>
<script type="text/javascript">
    $(function() {
        $(".btn").click(function(){
            /*.....*/
            $.post( "/demo/servlet", poststring);
        });
    });
</script>

的servlet:

public class servlet extends HttpServlet {
    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = (request.getSession());
        System.out.println("Session ID in servlet: "+session.getId());
        /*....*/
    }
}


 目前它正在JDeveloper 10.1.3.5中运行 每次页面刷新都会在JSP&#34;中显示不同的会话ID。在控制台中,但是&#34; servlet中的会话ID&#34;不改变,所以它必须是正确的 所以现在唯一的任务就是将数据放在正确的HttpSession中,我只需要在jsp页面中以某种方式访问​​。 jsp页面上的 HttpSession Session = request.getSession(); 会给出错误的会话(更改每次刷新)。

修改
毕竟@Jonathan回答了这个问题。它引出了另外一个问题,比如如何在jsp页面上获取HttpSession? 我发现,jsp页面上的session = HttpSession = ProviderSession ,与servlet中的HttpSession不相同。
(如果我将提供商注册页面上的登录频率设置为&#34;始终&#34;,jsp页面上的ProviderSession没有随页面刷新而改变)
我真的不知道ProviderSession和HttpSession之间的区别,以及如何从一个访问到另一个。如果我可以从servlet访问ProviderSession,那么从使用点来看它是一样的吗?

1 个答案:

答案 0 :(得分:0)

  

Applicationlet和Portlet容器中都存在应用程序会话。它   是共享数据的方式之一(原始的Portlet   通信)从渲染阶段到行动阶段(或任何更低阶段)   阶段)在portlet容器中。   what is the difference between a portlet and a servlet?

因此,当用户登录您的应用程序时,您将设置一个会话变量,在此示例中为&#34; loggedInUser&#34;。 然后在servlet中,在执行任何数据库请求之前,检查会话变量是否为空。像这样:

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

       HttpSession session = (request.getSession());
         //check if there is a loggedInUser session variable
         if(null == session.getAttribute("loggedInUser")){              
            request.setAttribute("pleaselogin", "Not Logged In. Login or register to do this.");            
             RequestDispatcher rd=request.getRequestDispatcher("Error.html");   
               rd.forward(request,response);        
        }else{

   String username = (String) session.getAttribute("loggedInUser");


   //do database logic

}

}
相关问题