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','352613432@qq.com');
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.数据库的取数据是很有问题的,需要实现通过用户名和密码去匹配,另外再添加注册功能。
struts1&&Hibernate Demo1的更多相关文章
- struts2&&Hibernate Demo1
这篇文章和<struts1&&Hibernate Demo1>基本类似,我这里只是拷贝代码了. 最核心的代码:LoginAction.java package action ...
- Hibernate框架笔记02_主键生成策略_一级缓存_事务管理
目录 0. 结构图 1. 持久化类的编写规则 1.1 持久化和持久化类 1.2 持久化类的编写规则 2. 主键生成策略 2.1 主键的分类 2.2 主键生成策略 3. 持久化类的三种状态[了解] 3. ...
- Hibernate框架笔记01_环境搭建_API_CRUD
目录 1. Hibernate框架的概述 1.1 什么是框架 1.2 经典三层架构 1.3 Hibernate框架 2 Hibernate入门 2.1 下载Hibernate的开发包 2.2 创建项目 ...
- SSH框架之hibernate《三》
Hibernate03 一.多表设计 1.1多表设计的总则 问题:我们为什么要学习多表映射? 答: ...
- hibernate 搭建框架
需要用的包 Hibernate的日志记录: * Hibernate日志记录使用了一个slf4j: * SLF4J,即简单日志门面(Simple Logging Facade for Java),不是具 ...
- 3、Hibernate的多表关联
一.数据库中的表关系: 一对一关系 一个人对应一张身份证,一张身份证对应一个人,一对一关系是最好理解的一种关系,在数据库建表的时候可以将人表的主键放置与身份证表里面,也可以将身份证表的主键放置于人表里 ...
- JavaEE之Hibernate(开放源代码的对象关系映射框架)
Hibernate(开放源代码的对象关系映射框架) 1.简介 Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全 ...
- 【转】pringMVC+Hibernate+Spring 简单的一个整合实例
ref:http://langgufu.iteye.com/blog/2088355 SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,我在博客 ...
- 定时从远程的数据库中取数据,然后把取出来的数据插入或更新本地的oracle数据库的表
最近项目中有一种需求: 大致需求是这样的 通过给定的 用户名和密码 要定时从远程的数据库中取数据,然后把取出来的数据插入或更新本地的oracle数据库的表 项目的结构式struts1 hibernat ...
随机推荐
- webstorm 注册码,亲测可用
WebStorm注册码 User Name: EMBRACE License Key: ===== LICENSE BEGIN ===== 24718-12042010 00001h6wzKLpfo3 ...
- pagemap, from the userspace perspective
pagemap, from the userspace perspective --------------------------------------- pagemap is a new (as ...
- 浅谈 js字符串 trim 方法之正则篇
关于 trim 其实没啥好说的,无非就是去除首位空格,对于现代浏览器来说只是简单的正则 /^\s+|\s+$/ 就可以搞定了.而且支持中文空格 等等.什么 \s 支持 中文空格?是的. 打开 Re ...
- 微信网页授权,微信登录,oauth2
微信官方文档: http://mp.weixin.qq.com/wiki 微信公众平台OAuth2.0授权详细步骤如下: 1. 用户关注微信公众账号.2. 微信公众账号提供用户请求授权页面URL.3. ...
- cf
Financing a capital project with equity may be a signal to investors that a company's prospects are ...
- 云端 Linux下安装 Java
根据需要在给云端的机器安装Java 问题的分解为2个一个是Java源文件的传输.一个是Linux下Java的安装. Java 传输到云端: 可以通过SSH Secure File Transfer C ...
- iOS开发UI篇—手写控件,frame,center和bounds属性
iOS开发UI基础—手写控件,frame,center和bounds属性 一.手写控件 1.手写控件的步骤 (1)使用相应的控件类创建控件对象 (2)设置该控件的各种属性 (3)添加控件到视图中 (4 ...
- LINQ 嵌套查询
直接代码: //获取教材下的章跟篇 IList<Chapter> chapters = EntAppFrameWorkContext.DomainModelService.ExtenedS ...
- OC中intValue要注意的地方
在程序中,发现一个问题,写了个例子,如下: NSDictionary * dict = [[NSDictionary alloc] init]; NSString * s ...
- quartz.net 使用(一)-执行定时计划任务
一.使用nuget安装所需要的包 Install-Package Quartz 二.实现自己的job继承IJob public class FirstJob : IJob { public void ...