我正在开发一个项目,该项目只有一个页面(index.jsp),并且页面初始加载,正在发送 Ajax 请求并检索 JSON 数据。发送到我的 Servlet 的 AJAX 调用和 Servlet 返回 JSON 数据,而我只有一个 Servlet。我正在尝试将一些数据发送到我的 JSP 页面进行填充,所以这就是我编写 Servlet 的方式......
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =response.getWriter();
String queryString = request.getQueryString();
ResourceBundle props = ResourceBundle.getBundle("jira");
XmlMerge xmlMerge = new XmlMerge();
String mergeFiles=xmlMerge.getJsonData();
out.println(mergeFiles);
out.close();
//Debug Statement
System.out.println(xmlMerge.getTodo());
// *THIS IS THE WAY I AM SEND DATA TO JSP PAGE.*
request.setAttribute("todo", xmlMerge.getTodo());
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
在我的index.jsp中
<%=(String)request.getAttribute("todo")%>
我正在尝试输出结果。
出了什么问题?
最佳答案
我刚刚执行了此更改,它显示了您需要的内容:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
request.setAttribute("todo", "10");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
这是生成的index.jsp:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=(String)request.getAttribute("todo")%>
</body>
</html>
你的 getTodo() 可能有问题..我不知道它是如何工作的,但也许这可以帮助:
...
XmlMerge xmlMerge = new XmlMerge();
String todo = xmlMerge.getTodo();
...
request.setAttribute("todo", todo);
更新:
PrintWriter out = response.getWriter();
out.println(...);
out.close();
这是你的问题...你正在获取资源并将其关闭。这可能会导致非法状态异常问题..
您“不需要”index.jsp 的调度程序。如果您不使用调度程序但想要呈现页面,您可以使用如下内容:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.getWriter().write("<html><body>"+getSomething()+"</body></html>");
}
为什么index.jsp不是默认调用?因为甚至可能不存在index.jsp 文件,并且它可能是对另一个servlet 的调用。您可以进行配置,将对 index.jsp 的调用映射到 servlet。
http://tutorials.jenkov.com/java-servlets/web-xml.html
我仍然不知道使用 out.println 的目的是什么,但如果您希望它显示在 jsp 中,您可以将其作为“todo”参数发送:
request.setAttribute("mergeFiles", mergeFiles);
然后在jsp中将其打印为“todo”。
关于java - 如何从 Servlet 向 JSP 发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19123573/