我是JSF的初學者,我似乎無法得到這個權利。我試圖在表單中接受用戶輸入,並在用戶單擊提交時將其插入到數據庫中。所以我必須在在前端只是一種形式和一個提交按鈕裝在窗體標籤:JSF:如何寫入數據庫?
<h:form>
<h:panelGrid columns="2" border="1">
<h:outputLabel value="Job Title: " />
<h:inputTextarea rows="1" cols="65"
id="jobTitle"
value="#{jdFormBean.jobTitle}" />
</h:panelGrid>
<h:commandButton type="submit"
value="Add Job Profile"
action="#{formBean.addJobProfile}" />
</h:form>
的FormBean的:
private String jobTitle;
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getJobTitle() {
return jobTitle;
public void addJobProfile() {
DatabaseHelper.populateDatabase(this.getJobTitle());
的DatabaseHelper:
public class DatabaseHelper {
private static Connection createConnection() throws NamingException,
SQLException {
Context ctx = new InitialContext();
if (ctx == null) {
throw new NamingException("No initial context");
}
Context envContext = (Context) ctx.lookup("java:/comp/env");
if (envContext == null) {
throw new NamingException("No environment context");
}
DataSource ds = (DataSource) envContext.lookup("jdbc/ecr");
if (ds == null) {
throw new NamingException("No data source");
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException("No database connection");
}
return conn;
}
public static void populateDatabase(String jt) {
Connection connection;
try {
connection = createConnection();
String insertSQL = "INSERT INTO JOBPROFILE(JOBTITLE) VALUES (' " + jt + "')";
executeUpdate(connection, insertSQL);
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
catch (NamingException ne) {
ne.printStackTrace();
}
}
private static void executeUpdate(Connection connection, String sql) {
Statement stmt = null;
try {
stmt = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
stmt.setQueryTimeout(30);
stmt.executeUpdate(sql);
} catch (SQLException exc) {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
我也配置了context.xml:
<Resource name="jdbc/ecr" auth="Container"
type="javax.sql.DataSource" username="ecr" password="*******"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:@//host:port/ecrdev"
maxActive="20" maxIdle="10"/>
我想這不是數據庫連接問題,因爲我已經測試過了。將不勝感激任何幫助。 JOBPROFILE表已經在db中創建,託管bean在請求範圍內註冊。我想以此爲榜樣 - >http://docs.aptana.com/docs/index.php/Creating_a_JSF_Application
現在我面臨着這樣的錯誤:java.io.NotSerializableException:org.apache.tomcat.dbcp.dbcp.BasicDataSource
在操作方法中放置一個斷點,看它是否到達它。如果否,請檢查驗證錯誤。頁面是否刷新,或完全沒有任何反應? – Bozho 2010-08-27 07:33:44
java.io.NotSerializableException:org.apache.tomcat.dbcp.dbcp.BasicDataSource – 2010-08-27 08:32:42
@Bozho頁面刷新 – 2010-08-27 08:33:04