struts2和hibernate整合

一.struts2和hibernate框架分别作用

struts2是MVC框架,而会hibernate是持久层框架。struts2框架是用来接受客户端请求,与数据库打交道,取数据,并响应客户端,而hibernate框架封装数据库,操作数据库。

二.简单流程

在jsp页面中提交数据,struts2里的action里的相关get,set方法获得数据,在该action里定义一个方法传到数据库中,hibernate可以去操作数据库生成相关表,定义一个类去访问数据库,进行数据的增删改查,在通过struts2的配置文件返回给客户端。

三.struts和hibernate整合例子

我举一个简单登录界面的小例子:

1.陪置web.xml文件


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Test17display-name>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-file>
  welcome-file-list>  


  <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>

    <filter-mapping>
        <filter-name>struts2filter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

web-app>

这里应该没什么大问题,只是简单的告诉项目添加了struts2框架。

2.配置struts2文件




<struts>

    
     <constant name="struts.action.extension" value="do,action,,">constant>
     
     <constant name="struts.enable.DynamicMethodInvocation" value="true">constant>
     
     <package name="index" extends="struts-default">

     <action name="addUser">
     <result>/WEB-INF/pages/addUser.jspresult>
     action>

     <action name="addUser2">
      <result>/WEB-INF/pages/addUser2.jspresult>
     action>

     
     <action name="saveUser" class="com.action.UserAction" method="saveUser">
     <result name="fail">/WEB-INF/pages/fail.jspresult>
     <result>/WEB-INF/pages/success.jspresult>
     action>
     

     
     <action name="*" class="com.action.UserAction" method="{1}">
     <result name="fail">/WEB-INF/pages/fail.jspresult>
     <result>/WEB-INF/pages/{1}.jspresult>
     action>
    //利用通配符来配置返回哪个jsp文件


     
     <action name="saveUser2" class="com.hanqi.action.UserAction2" method="saveUser">
     <result name="fail">/WEB-INF/pages/fail.jspresult>
     <result>success.jspresult>
     action>

package>

struts>

3.配置hibernate文件




<hibernate-mapping>
    <class name="com.hanqi.entity.User" table="T_USER">
        <id name="userID" type="int">
            <column name="USER_ID" />
            <generator class="native" />
        id>
        <property name="userName" type="java.lang.String">
            <column name="USER_NAME" length="20" not-null="true" unique="true"/>
        property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" sql-type="DATE"/>
        property>
        <property name="money" type="java.lang.Double">
            <column name="MONEY" sql-type="NUMBER" default="0" length="8" scale="2"/>
        property>
         <property name="password" type="java.lang.String">
        <column name="PASSWORD" length="10">column>
        property> 

    class>
hibernate-mapping>

4.配置user的生成表的相关文件




<hibernate-mapping>
    <class name="com.hanqi.entity.User" table="T_USER">
        <id name="userID" type="int">
            <column name="USER_ID" />
            <generator class="native" />
        id>
        <property name="userName" type="java.lang.String">
            <column name="USER_NAME" length="20" not-null="true" unique="true"/>
        property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" sql-type="DATE"/>
        property>
        <property name="money" type="java.lang.Double">
            <column name="MONEY" sql-type="NUMBER" default="0" length="8" scale="2"/>
        property>
         <property name="password" type="java.lang.String">
        <column name="PASSWORD" length="10">column>
        property> 

    class>
hibernate-mapping>

5.定义usedao类来操作数据库

package com.hanqi.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.hanqi.entity.User;

public class UserDAO {

    private Configuration cfg =null;
    private ServiceRegistry sr =null;

    private SessionFactory sf = null;
    private Session se =null;
    private Transaction ts =null;
    public UserDAO()
    {
        //初始化Hibernate
        cfg = new Configuration().configure();

        sr = new StandardServiceRegistryBuilder().
                applySettings(cfg.getProperties()).build();

    }
    //
    private void init()
    {
        sf= cfg.buildSessionFactory(sr);

        se = sf.openSession();

        ts = se.beginTransaction();
    }
    private void destory()
    {
        ts.commit();
        se.close();
        sf.close();

    }
    //保存User
    public User insert(User user)
    {

        init();
        se.save(user);
        destory();
        return user;
    }
    //查询列表
    public ListgetAll()
    {
        List rtn = new ArrayList<>();

        init();

        rtn=se.createQuery("from User ")
        .list();

        destory();

        return rtn;
    }
    //删除
    public void delete(int userID)
    {
        init();

        //获取对象
        User u=(User)se.get(User.class, userID);

        se.delete(u);

        destory();
    }
    //查询单个
        public User selectUser(int userID)
        {
            init();
            //获取对象
            User u = (User)se.get(User.class, userID);

            destory();

            return u;
        }
    //修改
    public User update(User user)
    {
        init();

        se.update(user);

        destory();

        return user;

    }

}

