javascript 将会话变量数据从jsp传递到java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15306958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:17:51  来源:igfitidea点击:

Passing session variable data from jsp to java

javajavascriptjspsessionsession-variables

提问by Seeya K

I have created session variables since I want to transfer data from one JSP to another. Each of my JSPs is a tab. I transfer data given from the user from one JSP to another using the request body. I have <form>..><button type = "submit"/> </form>in the last JSP from where I submit the data and use it in a Java class.

我创建了会话变量,因为我想将数据从一个 JSP 传输到另一个。我的每个 JSP 都是一个选项卡。我使用请求正文将用户提供的数据从一个 JSP 传输到另一个 JSP。我<form>..><button type = "submit"/> </form>在最后一个 JSP 中提交数据并在 Java 类中使用它。

When I try to access the session data from all the JSP pages, it returns a null value for all the data.

当我尝试从所有 JSP 页面访问会话数据时,它为所有数据返回一个空值。

How should I transfer all the session data from all the JSPs to a Java class? Please note that each JSP is a tab, and I submit data from the last JSP.

我应该如何将所有 JSP 中的所有会话数据传输到 Java 类?请注意,每个 JSP 都是一个选项卡,我从最后一个 JSP 提交数据。

Code:

代码:

<% 
    String joindate = request.getParameter( "joindate" );
    session.setAttribute("joindate",joindate);
    String birthdate = request.getParameter( "birthdate" );
    session.setAttribute("birthdate",birthdate);
%>

回答by zz3599

In general, just try to avoid scriptlets. You should definitely do what Makoto recommended: use a MVC pattern by having your JSPs submit their data to a servlet, which does the heavy duty lifting.

一般来说,尽量避免使用 scriptlet。您绝对应该按照 Makoto 的建议去做:使用 MVC 模式,让您的 JSP 将它们的数据提交给一个 servlet,servlet 完成繁重的工作。

Whenever you have a form in a JSP, consider using

每当您在 JSP 中有表单时,请考虑使用

<form action="servletpattern?action=add_date" method="post">

<form action="servletpattern?action=add_date" method="post">

Then in the servlet:

然后在 servlet 中:

 HttpSession session = request.getSession();
 String action = request.getParameter("action");
 if(action.equals("add_date")){
     String joindate = request.getParameter( "joindate" );
     session.setAttribute("joindate",joindate);
     String birthdate = request.getParameter( "birthdate" );
     session.setAttribute("birthdate",birthdate);
 } else if(action.equals("someotheraction"){
     //do something else
 }

In the JSP you should again not use scriptlets but instead access the session variables through EL :

在 JSP 中,您不应该再次使用 scriptlet,而是通过 EL 访问会话变量:

join date: ${joindate}, birth date: ${birthdate}