Struts2和hibernate3的简单应用-登录验证

来源:互联网 发布:淘宝10.11事变 编辑:程序博客网 时间:2024/05/21 07:02

先附上整体的结构吧
结构
Struts版本是hibernate-distribution-3.6.10.Final
hibernate版本是struts-2.3.24.1-all
一首先是导入jar包
jar包
这里要说明的是我使用Struts和hibernate的包貌似有冲突,所以把cg-lib.jar换成了cglib-nodep-2.13.jar.

二然后是Struts配置
web.xml:

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  <display-name></display-name>   //第一个显示的页面  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  //struts2的过滤器  //struts2可以为任何自定义字符串,单要和过滤映射器同名  <!-- 定义Filter -->  <filter>    <!-- Filter的名字 -->    <filter-name>struts2</filter-name>    <!-- Filter的实现类 -->    <filter-class>        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter    </filter-class>  </filter>  //过滤映射器  <filter-mapping>    <!-- Filter的名字 -->    <filter-name>struts2</filter-name>    <!-- Filter负责拦截的URL中*.action的请求,如果<url-pattern>/* </>,全部以/的请求-->    <url-pattern>*.action</url-pattern>  </filter-mapping></web-app>

Struts.xml:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts>    //包名:user,继承自struts-default;需要访问http://localhost:8080/ForTest/User/Login.action    <package name="user" namespace="/User" extends="struts-default">        <action name="Login">            <result>/login.jsp</result>        </action>        //action name是**Welcome**,class是该action对应的类        <action name="Welcome" class="com.bit.edu.cn.WelcomeUserAction">            <result name="SUCCESS">/welcome_user.jsp</result>            <result name="ERROR">/error.jsp</result>        </action>    </package></struts> 

WelcomeUserAction.java:

package com.bit.edu.cn;import java.util.List;import org.hibernate.Session;import org.hibernate.Transaction;import com.opensymphony.xwork2.ActionSupport;public class WelcomeUserAction extends ActionSupport{    private String username;    private String password;    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    //Action Welcome会执行execute()方法    public String execute() {//      WelcomeUserAction action = new WelcomeUserAction();        List<User> sList = queryResult(username, password);        System.out.println(username+"  "+password);        if(sList.size()>0){            return "SUCCESS";        }        return "ERROR";    }    public List<User> queryResult(String name, String pass){        Session session = HibernateUtil.currentSession();        Transaction ts = session.beginTransaction();        List<User> result = session.createQuery("from User where username='"+name+"' and password="+pass).list();        return result;    }}

四个JSP页面
index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">  </head>  <body>    This is my JSP page. <br>    //登录页面链接    <a href="http://localhost:8080/ForTest/User/Login.action">Login</a> <br>  </body></html>

login.jsp:

<%@ page contentType="text/html; charset=UTF-8"%>//导入Struts标签<%@ taglib prefix="s" uri="/struts-tags"%><html><head></head><body>    <h1>Login Page</h1>    //struts-form 标签    <s:form action="Welcome">        <s:textfield name="username" label="Username" />        <s:password name="password" label="Password" />        <s:submit />    </s:form></body></html>

welcome_user.jsp:

<%@ page contentType="text/html; charset=UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html><head></head><body>    <h1>Login Success Page</h1>    <h2>        Hello        <s:property value="username" />    </h2></body></html>

error.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->  </head>  <body>    Error Page <br>  </body></html>

三hibernate配置
先把数据库贴上来吧:
数据库用的是MySQL,database的名字是hibernate。
数据库
创建数据库:

/*Navicat MySQL Data TransferSource Host     : localhost:3306Source Database : hibernateTarget Host     : localhost:3306Target Database : hibernateDate: 2016-01-03 20:11:37*/SET FOREIGN_KEY_CHECKS=0;-- ------------------------------ Table structure for user-- ----------------------------DROP TABLE IF EXISTS `user`;CREATE TABLE `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(12) DEFAULT NULL,  `password` varchar(12) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;-- ------------------------------ Records of user-- ----------------------------INSERT INTO `user` VALUES ('1', 'heheda', '123');INSERT INTO `user` VALUES ('2', 'dacaibi', '1234');INSERT INTO `user` VALUES ('3', 'xyd', '1234');

hibernate.cfg.xml(hibernate配置文件):

<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>    <session-factory>    <!-- Database connection settings -->    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>    <property name="connection.url">jdbc:mysql://localhost/hibernate</property>    <property name="connection.username">root</property>    <property name="connection.password">2334145</property>    <!-- JDBC connection pool (use the built-in) -->    <!-- <property name="connection.pool_size">1</property> -->    <!-- SQL dialect -->    //方言设置    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>    <!-- Echo all executed SQL to stdout -->    //显示sql语句    <property name="show_sql">true</property>    <!-- Enable Hibernate's automatic session context management -->    <!--<property name="current_session_context_class">thread</property>-->    <!-- Drop and re-create the database schema on startup -->    <!-- <property name="hbm2ddl.auto">create</property> -->    <!-- Disable the second-level cache -->    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>    //映射配置文件    <mapping resource="com/bit/edu/cn/User.hbm.xml"/>    </session-factory></hibernate-configuration>

User.hbm.xml(映射配置文件):

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.bit.edu.cn">    <class name="User">        <id name="id">        //Native主键生成方式会根据不同的底层数据库自动选择Identity、Sequence、Hilo主键生成方式              <generator class="native"></generator>        </id>        <property name="username"></property>        <property name="password"></property>    </class></hibernate-mapping>

User.java:

package com.bit.edu.cn;public class User {    private int id;    private String username;    private String password;    public int getId() {        return id;    }    public String getPassword() {        return password;    }    public String getUsername() {        return username;    }    public void setId(int id) {        this.id = id;    }    public void setPassword(String password) {        this.password = password;    }    public void setUsername(String username) {        this.username = username;    }}

HibernateUtil.java:

package com.bit.edu.cn;import java.util.List;import org.hibernate.HibernateException;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.hql.ast.SqlASTFactory;public class HibernateUtil {    public static SessionFactory sessionFactory ;    static{        try {            //hibernate初始化            sessionFactory = new Configuration().configure().buildSessionFactory();        } catch (Exception e) {            System.err.print("Create SessionFactory Failed!");            e.printStackTrace();        }    }    public static ThreadLocal session = new ThreadLocal();    public static Session currentSession()throws HibernateException {        Session s = (Session) session.get();        if(s==null){            s = sessionFactory.openSession();            session.set(s);        }        return s;    }    public static void  closeSession()throws HibernateException{        Session s = (Session) session.get();        if(s!=null){            s.close();        }        session.set(null);    }}

ReadInfoUser.java(测试连接):

package com.bit.edu.cn;import java.util.List;import org.hibernate.Session;import org.hibernate.Transaction;public class ReadInfoUser {    public static void main(String[] args){        ReadInfoUser rUser = new ReadInfoUser();        List<User> list = rUser.getList();        for(int i=0;i<list.size();i++){            System.out.println(list.get(i).getId());        }    }    private List<User> getList(){        Session session = HibernateUtil.currentSession();        Transaction transaction = session.getTransaction();        List<User> list = session.createQuery("from User").list();        return list;    }}

至此,所有的代码都贴完了,我也是刚接触这些东西,有什么不对的地方,请指出,万分感谢!
下载地址:https://github.com/DevilHeS/LoginProject

0 0
原创粉丝点击