6.定义service类来操作userdao

package com.hanqi.service;


import java.util.List;

import com.hanqi.dao.UserDAO;
import com.hanqi.entity.User;

public class UserService {

    // 添加User的方法
    public User add(User user)
    {

        return     new UserDAO().insert(user);
    }
    //全表查询

    public List getAll()
    {
        return new UserDAO().getAll();
    }
    //删除记录
    public void delete(int userID)
    {
        new UserDAO().delete(userID);
    }

    //查询单个
    public User select(int userID)
    {
        return new UserDAO().selectUser(userID);
    }
    //修改记录
    public User update(User user)
    {
        return new UserDAO().update(user);
    }
}

7.定义action来接受数据

package com.hanqi.action;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hanqi.entity.User;
import com.hanqi.service.UserService;
import com.opensymphony.xwork2.ActionContext;

public class UserAction {

    //域模型方式
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
    public String insertUser()
    {
        return saveUser();
    }
    //处理保存User的方法
    public String saveUser()
    {
        String rtn ="fail";

        System.out.println(user);    
        try{
        // 调用Service层(模型层,业务逻辑层)
        User u1=new UserService().add(user);

        //使用request转发到下一个页面
        ActionContext ac = ActionContext.getContext();

        Mapmo=(Map)ac.get("request");

        mo.put("user", u1);

        rtn="success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return rtn;
    }
    //查询
    public String selectUser()
    {
        String rtn ="fail";
        try
        {
            //调用查询的方法
            List lu = new UserService().getAll();
            //得到原生的request
            HttpServletRequest hsr=ServletActionContext.getRequest();
            hsr.setAttribute("userlist", lu);
            rtn = "success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return rtn;
    }
    //删除
    public String deleteUser()
    {
        String rtn="fail";
        try
        {
            //获取userid;
            //得到原生的request
            HttpServletRequest hsr=ServletActionContext.getRequest();
            String uid = hsr.getParameter("userid");
            //执行删除
            new UserService().delete(Integer.parseInt(uid));

            rtn = "success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return rtn;
    }
    //查询单条记录
        public String selectd()
        {
            String rtn="fail";
            try
            {
                //得到原生的request
                HttpServletRequest hsr=ServletActionContext.getRequest();
                String uid=hsr.getParameter("userid");
                int userid = Integer.parseInt(uid);
                User u=    new UserService().select(userid);
                hsr.setAttribute("user", u);
                rtn="success";
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return rtn;
        }
    //修改单个用户记录
        public String update()
        {
            String rtn="fail";
            try
            {    
//                HttpServletRequest hsr=ServletActionContext.getRequest();
//                String uid=hsr.getParameter("userid");
                //执行修改
                new UserService().update(user);

                rtn="success";
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return rtn;
        }
    // 分页查询
        public String selectUserf()
        {
            String rtn="fail";
            try
            {
                //得到原生的request 
                HttpServletRequest hsr=    ServletActionContext.getRequest();
                int page= Integer.parseInt(hsr.getParameter("pages"));
                //调用查询的方法
                Listlist=new UserService().selectf(page);
                hsr.setAttribute("pages", page+1);
                hsr.setAttribute("fselect", list);
                rtn="success";
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }

            return rtn;
        }
}

8.定义个测试类

package com.hanqi.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.hanqi.entity.User;
import com.hanqi.service.UserService;
import com.opensymphony.xwork2.ModelDriven;

// 使用模型驱动的方式 
// 实现接口ModelDriven<实体类>
public class UserAction2 implements ModelDriven<User>{
    //必须要实例化
    private User user = new User();
    // 返回实体类的实例
    @Override
    public User getModel() {
    // 返回的必须是模型的 实例

        return user;
    }

    // 保存数据
    public String saveUser()
    {
        String rtn ="fail";

        try
        {
            //保存
            new UserService().add(user);
            HttpServletRequest hsr = ServletActionContext.getRequest();
            hsr.setAttribute("user", user);

            rtn="success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return rtn;
    }


}

9.各jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
<a href="addUser">添加用户a>

<br>
<br>
<a href="selectUser?pages=1">用户列表a>
<br>
<br>
<a href="addUser2">添加用户2a>
body>
html>

你可能感兴趣的:(hibernate)