Как Перенаправить в уникальный файл JSP (с использованием JSP ID) с помощью сервлета - PullRequest
0 голосов
/ 20 марта 2019

Я собираюсь создать форум, используя jsp и сервлеты.во-первых, я создал макет форума и передал соответствующие данные вопроса в этот макет, когда кто-то щелкает вопрос.когда вы переходите на страницу ComapnyForum.jsp, вы можете опубликовать свой ответ.после нажатия кнопки post действие формы переходит к сервлету PostAnswer и отправляет данные в базу данных.Что я хочу, после того, как вы нажмете кнопку «Опубликовать», перезагрузите страницу и покажите ответ, введенный до

i user <a href="CompanyForum.jsp?id=<%=rs.getString("id")%>" > на моей странице JSP, и это сработало очень хорошо.но когда я использовал

RequestDispatcher requestDispatcher = request.getRequestDispatcher("CompanyDashboard.jsp?id=<%=rs.getString("id")%>");
requestDispatcher.forward(request, response);

в моем PostAnswer сервлете, он не работал.пожалуйста, покажите мне, как это сделать

вот мой CompanyForum.jsp

 <%
               java.sql.Connection connection = null;


                try
                {
                    int id = Integer.valueOf(request.getParameter("id"));
                    connection = Connector.ConnectDb();
                    PreparedStatement pst = connection.prepareStatement(" SELECT * FROM question where id = '"+id+"' ");
                    ResultSet rs = pst.executeQuery();
                    while(rs.next())
                    {
                        String title=rs.getString("title");
                        String tags = rs.getString("tags");
                        String question = rs.getString("question");
                        int qid = rs.getInt("id");
                        request.setAttribute("tags", tags);
                        request.setAttribute("title", title);
                        request.setAttribute("question", question);
                        session.setAttribute("qid", qid);
                    }
                } 

                catch (SQLException ex) {

                }
            %>
            <form class="margin-top-40" action="PostAnswer" method="post">
            <div class="form-group">
                <input type="text" placeholder="Place your title here" disabled style="color: rgba(1, 203, 225, 0.8); font-size: 20px; font-weight: bold" class="form-control" style="font-weight: bold;font-size: 20px;"  name="title" value='${title}'>
            </div>
              <div class="form-group">
                  <label style="color: #ffffff">Tags</label>
                  <input type="text" placeholder="Place your tags here" disabled class="form-control"  name="keywords" value='${tags}' style="color: rgba(1, 203, 225, 0.8);">
                  <input type="hidden" display="none" name="qid" value='${qid}' style="color: rgba(1, 203, 225, 0.8);">

            </div>
            <div class="form-group">
              <label style="color: #ffffff;">Question Detials</label>
              <textarea cols="12" rows="12" placeholder="Post Your Question Details Here....." name="message" class="form-control" style="color: #ffffff;" disabled=""> ${question} </textarea>
            </div>
             <div class="form-group">
              <label style="color: #ffffff">Image</label>
              <input class="input--style-4" type="file" name="image">
            </div> 


              <div class="form-group">
              <label style="color: #ffffff">Answer</label>
              <textarea cols="12" rows="12" placeholder="Post Your Answer Here....."  name="comment" class="form-control"></textarea>
            </div>
            <button class="btn btn-primary pull-right" value="submit" type="submit"> Post </button> 
           <!-- <button class="btn btn-primary pull-right" value="reset">Reset</button>-->
           <br>
            <br>
            <br>
            <br>
            <hr style="border: 2px solid rgba(1, 203, 225, 0.8);">

           <h2>Answers</h2>

           <table align="left" cellpadding="10" cellspacing="10" border="0">

          <%                  
                try
                {
                    int id = Integer.valueOf(request.getParameter("id"));
                    connection = Connector.ConnectDb();
                    PreparedStatement pst = connection.prepareStatement(" SELECT * FROM comment where q_id = '"+id+"' order by id ");
                    ResultSet rs = pst.executeQuery();
                    while(rs.next())
                    {
            %>

            <tr>

                <td><ul><li><%= rs.getString("comment") %></li></ul></td>
            </tr>
            <% 
            }

            } 
            catch (Exception e) {
            e.printStackTrace();
            }
            %>
            </table>



          </form>

это мой PostAnswer.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String comment = request.getParameter("comment");
    PrintWriter out = response.getWriter();
    int id = Integer.parseInt(request.getParameter("qid"));

    try
    {
        connection = Connector.ConnectDb();
        PreparedStatement pst = connection.prepareStatement("INSERT INTO comment (comment,q_id) values (?,?)");
        pst.setString(1, comment);
        pst.setInt(2, id);

        int rs = pst.executeUpdate();

        if(rs>0)
        {
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("CompanyDashboard.jsp?id=<%=rs.getString("id")%>");
            requestDispatcher.forward(request, response);

        }
    } 

    catch (SQLException ex) {
        Logger.getLogger(PostAnswer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Обновление Я использовал

RequestDispatcher requestDispatcher = request.getRequestDispatcher("CompanyForum.jsp?id=" + id);
requestDispatcher.forward(request, response);

, и он проснулся !!.

Если есть другой способ, пожалуйста, покажите мне

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...