0
我試圖用hibernate和JSP連接數據庫,下面是我的代碼。使用Hibertane和JSP連接數據庫
我想連接使用JSP只反正它會被轉換爲內部Servlet來冬眠。
我正在自己學習,所以請讓我知道是否有一些愚蠢的錯誤。
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="action.jsp" method="post">
Name <input type="text" name = "name"> <br>
Password <input type="password" name="password"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
action.jsp
<%@page import="org.hibernate.Transaction"%>
<%@page import="p1.User"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@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>
<%
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
// out.println("Configuration object created");
SessionFactory sf = cfg.buildSessionFactory();
Session ses = sf.openSession();
Transaction t = ses.beginTransaction();
String n = request.getParameter("name");
String p = request.getParameter("password");
// out.println("Welcome " + n);
User u1 = new User(n, p);
ses.save();
t.commit();
ses.close();
out.println("Data inserted successfully");
%>
</body>
</html>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate- configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/form?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">tiger</property>
<mapping resource="p1/hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="p1.User" table="user">
<property name="name" column="uname"></property>
<property name="password" column="password"></property>
</class>
</hibernate-mapping>
我已經保存了會話對象,例如: ses.save()和我仍然收到相同的錯誤信息。 – krrish
@krrish問題不在於保存,而是使用無效的DTD。 'ses.save()'看起來像廢話。你認爲'會話'就像是一個心靈感應器,可以全面瞭解'用戶'嗎? –
我正在學習第一次使用hibernate,因此可能會出現錯誤。 請讓我知道是否需要在映射和cfg文件中更改DTD,或只更改它應該更改的DTD。 另外建議如何將數據保存到數據庫到數據庫如果ses.save不是一個好主意。 – krrish