Struts2+Hibernate 实现增删改用户

1. 配置

导入jar包至 WebContent/WEB-INF/lib



在工程src下添加 hiberneta.cfg.xml

<?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/test</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></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>

        <!-- Enable Hibernate's automatic session context management -->
        <!--  <property name="current_session_context_class">thread</property>-->

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">false</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="com/unicom/demo/bean/User.hbm.xml"/>

    </session-factory>

</hibernate-configuration>


添加bean, User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 2015-3-23 10:30:39 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.unicom.demo.bean.User" table="USER">
        <id name="ID" type="long">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
    </class>
</hibernate-mapping>


2. DAO

<pre name="code" class="java">package com.unicom.demo.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.unicom.demo.bean.User;
import com.unicom.demo.dao.IDao;
import com.unicom.demo.hibernate.HibernateUtil;

public class UserDaoHiber implements IDao {
	SessionFactory factory = HibernateUtil.getSessionFactory();
	Session session = factory.openSession();

	@Override
	public void add(User user) {
		// TODO Auto-generated method stub
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();
		Transaction t = session.beginTransaction();
		String userName = user.getUsername();
		String password = user.getPassword();
		try {
			// SQL语句
			String sql = "insert into user(name,password) " + " VALUES ( '"
					+ userName + "','" + password + "')";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			query1.executeUpdate();

			t.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void deleteById(long id) {
		// TODO Auto-generated method stub
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();
		Transaction t = session.beginTransaction();

		try {
			// SQL语句
			String sql = "delete from user where id = ?";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			query1.setLong(0, id);// 设定条件参数
			query1.executeUpdate();

			// TODO 提交事务
			t.commit();
			System.out.println("delete success!!");
		} catch (Exception e) {
			e.printStackTrace();

		}

	}

	@Override
	public User selectById(long id) {
		// TODO Auto-generated method stub
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();
		try {
			// SQL语句
			String sql = "select * from user where id = ?";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			query1.setLong(0, id);
			List<User> userList = query1.list();

			for (User user2 : userList) {
				String name = user2.getUsername();
				String password = user2.getPassword();
				return new User(id, name, password);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void updateById(User user) {
		// TODO Auto-generated method stub

		/**
		 * 超鏈接:edit: action:method-> select ?user.id=XXXX
		 * 
		 * update method獲取一個User select * from user where id=user.id
		 * 
		 * update.jsp 從前台獲取後台的 這個User
		 */
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();
		Transaction t = session.beginTransaction();
		long ID = user.getID();
		String userName = user.getUsername();
		String password = user.getPassword();

		try {
			String sql = "update user set name = ?,password = ? where id = ?";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			query1.setString(0, userName);
			query1.setString(1, password);
			query1.setLong(2, ID);
			query1.executeUpdate();
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public String select(User user) {
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();

		// 传入的用户的用户名与密码
		String userName = user.getUsername();
		String password = user.getPassword();
		Map<String, String> users = new HashMap<String, String>();

		try {
			// SQL语句
			String sql = "select * from user";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			List<User> userList = query1.list();

			for (User user2 : userList) {
				users.put(user2.getUsername(), user2.getPassword());
			}

			if (users.containsKey(userName)
					&& users.get(userName).equals(password)) {
				return "1";
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "0";
	}

	@Override
	public List<User> findAll() {
		// SessionFactory factory = HibernateUtil.getSessionFactory();
		// Session session = factory.openSession();

		try {
			// SQL语句
			String sql = "select * from user";
			Query query1 = session.createSQLQuery(sql).addEntity(User.class);
			List<User> userList = query1.list();
			// for (User user2 : userList) {
			// Long id = user2.getID();
			// String name = user2.getUsername();
			// String password = user2.getPassword();
			// User u = new User(id, name ,password );
			// userList.add(u);
			// }
			return userList;
			// for (User user2 : userList) {
			// Long id = user2.getID();
			// String name = user2.getUsername();
			// String password = user2.getPassword();
			// return new User(id, name ,password );
			// }

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// public static void main(String args[]){
	// UserDaoHiber udj = new UserDaoHiber();
	// User u = udj.selectById(18l);
	// u.setUsername("test");
	// u.setPassword("test");
	// udj.updateById(u);
	//

	// }

}




3. Action

定义一个updateId用来前后台传值

package com.unicom.demo.action;

import java.util.List;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.unicom.demo.bean.User;
import com.unicom.demo.dao.IDao;
import com.unicom.demo.dao.impl.UserDaoHiber;


public class UserAction extends ActionSupport {

	public String getUpdateId() {
		return updateId;
	}

	public void setUpdateId(String updateId) {
		this.updateId = updateId;
	}

	public List<User> getUsers() {
		return findAll();
	}

	private static final long serialVersionUID = 1L;

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}

	private User user;
	private List<User> users;

	public String login() throws Exception {
		// IDao userDao = new UserDaoJDBC();

		IDao userDao = new UserDaoHiber();
		String result = userDao.select(user);

		if ("1".equals(result)) {
			return "success";
		} else {
			return "error";
		}
	}

	public List<User> findAll() {
		IDao userDao = new UserDaoHiber();
		users = userDao.findAll();

		return users;
	}

	public String add() throws Exception {
		IDao userDao = new UserDaoHiber();
		userDao.add(user);
		return "success";
	}

	public String deleteById() throws Exception {
		UserDaoHiber udj = new UserDaoHiber();
		long delId = user.getID();
		udj.deleteById(delId);
		return "success";
	}

	private String updateId;

	public String selectById() throws Exception {
		UserDaoHiber udj = new UserDaoHiber();
		user = udj.selectById(Long.parseLong(updateId));
		return "success";
	}

	public String updateById() throws Exception {
		IDao udj = new UserDaoHiber();
		User u = udj.selectById(Long.parseLong(updateId));
		u.setUsername(user.getUsername());
		u.setPassword(user.getPassword());
		udj.updateById(u);
		return "success";
	}

}


4. struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
	<constant name="struts.enable.DynamicMethodInvocation" value="false" />
	<constant name="struts.devMode" value="true" />
   <package name="userLoginPackage" extends="struts-default">
       
   <action name="loginAction" class="com.unicom.demo.action.UserAction"
        method="login">
   <result name="success">/loginSuccess.jsp</result>
   <result name="error">/loginError.jsp</result>
	</action>
	<action name="addAction" class="com.unicom.demo.action.UserAction"
        method="add">
   <result name="success">/addsuccess.jsp</result>
    </action>
    
	<action name="delAction" class="com.unicom.demo.action.UserAction"
        method="deleteById">
   <result name="success">/delsuccess.jsp</result>
    </action>   
    
    <action name="selectByIdAction" class="com.unicom.demo.action.UserAction"
        method="selectById">
   		<result >/update.jsp</result>
    </action>
    
    <action name="updateAction" class="com.unicom.demo.action.UserAction"
        method="updateById">
   		<result name="success">/updatesuccess.jsp</result>
    </action> 
      
    <action name="findAllAction" class="com.unicom.demo.action.UserAction"
        method="findAll">
    </action> 
	</package>
	<!-- Add packages here -->
</struts>


5. jsp页面

loginSuccess.jsp  用s标签动态获取数据库信息

<%@page import="com.opensymphony.xwork2.ActionContext"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*,java.io.*,java.util.*"%>
<%@ page import="com.opensymphony.xwork2.*"%>
<%@ page import="com.opensymphony.xwork2.util.*"%>
<%@ page import="com.unicom.demo.bean.User"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style type="text/css">
table {
	border: 2px #CCCCCC solid;
	width: 360px;
}

td, th {
	height: 30px;
	border: #CCCCCC 1px solid;
}
</style>
</head>
<body>
	<center>


		<form action="findAllAction">
			<table
				class="table table-striped table-bordered table-hover table-condensed">
				<tr>
					<th>ID</th>
					<th>Name</th>
					<th>Password</th>
				</tr>
				<s:iterator value="users">
					<a href="<s:url action="findAllAction" />"></a>
					<tr>
						<td><s:property value="ID" /></td>
						<td><s:property value="username" /></td>
						<td><s:property value="password" /></td>
						<td><a
							href='delAction.action?user.ID=<s:property value="ID"/>'>delete</a>
							<!-- <a
							href='selectByIdAction.action?user.ID=<s:property  value="ID"/>'>edit</a></td>
							 --> <a
							href='selectByIdAction.action?updateId=<s:property value="ID" />'>edit</a></td>
					</tr>
				</s:iterator>

				<tr align="center">
					<td colspan="4"><a href="add.jsp">add</a></td>
				</tr>
			</table>
			>

			<%
				ActionContext cxt = ActionContext.getContext();
				ValueStack stack = cxt.getValueStack();
				User user = (User) stack.findValue("user");
				out.println(user.getUsername());
				out.println(user.getPassword());
			%>

		</form>

	</center>
</body>
</html>

再分别写一下各自跳转页面

最后效果







阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页