用struts和hibernate结合MVC层实例

1、倒包hibernate11个包+sturts2 13个包

2、创建web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>Test27</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

3、创建struts

<?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.action.extension" value="do,action,,"></constant>
    <!-- 定义包 -->
    <package name="index" extends="struts-default">
    <action name="addUser">
    <result>/WEB-INF/pages/addUser.jsp</result>
    </action>
    <!-- 保存User -->
    <action name="saveUser" class="com.hanqi.action.UserAction" method="saveUser">
    
    <result name="fail">/WEB-INF/pages/fail.jsp</result>
    <result >/WEB-INF/pages/success.jsp</result>
    </action>
    <!-- 查询用户 -->
    <action name="selectUser" class="com.hanqi.action.UserAction" method="selectUser">
    
    <result name="fail">/WEB-INF/pages/fail.jsp</result>
    <result >/WEB-INF/pages/selectUser.jsp</result>
    
    </action>
    <!-- 删除用户 -->
    <action name="deleteUser" class="com.hanqi.action.UserAction" method="deleteUser">
    <result name="fail">/WEB-INF/pages/fail.jsp</result>
    <result type="redirectAction">selectUser</result>
    
    
    </action>
    <!-- 修改用户 -->
    
    <action name="EditUser">
    <result>/WEB-INF/pages/EditUser.jsp</result>
    </action>
    <action name="updateUser" class="com.hanqi.action.UserAction" method="updateUser">
    <result name="fail">/WEB-INF/pages/fail.jsp</result>
    <result type="redirectAction">selectUser</result>
    </action>
    
    
    
    </package>
    
    
    
    
</struts>

4、创建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">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.password">123</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
        <property name="hibernate.connection.username">test0816</property>
        <property name="hibernate.default_schema">TEST0816</property>
        <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
         <property name="hibernate.show_sql">true</property>
  <property name="hibernate.format_sql">true</property>
  <!-- 自动建表方式 -->
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- 映射文件 -->
  <mapping resource="com/hanqi/entity/T_User.hbm.xml"/>
  
    </session-factory>
</hibernate-configuration>

5、创建登陆界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="addUser">添加用户</a>
<br><br>
<a href="selectUser">查询用户列表</a>
</body>
</html>

6、按照MVC思想创建包和类

6.1创建实体类和对应的映射文件(可用反向工程)

package com.hanqi.entity;
//持久化类
//不要使用final修饰
import java.util.Date;

public class T_User {
 
    private Integer user_ID;
    private String name;
    private Date birthday;
    private double money;
    private String password;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Integer getuser_ID() {
        return user_ID;
    }
    public void setuser_ID(Integer user_ID) {
        this.user_ID = user_ID;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public double getMoney() {
        return money;
    }
    public void setMoney(double money) {
        this.money = money;
    }
    public T_User(Integer user_ID, String name, Date birthday, double money) {
        super();
        this.user_ID = user_ID;
        this.name = name;
        this.birthday = birthday;
        this.money = money;
    }
    
    public T_User(Integer user_ID, String name) {
        super();
        this.user_ID = user_ID;
        this.name = name;
    }
    //必须提供无参的构造方法
    //需要用到反射
    public T_User() {
        super();
    }
    @Override
    public String toString() {
        return "User [user_ID=" + user_ID + ", name=" + name + ", birthday=" + birthday + ", money=" + money
                + ", password=" + password + "]";
    }
    
    
    
}

对应的映射文件:

<?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 2016-11-16 14:30:38 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
    <class name="com.hanqi.entity.T_User" table="T_USER">
        <id name="user_ID" type="java.lang.Integer">
            <column name="USER_ID" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="birthday" type="java.util.Date">
            <column name="BIRTHDAY" />
        </property>
        <property name="money" type="double">
            <column name="MONEY" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="PASSWORD" />
        </property>
    </class>
</hibernate-mapping>

 

 

6.2创建action类

package com.hanqi.action;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.hanqi.entity.T_User;
import com.hanqi.service.UserService;
import com.opensymphony.xwork2.ActionContext;

public class UserAction {

    //域模型方式
    private T_User user;
    private int userid;
    private String name;
    private String password;
    private Date birthday;
    private double money;

    public int getUserid() {
        return userid;
    }


    public void setUserid(int userid) {
        this.userid = userid;
    }


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public String getPassword() {
        return password;
    }


    public void setPassword(String password) {
        this.password = password;
    }


    public Date getBirthday() {
        return birthday;
    }


    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }


    public double getMoney() {
        return money;
    }


    public void setMoney(double money) {
        this.money = money;
    }


    public T_User getUser() {
        return user;
    }


