当前位置: 首页 > 知识库问答 >
问题:

当jsp调用servlet并重定向回同一jsp时,如何保留jsp页面上字段的值

季博
2023-03-14

我有一个welcome.jsp的页面,在那里我收集了一些信息,并借助超文本标记语言FORM将此请求和响应对象发送到servlet以将数据插入数据库,所以在这个操作之后,我想回到原来的位置Welcome.jsp,但当我试图使用请求调度rs=request.get请求调度(Welcome.jsp);rs.forward(请求,响应);

我在同一个Welcome.jsp上丢失了所有填充的值,所以请建议是否有一种方法可以将现有的请求和响应对象与新的请求和响应发送到servlet,并将旧的请求和响应对象从Servlet到JSP。

下面是来自“Welcome.jsp”的代码

<!DOCTYPE html>
<%@page import="***********"%>
<%@page import="java.io.Console"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.util.ArrayList"%>
<html>

<head>
  <title>Treatment Dashboard</title>
  <meta charset="utf-8" />
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

<!--   <script type="text/javascript">
        function noBack()
         {
             window.history.forward()
         }
        noBack();
        window.onload = noBack;
        window.onpageshow = function(evt) { if (evt.persisted) noBack() }
        window.onunload = function() { void (0) }
    </script> -->    
</head>

<body>
    <%
        HttpSession sessions = request.getSession();
        String lanId = (String)sessions.getAttribute("lanid");
        System.out.println("session Lanid:- " + lanId);
    %>
   <!-- Codrops top bar -->
   <div class="codrops-top">

                <a>
                    <strong> VALUES </strong>
                </a>

                <span class="right">

                        <strong> VALUE </strong>

                </span>                        
  <div class="menu-area">
    <div id="dl-menu" class="dl-menuwrapper">
      <button class="dl-trigger">Open Menu</button>
      <ul class="dl-menu">
        <li><a href="#intro">Profile</a></li>
        <li><a href="#WeekendsShift">Weekends Shift</a></li>
        <li><a href="#compoff">Comp Off</a></li>
        <li><a href="<%=request.getContextPath()%>/LogoutServlet">Log Off</a></li>
      </ul>
    </div>
  </div>


  <!-- intro area -->
  <div id="intro">

    <div class="intro-text">
      <div class="container">
        <div class="row">


          <div class="col-md-12">
            <div class="intro-data">
            <div class="brand">
              <%            
                  String fname      = (String) request.getAttribute("fname");
                  String lname      = (String) request.getAttribute("lname");
                  String emailid    = (String) request.getAttribute("emailid");
                  String ext        = (String) request.getAttribute("ext");
                  String rmlanid    = (String) request.getAttribute("rmlanid");
                  String role       = (String) request.getAttribute("role");
                  String ipadd      = (String) request.getAttribute("ipadd");
                  String wcounts    = (String) request.getAttribute("weekendsCount");
                  String acocounts  = (String) request.getAttribute("appliedCompOff");
                  String rcocounts  = (String) request.getAttribute("remainingCompOff");
                  String pacocounts = (String) request.getAttribute("appliedCompOffPendingApprovalcount");   
              %>              
               <table style="width:100%" >
                     <tr>
                        <td>
                            <label for="userName" class="uname" data-icon="u"> Name :- </label>
                        </td>
                        <td>            
                             <label for="userName" class="uname" data-icon="u"><%=fname%> <%=lname%></label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userEmail" class="email" data-icon="u"> Email :- </label>
                        </td>
                        <td>            
                             <label for="userEmail" class="email" data-icon="u"><%=emailid%> </label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userExt" class="ext" data-icon="u"> EXT :- </label>
                        </td>
                        <td>            
                             <label for="userExt" class="ext" data-icon="u"><%=ext%> </label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userRmlanid" class="rmlanid" data-icon="u"> RM Lan-Id :- </label>
                        </td>
                        <td>            
                             <label for="userRmlanid" class="rmlanid" data-icon="u"><%=rmlanid%> </label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userIpadd" class="ipadd" data-icon="u"> TechM Machine IP :- </label>
                        </td>
                        <td>            
                             <label for="userIpadd" class="ipadd" data-icon="u"><%=ipadd%> </label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userWeekendsNumber" class="weekends" data-icon="WND"> Worked ON Weekends :- </label>
                        </td>
                        <td>            
                             <label for="userWeekendsNumber" class="weekends" data-icon="WND"> <%=wcounts%> </label>
                        </td>
                      </tr>                   
                      <tr>
                        <td>
                            <label for="userCompOffApplied" class="compoff" data-icon="u"> Applied Comp Off :- </label>
                        </td>
                        <td>            
                             <label for="userCompOffApplied" class="compoff" data-icon="u"> <%=acocounts%> </label>
                        </td>
                      </tr>
                      <tr>
                        <td>
                            <label for="userCompOffAvailed" class="compoff" data-icon="u"> Remaining Comp Off :- </label>
                        </td>
                        <td>            
                             <label for="userCompOffAvailed" class="compoff" data-icon="u"> <%=rcocounts%> </label>
                        </td>
                      </tr>
                      <tr>
                      <td>
                            <label for="userCompOffPendingApproval" class="compoff" data-icon="u"> CompOff Pending For Approval :- </label>
                        </td>
                        <td>            
                             <label for="userCompOffPendingApproval" class="compoff" data-icon="u"> <%=pacocounts%> </label>
                        </td>
                      </tr>                                       
                      <tr>
                        <td> </td>
                        <td>
                             <input type="submit" value="Update"/>          
                             <!-- <input type="submit" value="Cancel"/> -->
                        </td>
                      </tr>                                                                               
                </table> 
            </div>
            </div>
          </div>
        </div>
      </div>
    </div>

  </div>

