我在jsp中有一個web表單,它應該從servlet獲取值,但是它打印出空值。我在下面包含了jsp和servlet的代碼。任何人都可以告訴我如何解決下面的代碼,以便它打印出請求對象的值而不是打印空值?servlet將空值打印到jsp
這裏是my.jsp代碼:
<jsp:useBean id="errors" scope="request" type="java.util.Map" class="java.util.HashMap" />
<form method="post">
<table>
<tr>
<td width=302>
</td>
<td width=250>
<table>
<tr>
<td width=150 align="right">tha: </td>
<td><input type="text" name="tha" value="c3t" size="15" />
<%if (errors.containsKey("tha")) {out.println("<span class=\"error\">" + errors.get("tha") + "</span>");}
else{out.println(request.getParameter("tha"));}%>
</td>
</tr>
<tr>
<td width=150 align="right">min: </td>
<td><input type="text" name="min" value="0" size="15" />
<% if (errors.containsKey("min")) {out.println("<span class=\"error\">" + errors.get("min") + "</span>");}
else{out.println(request.getParameter("min"));}%>
</td>
</tr>
<tr>
<td width=150 align="right">max: </td>
<td><input type="text" name="max" value="2*pi" size="15" />
<% if (errors.containsKey("max")) {out.println("<span class=\"error\">" + errors.get("max") + "</span>");}
else{out.println(request.getParameter("max"));}%>
</td>
</tr>
<tr>
<td></td>
<td align="right">
<input type="submit" name="submit-button" value="Click To Plot" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
這裏是servlet代碼:
public class PlotPolarServlet extends HttpServlet{
private RequestDispatcher jsp;
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
jsp = context.getRequestDispatcher("/WEB-INF/jsp/my.jsp");
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
jsp.forward(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
Map<String, String> errors = validate(req);
if (!errors.isEmpty()){
jsp.forward(req, resp);
return;
}
resp.sendRedirect("my");
}
public static Map<String, String> validate(HttpServletRequest req){
HashMap<String, String> errors = new HashMap<String, String>();
req.setAttribute("errors", errors);
String tha = req.getParameter("tha");
if (tha == null || tha.trim().length() == 0){
errors.put("tha", "tha required.");
}
String min = req.getParameter("min");
if (min == null || min.trim().length() == 0){
errors.put("min", "min required.");
}
String max = req.getParameter("max");
if (max == null || max.trim().length() == 0){
errors.put("max", "max required.");
}
return errors;
}
}
旁註:擺脫那個實例變量,並在JSP中使用JSTL/EL! – NINCOMPOOP
@TheNewIdiot你能更具體嗎?建議實際行添加/刪除? – CodeMed
@CodeMed所有這些都不是JSTL/EL。 –