我可以通过Integer
, String
, Float
等等...但是当我传递我定义的对象( Employee
)时,JSP 将其接收为 null
.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.rahul.model.bean.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Search Result</title>
</head>
<body>
<%
Employee record = (Employee) request.getAttribute("searchResult");
out.println(record);
%>
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Designation</th>
<th>Department</th>
<th>Salary</th>
</tr>
</table>
</body>
</html>
And My Controlleer doGet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
EmployeeDAO dao = new EmployeeDAOImpl();
Employee result = dao.search(request.getParameter("id"));
// PrintWriter pw=response.getWriter();
// pw.println(result);
ServletContext app = getServletContext();
app.setAttribute("searchResult", result);
System.out.println("Emp= "+result);
response.sendRedirect("./searchview.jsp");
}
最佳答案
试试这个:
GreetingsServlet.java
import java.io.IOException;
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("/greetings")
public class GreetingsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String message = "Hello, World";
req.setAttribute("message", message);
RequestDispatcher dispatcher = req.getServletContext().getRequestDispatcher("/WEB-INF/jsp/greetings.jsp");
dispatcher.forward(req, resp);
}
}
问候.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><%= request.getAttribute("message") %></h1>
</body>
</html>
这不能与 sendRedirect
一起使用,因为您基本上是在客户端和服务器之间进行往返,跨越 2 个请求,而不是一个。第一个请求有您的参数,但由于您的客户端不存储它,因此当发生重定向时它会丢失。您应该转发到您的 JSP,除非 servlet 所做的事情不应该一遍又一遍地执行(如数据库插入)。看here如果您确实需要重定向。
关于java - 如何将对象从 servlet 传递到 JSP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38612699/