<!-- Weekend Shift -->
  <section id="WeekendsShift" class="home-section bg-white">
    <div class="container">
      <div class="row">
            <div class="col-md-12">
            <div class="intro-data">
            <form  method = "post" action="AddWeekendsShiftDetails" autocomplete="on" >             
               <div class="brand">    
               <table style="width:100%" >                  
                     <tr>
                        <td>
                            <p> <br><br><br>
                                <label for="weekendDetails" class=""> Worked On Weekend :- </label>
                            </p>
                        </td>
                        <td>
                            <p><br><br><br>
                                <input type="text" id= "datepicker1" placeholder="Weekend Date" name="pickedDate"/>
                                <script>
                                    var datepicker = $("#datepicker1").datepicker({
                                        dateFormat: 'yy-mm-dd',
                                        changeMonth: true, 
                                        changeYear: true                                      
                                        }).val();                               
                                </script>
                            </p>                            
                        </td>
                      </tr>
                     <tr>
                            <td>
                                <p> <br>
                                    <label for="processname" class="uname" data-icon="PN" > Process Name :- </label>
                                </p>
                            </td>
                            <td>
                                <p> <br>
                                    <input id="processname" name="processname" required="required" type="text" placeholder="ex:-BAC"/>                                    
                                </p>
                            </td>
                      </tr>                                                               
                      <tr>
                        <td> </td>
                        <td>
                            <p> <br> 
                                <input type="submit" value="Submit"/> &nbsp;&nbsp;          
                                <input type="reset" value="Reset"/>
                             </p>
                        </td>
                      </tr>                                                                               
                </table> 
            </div>
            </form>
            </div>
          </div>
      </div>
    </div>
  </section>

  <!-- Comp Off -->
  <section id="compoff" class="home-section bg-white">
    <div class="container">
      <div class="row">
            <div class="col-md-12">
            <div class="intro-data">
            <form  method = "post" action="AddCompOffDetails" autocomplete="on" >
                <div class="brand">
              <%  
                final String USER_WEEKENDS_COMPOFF_DETAILS_QRY = "SELECT WEEKEND_DATE FROM tbl_weekend_rota WHERE (LANID= ? and IS_COMPOFF_CONSUMED = 'N' and IS_APPROVED != 'P')";
                Connection con = null;                  
                con = DBConnection.createConnection();
                PreparedStatement ps = null;
                ps =con.prepareStatement(USER_WEEKENDS_COMPOFF_DETAILS_QRY);
                ps.setString(1, lanId);

                ResultSet rs = ps.executeQuery();
              %>              
               <table style="width:100%" >      
                     <tr>
                        <td>
                            <p> <br><br><br>
                                <label for="userName" class=""> Apply CompOff :- </label>
                            </p>    
                        </td>
                        <td>
                            <p><br><br><br>
                                <select name="compOffDate">
                                    <option>-- Available CompOffs --</option>
                                    <%  while(rs.next()) { %>
                                        <option><%=rs.getString(1)%></option>
                                    <% } %>
                                    <% con.close();%>
                                </select>
                            <p>                             
                        </td>
                      </tr>                                                                   
                      <tr>
                        <td> </td>
                        <td>
                            <p><br>
                                <input type="submit" value="Apply"/> &nbsp;&nbsp;&nbsp;         
                                <input type="reset" value="Reset"/> 
                                <br><br>
                             </p>
                        </td>
                      </tr>                                                                               
                </table> 
            </div>
            </form>
            </div>
          </div>
      </div>
    </div>
  </section>