    public void setUser(T_User user) {
        this.user = user;
    }
    //处理保存User的方法
    public String saveUser()
    {
        String rtn="fail";
        try{
        //调用Service层(模型层,业务逻辑层)
            T_User u1=new UserService().add(user);
            //使用request转发到下一个页面上去
            ActionContext ac=ActionContext.getContext();
            Map<String, Object>mo=(Map<String, Object>)ac.get("request");
            mo.put("user", u1);
            rtn="success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        
        return rtn;
        
        
    }
    //查询
    public String selectUser()
    {
        String rtn="fail";
        try{
            //调用查询的方法
            List<T_User> 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 updateUser()
    {
        String rtn="fail";
        
        try{
            T_User user=new T_User();
            user.setuser_ID(userid);
            user.setPassword(password);
            user.setName(name);
            user.setBirthday(birthday);
            user.setMoney(money);
            new UserService().update(user);        
            rtn="success";
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
        
        
        return rtn;
    }
    
    
}

6.3 创建service层

package com.hanqi.service;

import java.util.List;

import com.hanqi.DAO.UserDAO;
import com.hanqi.entity.T_User;

public class UserService {

    //添加user的方法
    public T_User add(T_User user)
    {
        return new UserDAO().insert(user);
        
    }
    //全表查询
    public List<T_User> getAll()
    {
        return new UserDAO().getAll();
    }
    //删除
    public void delete(int userID)
    {
        new UserDAO().delete(userID);
    }
    //单条查询
    public T_User getUser(int userID)
    {
        return new UserDAO().getUser(userID);
    }
    //执行修改
    public void update(T_User user)
    {
        new UserDAO().updateUser(user);
    }
    
}

6.4 创建DAO层

package com.hanqi.DAO;

import java.util.ArrayList;
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.T_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()
    {
        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 T_User insert(T_User user)
    {
        
        init();
        se.save(user);
        
        destory();
        return user;
        
    }
    //查询列表
    public List<T_User> getAll()
    {
        init();
        List<T_User> rtn=new ArrayList<>();
        rtn=se.createQuery("from T_User").list();
        destory();
        return rtn;
    }
    //删除
    public void delete(int userID)
    {
        init();
        //获取对象
        T_User u=(T_User)se.get(T_User.class, userID);
        
        se.delete(u);
        destory();
    }
    //单条查询
    public T_User getUser(int userID)
    {
        init();
        T_User rtn=null;
        rtn=(T_User)se.get(T_User.class, userID);
        destory();
        return rtn;
    }
    //修改单条查询内容
    public T_User updateUser(T_User user)
    {
        init();
        T_User rtn=null;
        rtn=(T_User)se.get(T_User.class, user.getuser_ID());
        rtn.setuser_ID(user.getuser_ID());
        rtn.setName(user.getName());
        rtn.setPassword(user.getPassword());
        rtn.setBirthday(user.getBirthday());
        rtn.setMoney(user.getMoney());
        destory();
        return rtn;
    }
    
    

}

7、跳转页面

7.1添加用户页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
添加用户
<br><br>
<form action="saveUser" method="post">
用户名:<input type="text" name="user.name"/>
<br>
密码:<input type="password" name="user.password"/>
<br>
生日:<input type="text" name="user.birthday"/>
<br>
薪酬:<input type="text" name="user.money"/>
<br>
<input type="submit" value="保存"/>

</form>

</body>
</html>

7.2查询页面

<%@page import="com.hanqi.entity.T_User"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
List<T_User> lu=(List<T_User>)request.getAttribute("userlist");
for(T_User u:lu)
{
    out.print(u + "【<a href='EditUser?userID="+u.getuser_ID()+"'>修改</a>】【<a href='deleteUser?userID="+u.getuser_ID()+"'>删除</a>】 <br>");    
}


%>

</body>
</html>

7.3 修改用户界面

<%@page import="com.hanqi.entity.T_User"%>
<%@page import="com.hanqi.service.UserService"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<% 
// 接收参数
String userID = request.getParameter("userID");

 T_User us=null;

if (userID == null || 
userID.trim().equals(""))
{
    response.getWriter().print("请正确访问");

}
else
{
     us=new UserService().getUser(Integer.parseInt(userID));
    

}
%>
编辑银行卡信息<br><br>

<form action="updateUser" method="post">
用户id号:<input type="text" name="userid" value="<%=us.getuser_ID() %>"readonly><br>

用户名:<input type="text" name="name" value="<%=us.getName() %>"/>
<br>
密码:<input type="password" name="password" value="<%=us.getPassword() %>"/>
<br>
生日:<input type="text" name="birthday" value="<%=us.getBirthday() %>"/>
<br>
薪酬:<input type="text" name="money" value="<%=us.getMoney() %>"/>
<br>
<input type="submit" value="提交"/>

</form>
</body>
</html>

7.4 操作失败的跳转页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
操作失败
</body>
</html>

7.5 保存成功的跳转页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
操作成功
User=${user }

</body>
</html>

 

转载于:https://www.cnblogs.com/diaozhaojian/p/6072705.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值