我创建了这样一个 JSP 文件:
<jsp:useBean id="ucz" class="pl.lekcja.beany.beany.Uczen" scope="request">
<jsp:setProperty name="ucz" property="*"/>
</jsp:useBean>
<%@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>Podaj dane ucznia:</h1>
<form method="POST" action="Ocen">
<table>
<tr>
<td>Imie:</td>
<td><input type="text" name="imie" /></td>
</tr>
<tr>
<td>Nazwisko:</td>
<td><input type="text" name="nazwisko" /></td>
</tr>
<tr>
<td>Punkty:</td>
<td><input type="text" name="punkty" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Oceń" /></td>
</tr>
</table>
</form>
</body>
</html>
使用 Bean 类:
import java.io.Serializable;
public class Uczen implements Serializable {
private String imie, nazwisko;
private int punkty;
public Uczen() {
}
public Uczen(String imie, String nazwisko, int punkty) {
this.imie = imie;
this.nazwisko = nazwisko;
this.punkty = punkty;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public int getPunkty() {
return punkty;
}
public void setPunkty(int punkty) {
this.punkty = punkty;
}
}
和 Servlet:
public class Ocen extends HttpServlet {
private static final int PROG_PUNKTOWY = 50;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Uczen uczen = (Uczen)request.getAttribute("ucz");
System.out.println(uczen); // <---- here prints null, always, there's no "uczen" object in attributes
String czyZdal = "nie ";
if (uczen.getPunkty() >= PROG_PUNKTOWY) {
czyZdal = " ";
}
request.setAttribute("czyZdal", czyZdal);
request.getRequestDispatcher("/WEB-INF/wynik.jsp").forward(request, response);
}
}
正如我在 servlet 代码中所写的那样,有一点总是打印 null,而不是创建的 bean 类。 Bean 未创建或未添加到属性。
processRequest() 被 doGet() 和 doPost() 调用
这段代码有什么问题?
最佳答案
您将请求发布到您的 Ocen
servlet。当servlet执行时,JSP还没有执行,所以jsp:useBean还没有执行,所以bean还没有在请求中。
jsp:useBean
不应再使用。请求参数应该在 Controller servlet 中读取,而不是在 JSP 中读取。您应该使用 Spring MVC 或 Stripes 等 MVC 框架,它会自动将请求参数转换为表单 bean 并将此表单 bean 传递给操作。
关于java - 为什么请求范围的 bean 不是从表单值创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19092472/