struts1&&Hibernate Demo1
用struts1和Hibernate实现简单登录案例
主要思路:通过用户名name验证 如果一致则验证成功。
附上源码:
1.建立student表,这里使用的是mysql数据库,以下为该表的DDL:
create table `test`.`student`( `sid` INT not null auto_increment, `sname` VARCHAR(64), `email` VARCHAR(32), primary key (`sid`) ); create unique index `PRIMARY` on `test`.`student`(`sid`);
并插入一条记录:
insert into student(sname,email) values(‘xwj‘,‘[email protected]‘);
2.建立web工程,引入struts1.2包和hibernate3.3包
3.反向工程建立form和*.hbm.xml 以及HibernateSessionFactory文件(也叫PO)。(当然form也可以使用struts-config.xml自动构建,这里我是使用这种方法,不过建议使用第一种)
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.xwj.struts.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; /** * MyEclipse Struts * Creation date: 11-12-2014 * * XDoclet definition: * @struts.form name="studentForm" */ public class StudentForm extends ActionForm { /* * Generated fields */ /** id property */ private Integer id; /** email property */ private String email; /** name property */ private String name; /* * Generated Methods */ /** * Method validate * @param mapping * @param request * @return ActionErrors */ public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub return null; } /** * Method reset * @param mapping * @param request */ public void reset(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub } /** * Returns the id. * @return Integer */ public Integer getId() { return id; } /** * Set the id. * @param id The id to set */ public void setId(Integer id) { this.id = id; } /** * Returns the email. * @return String */ public String getEmail() { return email; } /** * Set the email. * @param email The email to set */ public void setEmail(String email) { this.email = email; } /** * Returns the name. * @return String */ public String getName() { System.out.println("StudentForm.getName()"+name); return name; } /** * Set the name. * @param name The name to set */ public void setName(String name) { this.name = name; } }
student.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"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.xwj.struts.form.StudentForm" table="student" catalog="test"> <id name="id" type="java.lang.Integer"> <column name="sid" /> <generator class="increment" /> </id> <property name="name" type="java.lang.String"> <column name="sname" length="64" /> </property> <property name="email" type="java.lang.String"> <column name="email" length="32" /> </property> </class> </hibernate-mapping>
HibernateSessionFactory.java
package com.xwj.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
另外附上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"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="connection.url">jdbc:mysql:///test</property> <property name="connection.username">xiaoming</property> <property name="connection.password">xiaoming</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="myeclipse.connection.profile">mysql</property> <mapping resource="com/xwj/hibernate/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
3.通过配置文件struts-config.xml实现自动建Action,并且把关键逻辑代码写入这里:
LoginAction.java
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.xwj.struts.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.hibernate.Session; import org.hibernate.Transaction; import com.xwj.hibernate.HibernateSessionFactory; import com.xwj.struts.form.StudentForm; /** * MyEclipse Struts * Creation date: 11-12-2014 * * XDoclet definition: * @struts.action input="/index.jsp" validate="true" */ public class LoginAction extends Action { /* * Generated Methods */ /** * Method execute * @param mapping * @param form * @param request * @param response * @return ActionForward */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub System.out.println("LoginAction.execute()"); StudentForm student = (StudentForm) form; System.out.println("name= "+student.getName()); Session session =HibernateSessionFactory.getSession(); Transaction tx=session.beginTransaction(); StudentForm s = (StudentForm) session.load(StudentForm.class, 1); System.out.println(1); System.out.println("hibernate name:"+s.getName()); // tx.commit(); System.out.println(2); if(s.getName().equals(student.getName())){ System.out.println(3); return mapping.findForward("success"); }else{ System.out.println(4); return mapping.findForward("error"); } } }
附上struts-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd"> <struts-config> <data-sources /> <form-beans > <form-bean name="studentForm" type="com.xwj.struts.form.StudentForm" /> </form-beans> <global-exceptions /> <global-forwards /> <action-mappings > <action attribute="studentForm" input="/WEB-INF/student.jsp" name="studentForm" path="/login" scope="request" type="com.xwj.struts.action.LoginAction"> <set-property property="cancellable" value="true" /> <forward name="error" path="/WEB-INF/error.jsp" /> <forward name="success" path="/WEB-INF/wel.jsp" /> </action> </action-mappings> <message-resources parameter="com.xwj.struts.ApplicationResources" /> </struts-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name /> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
4.编写jsp页面层:
index.jsp(input source)
<form action="login.do" > name:<input type="text" name="name"><br> email:<input type="text" name="email"><br> <input type="submit" value="submit"> </form>
跳转页面wel.jsp 以及error.jsp
<body> This is wel JSP page. <br> hello<%=request.getParameter("name") %> <br>
your email is <%=request.getParameter("email") %> </body>
到这里,大功告成!如果期间遇到问题,建议慢慢来构建工程,我个人先是验证Hibernate配置是否有错,建了testMain文件:
package com.xwj.hibernate; import org.hibernate.Session; import com.xwj.struts.form.StudentForm; public class TestMain { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* //test hibernate Session session = HibernateSessionFactory.getSession(); StudentForm student = (StudentForm) session.load(StudentForm.class, 1); System.out.println("name:"+student.getName()); System.out.println("email:"+student.getEmail());*/ } }
确认没问题在验证struts,如此这样,得到解决问题的方法。
接下来要慢慢完善,1.数据库的取数据是很有问题的,需要实现通过用户名和密码去匹配,另外再添加注册功能。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。