这将是一个奇怪的问题,我会尽力解释它,但要忍受我。
我有一个.jsp页面,其中包含一个表单以输入信息,一个提交。这个问题。实际上它包含更多数据)。
我的主要问题是我无法获得一个请求对象来了解键入newForm.jsp的任何数据。例如,在调试时,在constructInSertStatement()函数的内部,myTextbox的值始终为null。
我会发布我拥有的内容,希望有人能告诉我我缺少的东西。
newform.jsp
<html>
<head>
<sx:head />
</head>
<body>
<s:form action="submitNew" method="post" namespace="/">
<s:textfield label="Text Box" name="myTextBox"
<s:submit label="Submit" name="submit_btn" align="center" />
</s:form>
</body>
</html>
提交Action.java
public class SubmitAction extends ActionSupport {
private Request request = new Request();
public void executeInsert() throws SQLException{
Connection conn = null;
PreparedStatement ps = null;
try {
ps = request.constructInsertStatement();
// execute the INSERT Statement
ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
}
}
request.java
public class Request {
private String myTextBox;
public PreparedStatement constructInsertStatement() throws SQLException{
PreparedStatement ps = null;
Connection conn = null;
String URL = "myURL";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
conn = DriverManager.getConnection(URL, "defaultUser", "defaultPassword");
String sql = "INSERT INTO `myTable` (SomeText)";
sql += "VALUES";
sql+="(?)";
ps = conn.prepareStatement(sql);
try{
ps.setString(1, myTextBox);
} catch (SQLException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return ps;
}
public String getmyTextBox() {
return myTextBox;
}
public void setmyTextBox(String myTextBox) {
this.myTextBox = myTextBox;
}
Struts.xml Action
<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="submitNew"
class="my.package.path.SubmitAction" method="executeInsert">
<result name="success">NewForm.jsp</result>
</action>
</package>
</struts>
要获得一个 Request
对象,你应该有一个getter
public Request getMyRequest() { return request; }
要为此对象设置值
public String getMyTextBox() {
return myTextBox;
}
public void setMyTextBox(String myTextBox) {
this.myTextBox = myTextBox;
}
如果您想了解更多有关OGNL访问豆的属性的更多信息,请参见struts2通过变量案例答案。
要将此对象绑定到文本字段,您应该在名称属性中使用通往属性的路径。
<s:textfield label="Text Box" name="myRequest.myTextBox" />