struts spring hibernate 三大框架实现基本的增删改查技术

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts spring hibernate 三大框架实现基本的增删改查技术相关的知识,希望对你有一定的参考价值。

/*struts.xml配置*/
1
<?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" 4 "http://struts.apache.org/dtds/struts-2.3.dtd"> 5 6 <struts> 7 8 <package name="packageone" namespace="" extends="struts-default" > 9 <action name="userAction_*" class="com.action.UserAction" method="{1}"> 10 <result name="success">query.jsp</result> 11 <result name="query" type="redirectAction">userAction_query</result> 12 <result name="update">update.jsp</result> 13 </action> 14 </package> 15 16 </struts>

 

/*bean.xml配置*/

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans
 3     xmlns="http://www.springframework.org/schema/beans"
 4     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:aop="http://www.springframework.org/schema/aop"
 7     xmlns:tx="http://www.springframework.org/schema/tx"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans
 9      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
10                         http://www.springframework.org/schema/tx 
11                         http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
12                         http://www.springframework.org/schema/context 
13                         http://www.springframework.org/schema/context/spring-context-4.0.xsd
14                         http://www.springframework.org/schema/aop 
15                         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
16 
17     <context:component-scan base-package="com"/>
18 
19     <!-- 数据源对象    c3p0   DBCP -->
20     <bean name="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
21         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
22         <property name="url" value="jdbc:mysql:///test"></property>
23         <property name="username" value="root"></property>
24         <property name="password" value="root"></property>
25     </bean>
26 
27     <!-- 
28         操作流程:
29             1.配置信息  
30             2.创建sessionFactory
31             3.创建session
32             4.开启事务
33             5.操作数据库
34             6.提交事务
35             7.释放资源
36      -->
37     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
38          <property name="dataSource" ref="dataSource"></property>
39          <property name="hibernateProperties" >
40          
41              <props><!-- hibernate  相关的属性 -->
42                  <prop key="hibernate.show_sql">true</prop>
43                  <prop key="hibernate.hbm2ddl.auto">update</prop>
44                  
45              </props>
46          </property>
47              <!--扫描包  -->
48          <property name="packagesToScan">
49              <value>com.beans</value>
50          </property>
51     </bean>
52     
53         <!--开启   提交事务  -->
54     <bean name="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
55         <property name="sessionFactory" ref="sessionFactory" ></property>
56     </bean>
57     <!--transaction-manager  配置事务管理器     proxy-target-class   如果是ture   表示底层强制使用Cglib  代理-->
58     <!-- <tx:annotation-driven  transaction-manager="txManager"   proxy-target-class="false"/> -->
59     <aop:config>
60         <!--配置AOP  -->
61             <aop:pointcut expression="execution(* com.service.*.*(..))" id="myctu"/>
62             <aop:advisor advice-ref="txAdvice" pointcut-ref="myctu" />
63     
64     </aop:config>
65     <!--配置那些操作是需要开启  提交事务  -->
66     <tx:advice id="txAdvice" transaction-manager="txManager">
67         <tx:attributes>
68             <tx:method name="*" propagation="REQUIRED"/>
69         </tx:attributes>
70     </tx:advice>
71     
72 </beans>                                                            

 

/*com.action.UserAction*/

  1 package com.action;
  2 
  3 import java.util.Date;
  4 import java.util.List;
  5 
  6 import javax.annotation.Resource;
  7 
  8 import org.springframework.stereotype.Controller;
  9 
 10 import com.beans.User;
 11 import com.service.UserService;
 12 
 13 @Controller
 14 public class UserAction {
 15 
 16     
 17     
 18     
 19     @Resource
 20     UserService service; 
 21     String username;
 22     String password;
 23     int  pageSize;//一共显示多少条数据
 24     int  page;//当前页
 25     int total;//总共多少条数据
 26     
 27     User user;
 28     String msg;
 29      List<User>list; 
 30      //添加用户
 31     public String   add(){
 32        
 40         service.add(user);
 41         msg="添加成功";
 42         return "query";
 43     }
 44     //查询用户  
 45     public String query(){
 46         total=service.userCount();
 47         list=    service.queryUser(page,pageSize);
 48         return "success";
 49     }
 50     //删除用户
 51     public String delUser(){
 52         
 53         service.delUser(user);
 54         msg="删除成功";
 55         return "query";
 56     }
 57         //修改用户名
 58     public String  findById(){
 59         user=service.findById(user.getId());
 60         return "update";
 61     }
 62     
 63     public String update(){
 64         service.update(user);
 65         msg="修改成功";
 66         return "query";
 67     }
 68     
 69     //登录功能
 70     public String login(){
 71         
 72         user=service.loginUser(user.getUsername(),user.getPassword());
 73         if(username.equals(user.getUsername())&&password.equals(user.getPassword())){
 74             return null;
 75         }
 76         return msg;
 77     }
 78     
 79     
 80     
 81     
 82     
 83     public User getUuer() {
 84         return user;
 85     }
 86 
 87     public void setUser(User user) {
 88         this.user = user;
 89     }
 90 
 91     public List<User> getList() {
 92         return list;
 93     }
 94 
 95     public void setList(List<User> list) {
 96         this.list = list;
 97     }
 98     public String getMsg() {
 99         return msg;
100     }
101     public void setMsg(String msg) {
102         this.msg = msg;
103     }
104     public int getPageSize() {
105         return pageSize;
106     }
107     public void setPageSize(int pageSize) {
108         this.pageSize = pageSize;
109     }
110     public int getPage() {
111         return page;
112     }
113     public void setPage(int page) {
114         this.page = page;
115     }
116     public int getTotal() {
117         return total;
118     }
119     public void setTotal(int total) {
120         this.total = total;
121     }
122     public String getUsername() {
123         return username;
124     }
125     public void setUsername(String username) {
126         this.username = username;
127     }
128     public String getPassword() {
129         return password;
130     }
131     public void setPassword(String password) {
132         this.password = password;
133     }
134     
135     
136 }

 

