java 在同一页面上获取、处理和显示结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11177971/
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-31 04:05:09  来源:igfitidea点击:

Fetch, process and display the result on the same page

javajspservletsjavabeans

提问by Chitransh Saurabh

I have a jsp page containing a form where a user fills in some value. Now i pass these values into a servlet which processes it and retieves a related set of data. Now, i am able to retrieve the data in the servlet page, but am not able to display it on the same jsp page at which i fetched the request.

我有一个包含用户填写一些值的表单的 jsp 页面。现在我将这些值传递到一个 servlet 中,该 servlet 处理它并检索一组相关的数据。现在,我能够在 servlet 页面中检索数据,但无法在我获取请求的同一个 jsp 页面上显示它。



I do not want to use java code inside jsp. I wish to do the same using servlets only. I do not want to do something like this

我不想在jsp中使用java代码。我希望只使用 servlet 来做同样的事情。我不想做这样的事情



<% if(rollno==null)
      // then display the form
   else 
      // process the request on the jsp page itself  
%>


I want to process all my reults in a servlet file and then dispaly the result on the jsp page by passing data from servlet to jsp. I am posting my code below :

我想在一个 servlet 文件中处理我的所有结果,然后通过将数据从 servlet 传递到 jsp 来在 jsp 页面上显示结果。我在下面发布我的代码:



<form id="form" method="post" action="searchServlet">
Student Roll No :<br><input type="text" value="" name="rollno"><br><br>
<input type="submit" value="SHOW DETAILS" />
</form>


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {
            String rollno=request.getParameter("rollno");
            ResultSet rs=null;

            Class.forName("com.mysql.jdbc.Driver");  
            String url="jdbc:mysql://localhost/schooldatabase";
            Connection con = DriverManager.getConnection(url,"root","passwd");

            Statement st= (Statement) con.createStatement();
            String strquery="SELECT name,regno FROM `schooldatabase`.`student_info` WHERE rollno="+ rollno+ ";";

            if(!con.isClosed()) {
                rs=st.executeQuery(strquery);

                while(rs.next())
                {
                    out.println(rs.getString("name"));
                    out.println(rs.getString("regno"));
                }
            }

            else
            {    // The connection is closed 
            }
          }           

            catch(Exception e)
            {
                out.println(e);
            }

             finally {            
               out.close();
            }
}

回答by BalusC

You shouldn't be doing the presentation in the servlet. You should nothave anyof those lines in the servlet.

您不应该在 servlet 中进行演示。你应该不会任何在servlet的线。

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// ...
                out.println(rs.getString("name"));
                out.println(rs.getString("regno"));

// ...

            out.println(e);

You should instead be storing the data in a sensible collection and be setting it as a request attribute and finally forward the request/response to a JSP which in turn generates the proper HTML around all those data. Something like this:

相反,您应该将数据存储在一个合理的集合中,并将其设置为请求属性,最后将请求/响应转发到 JSP,后者又会围绕所有这些数据生成正确的 HTML。像这样的东西:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<Student> students = studentDAO.find(request.getParameter("rollno"));
        request.setAttribute("students", students); // Will be available as ${students} in JSP
        request.getRequestDispatcher("/WEB-INF/students.jsp").forward(request, response);
    } catch (SQLException e) {
        throw new ServletException("Cannot obtain students from DB", e);
    }
}

with this in the students.jsp

有了这个 students.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
    <c:forEach items="${students}" var="student">
        <tr>
            <td>${student.name}</td>
            <td>${student.regno}</td>
        </tr>
    </c:forEach>
</table>

For a more concrete example, see also this answer: Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern

有关更具体的示例,另请参阅此答案:使用 MVC 和 DAO 模式在 JSP 页面中的 HTML 中显示 JDBC ResultSet

See also:

也可以看看: