我试图处理一个简单的JSP表单,它接受你的名字和姓氏,然后打印:
Your first name: entered_first_name
Your last name: entered_last_name
使用jsp:useBean动作标签,到目前为止没有运气......
让我首先展示我到目前为止所写的内容,然后我将解释这个问题 这就是UserData类的样子:
package pack;
public class UserData {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
这是第一种形式( index.jsp )的样子:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="userinfo" class="pack.UserData" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="userinfo"/>
<body>
<form action="MyServlet" method="post">
First Name: <input type="text" name="firstName"><br>
Last Name: <input type="text" name="lastName"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
这是 MyServlet.java :
的相关部分protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("another.jsp").forward(request, response);
}
这是 another.jsp :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="userinfo" class="pack.UserData"></jsp:useBean>
<body>
Your first name: <%=userinfo.getFirstName() %><br>
Your last name: <%=userinfo.getLastName() %>
</body>
</html>
当我运行index.jsp
时,输入我的名字和姓氏,然后点击&#34;提交&#34;,我得到:
Your first name: null
Your last name: null
这显然很糟糕。
首先,最重要的是:我做错了什么?为什么没有调用setter?
其次,正如您可能已经注意到的,MyServlet.java并没有做太多。它只重定向到another.jsp,所以我真的需要它吗?在重定向之间没有太多工作要做的情况下,是否有更快,更优雅的方式从一个jsp重定向到另一个jsp?
答案 0 :(得分:0)
在转发之前,您必须将一个UserData bean放在servlet中的请求属性中:
UserData userinfo;
userinfo.setFirstName(request.getParameter("firstName");
userinfo.setLastName(request.getParameter("lastName");
request.addAttribute("userinfo", userinfo);
request.getRequestDispatcher("another.jsp").forward(request, response);
如果你想让事情自动发生,你将不得不使用一个框架,如Struts2,Spring MVC或......
答案 1 :(得分:0)
了解Bean
属性
<强>的index.html 强>
<form action="welcome.jsp">
Enter Name:<input type="text" name="firstName"/>
<input type="submit" value="go" />
</form>
<强>的welcome.jsp 强>
<jsp:useBean id="obj" class="pack.UserData" />
<jsp:setProperty name="obj" property="*" />
Welcome, <jsp:getProperty name="obj" property="firstName" />
<强> UserData.java 强>
public class UserData {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
System.out.print("the values are"+firstName);
}
}
您将获得在html页面中输入的值。