[英]Why request-scoped bean is not created from form values?
我已經創建了這樣的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>
與豆類:
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或未將其添加到屬性中。
doRequest()和doPost()都調用processRequest()
這段代碼有什么問題?
您將請求發布到Ocen
servlet。 當執行servlet時,JSP尚未執行,因此jsp:useBean
尚未執行,因此Bean不在請求中。
jsp:useBean
不應該再使用了。 請求參數應該在控制器servlet中讀取,而不是在JSP中讀取。 您應該使用Spring MVC或Stripes之類的MVC框架,該框架會自動將請求參數轉換為表單bean,並將該表單bean傳遞給操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.