/*com.dao.UserDao*/

package com.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.beans.User;

@Repository
public class UserDao {
    
    @Autowired
    private SessionFactory  sessionFactory;
    
    public void add(User user) {
        Session session = sessionFactory.getCurrentSession();//
        session .save(user);
    }

    public void delUser(User user) {
        Session session = sessionFactory.getCurrentSession();//
        session.delete(user);
    }
    //查询及分页
    public List<User> queryUser(int page, int pageSize) {
        Session session = sessionFactory.getCurrentSession();
        Query q=session.createQuery("from User");
        q.setFirstResult((page-1)*pageSize);
        q.setMaxResults(pageSize);
        List<User>list=q.list();
        return list;
    }

    public User findById(int id) {
        Session session = sessionFactory.getCurrentSession();
        User user=(User) session.get(User.class, id);
        return user;
    }

    public void update(User user) {
        Session session = sessionFactory.getCurrentSession();//
        session.update(user);
    }

    public int userCount() {
        Session session = sessionFactory.getCurrentSession();
        Query q=session.createQuery("select count(*) from User");
        int total=Integer.parseInt(q.uniqueResult()+"");
        return total;
    }

    public User loginUser(String username, String password) {
        Session session = sessionFactory.getCurrentSession();
        
        return null;
    }
        

}

 

 

/*com.service.UserService*/

package com.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.beans.User;
import com.dao.UserDao;
@Service
public class UserService {

    
    @Resource
    UserDao dao;
    //添加用户
    public void add(User user) {
        dao.add(user);
    }
    //删除用户
    public void delUser(User user) {
        dao.delUser(user);
        
    }
    //查询
    public List<User> queryUser(int page, int pageSize) {
        
        List <User>list=dao.queryUser(page,pageSize);
        return list;
    }
    //修改用户
    public User findById(int id) {
        
        User user=    dao.findById(id);
        return user;
    }
    public void update(User user) {
        dao.update(user);
        
    }
    public int userCount() {
        int total=dao.userCount();
        return total;
    }
    public User loginUser(String username, String password) {
        User user=dao.loginUser(username,password);
        return user;
    }


}

 

/*com.beans.User*/

 

package com.beans;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
@Entity
public class User {

    private int id;
    private String username;
    private String password;
    private String email;
    private int roleId;
    private Date tdata;
    
    @Id
    @GenericGenerator(strategy="native",name="generator")
    @GeneratedValue(generator="generator")
    @Column(name="id")
    @Type(type="int")
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    
    @Column(name="username")
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    @Column(name="password")
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Column(name="email")
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Column(name="roleId")
    public int getRoleId() {
        return roleId;
    }
    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name="tdata")
    public Date getTdata() {
        return tdata;
    }
    public void setTdata(Date tdata) {
        this.tdata = tdata;
    }
    @Transient
    public  String  getDateStr(){
        SimpleDateFormat  sdf=new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(tdata);
    }
    
}

 

query.jsp    

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core"   prefix="c"%>
<%
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 ‘query.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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<script type="text/javascript"  src="js/jquery-1.4.4.js"></script>
  </head>
  
  <body>
            <table  border="2"   width="70%">
                    <c:forEach  var="user"  items="${list }">/*这里面的list是通过UserAction中提供get set  方法传过来的*/
                                <tr  height="50">
                                        <td>${user.username }</td>
                                        <td>${user.password }</td>
                                        <td>${user.email }</td>
                                        <td>${user.roleId }</td>
                                        <td>${user.tdata }</td>
                                        <td><a  href="userAction_delUser?user.id=${user.id }">删除</a></td>
                                        <td><a  href="userAction_findById?user.id=${user.id }">修改</a></td>
                                </tr>
                    </c:forEach>
            </table>
  </body>
</html>

 

addUser.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
   <form action="userAction_add" method="post">
           用户名<input type="text" name="user.username"><br>
           密码<input type="text" name="user.password"><br>
           邮箱<input type="text" name="user.email"><br>
           角色<input type="text" name="user.roleId"><br>
           日期<input type="text" name="user.tdata"><br>
   <input type="submit"><br>
   </form>
  </body>
</html>

 

update.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 ‘update.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">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
            <form action="userAction_update"  method="post">
                    <input  type="hidden"   name="user.id"   value="${user.id }"><br> 
                    用户名:<input  type="text"   name="user.username"  value="${user.username }"><br>
                    密码:<input  type="text"   name="user.password"  value="${user.password }"><br>
                    email:<input  type="text"   name="user.email"  value="${user.email }"><br>
                    角色:<input  type="text"   name="user.roleId"  value="${user.roleId }"><br>
                    日期:<input  type="text"   name="user.tdata"  value="${user.tdata }"><br>
                    <input  type="submit"  ><br>
            </form>
  </body>
</html>

关于jar包由于某些问题,先把需要那些jar包的图片上传到这里自己去下,也可以问我要,看到会及时回复。

技术分享

技术分享

登录功能未实现,可以 自己参照理解以上内容实现登录功能,如有疑问,请在微博留言 ,或者发邮件到我的qq邮箱进一步探讨,看到会及时回复!

 


以上是关于struts spring hibernate 三大框架实现基本的增删改查技术的主要内容,如果未能解决你的问题,请参考以下文章

SSH整合需要的jar包

jsf struts jsp spring 啥关系和区别?

struts与spring整合

请问spring与struts有啥区别?

struts2 与spring整合

下面关于spring和struts的描述