</body>

</html>

但是当我单击Submit按钮时,它调用AddWeekendShiftDetails servlet,所以在这种情况下,这个表单将发送自己的请求和响应对象,对吗?因此,我将从AddWeekendShiftDetails servlet向Mysql数据库插入值

下面的代码来自于addBookendsShift细节servlet:-

package com.taskManagment.login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Date;

//import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/AddWeekendsShiftDetails")
public class AddWeekendsShiftDetails extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public AddWeekendsShiftDetails() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {      
        String sDate = request.getParameter("pickedDate");
        String processName = request.getParameter("processname");       

        try {                       
            Date sqlDate=Date.valueOf(sDate);

            Connection con = null;
            con = DBConnection.createConnection();

            String lanId = SessionDetails.getDetailsFromSession(request, "lanid");
            System.out.println("session Lanid from Weekend Servlet:- " + lanId);

            insertWeekendShiftDetails(con, lanId, processName, sqlDate);
            con.close();

            /*RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
            rs.forward(request, response);*/
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void insertWeekendShiftDetails(Connection con, String lanId, String processname, Date date ) {
        PreparedStatement ps = null;

        try {
            String insertWeekendRotaDetails = "MY INSERT QUERY";

            java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());

            ps = con.prepareStatement(insertWeekendRotaDetails);
            ps.setString(1, null);                  ps.setString(2, lanId);
            ps.setDate(3, (java.sql.Date) date);    ps.setString(4, processname);           
            ps.setString(5, "Y");                   ps.setString(6, "N");           
            ps.setString(7, null);                  ps.setDate(8, null);
            ps.setString(9, "N");                   ps.setDate(10, sqlDate);
            ps.setDate(11, null);

            ps.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

现在从doPost开始,当我想返回到“Welcome.jsp”时,代码如下

RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);

因此,它将发回从节调用的表单的请求和响应对象,因此字段上的其他值将变为空,因此我想要一种方法来保存W<--plhd--上的旧值0/>页面。

共有1个答案

柴嘉石
2023-03-14

在发送回请求之前,需要设置请求的属性。您可以使用请求来实现这一点。setAttribute(“属性名称”、“属性值”);并且,您可以通过使用请求来检索它。下一页中的getAttribute。例如

request.setAttribute("errorMsg", "Invalid data . Please correct the input data");
requestDispatcher = request.getRequestDispatcher("error.jsp");
requestDispatcher.forward(request, response);

然后就错了。jsp您可以使用:

<%=request.getAttribute("errorMsg") %>
 类似资料:
  • 这里我想使用RequestDispatcher从servlet调用jsp页面,问题是在jsp代码中调用java代码没有问题,问题是html代码不起作用 下面是代码: 重定向servlet。爪哇: showReportt_arb。jsp: 在上面的逻辑中,java代码显示在服务器控制台中,但html代码没有显示。请帮我解决这个问题

  • 我有一个带有登录表单的jsp页面,我使用的是servlet,如果用户名和密码正确,servlet会将用户重定向到另一个页面,否则它会再次将用户重定向到登录页面 下面是servlet

  • 登录。当点击按钮时,我想从这里重定向到另一个jsp页面,但它只在servlet页面中,而不是从那里重定向到另一个jsp页面,即CustomerLogin。jsp servlet编码

  • 当需要将文档移动到一个新的位置时,就需要使用JSP重定向了。 最简单的重定向方式就是使用response对象的sendRedirect()方法。这个方法的签名如下: public void response.sendRedirect(String location) throws IOException 这个方法将状态码和新的页面位置作为响应发回给浏览器。您也可以使用setStatus()和

  • 我有2个问题 1)我有一个login.jsp页和索引页。一旦我验证了用户(在servlet ie中),用户将被重定向到index.jsp页面。我用servlet的这条线重定向它 这个过程运行良好。但是当我刷新页面时,我会被重定向回登录页面。另外,我注意到在index.jsp页面上,我得到的名字而不是index.jsp,即我的servlet名称得到displayed.for这样的例子得到代替显示 2

  • 谁能告诉我,除了RequestDispatcher之外,是否还有其他方法可以从我的servlet调用jsp页面?因为我试了很多都没有成功。 我的servlet工作正常,从JSP中恢复了所有数据。我所需要的只是在用户正确输入用户名和密码时被重定向到另一个页面。 我要为其重定向的jsp