java 从 servlet 到 JSP 的输出

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

Output from servlet to JSP

javajspservlets

提问by NewBee

I am passing parameters from JSP page calendar.jspto a servlet connect.java. In the Java class I am passing a query from a database. It retrievs data fine but I need it to print the result back to the JSP page.

我正在将参数从 JSP 页面calendar.jsp传递给 servlet connect.java。在 Java 类中,我从数据库传递查询。它可以很好地检索数据,但我需要它将结果打印回 JSP 页面。

I tried the following code but with an error at out.println().

我尝试了以下代码,但在out.println().

@WebServlet("/calendar")
public class Connect extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        String fromDate = request.getParameter("fromDate");
        String toDate = request.getParameter("toDate");
        System.out.println("fromDate---->"+fromDate);
        System.out.println("toDate---->"+toDate);
        String query = "SELECT action_time,user_action,user_ip,user_id FROM ksdi.login_detail where (action_time, action_time) OVERLAPS (DATE '"
                    + fromDate+ "',DATE '"+ toDate+ "'+ integer '1')" +
                    " order by action_time desc";

        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            conn = ConnectionUtil.getConnection();
            statement = conn.prepareStatement(query);
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                while (resultSet.next()) {
                    String action_time=resultSet.getString("action_time");
                    String user_action=resultSet.getString("user_action");
                    String user_ip=resultSet.getString("user_ip");
                    String user_id=resultSet.getString("user_id");
                    System.out.println((action_time) + " " + (user_action) + " "+(user_ip) + " "+(user_id) + " ");

                    response.setContentType("text/html");  
                    PrintWriter out = response.getWriter();  
                    out.println("action time"+((ResultSet) request).getString("action_time")+"<br />");  
                    RequestDispatcher view = request.getRequestDispatcher("calendar.jsp");  
                    view.forward(request,response);         
                }
            } else {
                System.out.println("not found");
            }
        } catch (SQLException e) {
            throw new ServletException("DB interaction failed", e);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
            if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
            if (conn != null) try { conn.close(); } catch (SQLException ignore) {}
        }
    }

}


Here is my JSP file:


这是我的 JSP 文件:

<%@ page import="java.sql.*" %>
<%  String path = request.getContextPath();%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

    <script src="<%=path%>/js/calendar.js"></script>
    <link href="<%=path %>/css/calendar.css" rel="stylesheet">
</head>
<body>
<form action="calendar">
            <div class="container">
            From:<input  name="fromDate" type="text" class="calendarSelectDate" />
            To: <input   name="toDate"   type="text" class="calendarSelectDate" />
            <input type="submit" name="b1" value="Go">
        </div>          
<div id="calendarDiv"></div>


</form> 

</body>
</html>

采纳答案by informatik01

1) In your servlet code you are doing it wrong. You should eitheroutput using PrintWriter's println()oruse RequestDispatcher's forward()method. But NOT both in the same servlet's method.

1) 在您的 servlet 代码中,您做错了。你应该要么输出使用的PrintWriter的println()使用的RequestDispatcher的forward()方法。但不是在同一个 servlet 的方法中

Quote from here: What is a request dispatcher and how do I use it?

引自此处:什么是请求调度程序以及如何使用它?

Unlike the case with the 'include', the 'forward' discards the previous output that Servlet had written to the response.

与 'include' 的情况不同,'forward' 丢弃 Servlet 已写入响应的先前输出

See the examples in the above mentioned page.

请参阅上述页面中的示例。

And if you choose to use forward()then to pass the data previously retieved from your database, you can store that data in the request scope, i.e. set the request attributes, like

如果您选择使用forward()then 传递先前从数据库中检索到的数据,您可以将该数据存储在请求范围中,即设置请求属性,例如

request.setAttribute("actionTime", action_time);

Of course you must do it beforecalling forward()!

当然你必须打电话之前forward()

Then in your JSP you can output that data using Expression Languge, like this:
test.jsp

然后在您的 JSP 中,您可以使用Expression Languge输出该数据,如下所示:
test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
    <h1>Testing the passed values</h1>
    <p>Action time: ${actionTime}</p>
    <!-- same way for other data -->
</body>
</html>


2) Another issue, in your servlet code there is a line that has this:
((ResultSet) request).getString("action_time")


2) 另一个问题,在您的 servlet 代码中有一行是这样的:
((ResultSet) request).getString("action_time")

Neaither ServletRequestnor HttpServletRequesthas the method getString(). Although ResultSethas such method, but, in your case, it is pointless and wrong to cast a request to ResultSet.

Neaither的ServletRequest也不HttpServletRequest的有法getString()。虽然ResultSet有这样的方法,但是,在你的情况下,将请求转换为ResultSet是毫无意义和错误的。



P.S.
Using scriplets in JSP is discouraged

PS
不鼓励在 JSP 中使用脚本

回答by Kevin Bowersox

The could is casting the returned HttpServletRequestrequest to a ResultSet, I think it should use the ResultSet's getStringmethod with no casting.

可以将返回的HttpServletRequest请求转换为 a ResultSet,我认为它应该使用ResultSet'sgetString方法而不进行转换。

   PrintWriter out = response.getWriter();  
   out.println("action time"+ resultSet.getString("action_time") + "<br />");  

回答by Sudhakar

Well set the values you fetch into httprequestlike this in the servlet

叫你们来读取值成的HttpRequest这样在servlet

PS: i have commented unnecessary lines

PS:我评论了不必要的行

   //response.setContentType("text/html");  
     //PrintWriter out = response.getWriter();  
    // out.println("action time"+((ResultSet) request).getString("action_time")+"<br />"); 

        request.setAttribute("action_time",action_time);
        request.setAttribute("user_action",user_action);
        request.setAttribute("user_ip",user_ip);
        request.setAttribute("user_id",user_id);


     RequestDispatcher view = request.getRequestDispatcher("calendar.jsp");  
    view.forward(request,response);  

And in calendar.jspto which you forward , access the values by

在您转发到的calendar.jsp中,通过以下方式访问值

<%= request.getAttribute("action_time")%>
<%= request.getAttribute("user_action")%>
<%= request.getAttribute("user_ip")%>
<%= request.getAttribute("user_id")%>