一个简单的Struts Hibernate入门例子(上)

本文介绍了一个使用Struts框架实现的学生管理系统,包括学生信息的增删改查等功能。系统通过MyEclipse开发环境搭建,利用Hibernate作为持久层框架进行数据库操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上图为MyEclipse截图
源代码如下:
package com.student.action;

import org.apache.struts.action.*;
import org.apache.struts.actions.*;
import javax.servlet.http.*;

import com.student.entity.Student;
import com.student.service.StudentService;

import java.util.Collection;
import java.sql.Date;

public class StudentAction extends DispatchAction
{
	private StudentService service = new StudentService();
	
	public ActionForward find(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ActionForward forward = mapping.findForward("list");
		
		try
		{
			Collection students = service.find();	
			request.setAttribute("students", students);
		}catch(Exception e)
		{
			e.printStackTrace();
			forward = mapping.findForward("error");
		}
		
		return forward;
	}
	
	public ActionForward tomodify(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ActionForward forward = mapping.findForward("modify");
		
		try
		{
			String id = request.getParameter("id");
			Student student = service.findById(Integer.parseInt(id));
			request.setAttribute("student", student);
		}catch(Exception e)
		{
			e.printStackTrace();
			forward = mapping.findForward("error");
		}
		
		return forward;
	}
	
	public ActionForward add(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ActionForward forward = mapping.findForward("tolist");
		
		try
		{
			String name = request.getParameter("name");
			String birthday = request.getParameter("birthday");
			Student student = new Student();
			student.setName(name);
			student.setBirthday(Date.valueOf(birthday));
			service.add(student);
		}catch(Exception e)
		{
			e.printStackTrace();
			forward = mapping.findForward("error");
		}
		
		return forward;
	}
	
	public ActionForward modify(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ActionForward forward = mapping.findForward("tolist");
		
		try
		{
			String name = request.getParameter("name");
			String birthday = request.getParameter("birthday");
			int id = Integer.parseInt(request.getParameter("id"));
			Student student = new Student();
			student.setId(id);
			student.setName(name);
			student.setBirthday(Date.valueOf(birthday));
			service.modify(student);
		}catch(Exception e)
		{
			e.printStackTrace();
			forward = mapping.findForward("error");
		}
		
		return forward;
	}
	
	public ActionForward remove(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		ActionForward forward = mapping.findForward("tolist");
		
		try
		{
			String id = request.getParameter("id");
			service.remove(Integer.parseInt(id));
		}catch(Exception e)
		{
			e.printStackTrace();
			forward = mapping.findForward("error");
		}
		
		return forward;
	}
	
	public ActionForward toadd(ActionMapping mapping, ActionForm form, 
												HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		return mapping.findForward("add");
	}
}

package com.student.entity;

import java.sql.Date;
import java.io.Serializable;

public class Student implements Serializable
{
	private int id;
	private String name;
	private Date birthday;
	
	public void setId(int id)
	{
		this.id = id;
	}
	
	public int getId()
	{
		return id;
	}
	
	public void setName(String name)
	{
		this.name = name;
	}
	
	public String getName()
	{
		return name;
	}
	
	public void setBirthday(Date birthday)
	{
		this.birthday = birthday;
	}
	
	public Date getBirthday()
	{
		return birthday;
	}
}

package com.student.filter;

import java.io.IOException;
import javax.servlet.*;

public class CharacterEncodingFilter implements Filter
{

	protected String encoding = null;
	protected FilterConfig filterConfig = null;
	protected boolean ignore = true;

	public void destroy()
	{
		this.encoding = null;
		this.filterConfig = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		if (ignore || (request.getCharacterEncoding() == null))
		{
			String encoding = selectEncoding(request);
			if (encoding != null)
				request.setCharacterEncoding(encoding);				
		}
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException
	{

		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
		String value = filterConfig.getInitParameter("ignore");
		if (value == null)
			this.ignore = true;
		else if (value.equalsIgnoreCase("true"))
			this.ignore = true;
		else if (value.equalsIgnoreCase("yes"))
			this.ignore = true;
		else
			this.ignore = false;
	}

	protected String selectEncoding(ServletRequest request)
	{
		return (this.encoding);
	}
}

package com.student.service;

import com.student.entity.Student;
import com.student.util.HibernateUtil;

import java.util.Collection;

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

public class StudentService
{
	public void add(Student student)
	{
		  Session session = null;
        Transaction trans = null;

        try
        {
            session = HibernateUtil.getSession();
            trans = session.beginTransaction();
            session.save(student);
            trans.commit();
        } catch (RuntimeException e)
        {
            trans.rollback();
            e.printStackTrace();
            throw e;
        } finally
        {
            session.close();
        }
	}
	
	public void modify(Student student)
	{
		  Session session = null;
        Transaction trans = null;

        try
        {
            session = HibernateUtil.getSession();
            trans = session.beginTransaction();
            session.update(student);
            trans.commit();
        } catch (RuntimeException e)
        {
            trans.rollback();
            e.printStackTrace();
            throw e;
        } finally
        {
            session.close();
        }
	}
	
	public void remove(int id)
	{
		  Session session = null;
        Transaction trans = null;

        try
        {
            session = HibernateUtil.getSession();
            trans = session.beginTransaction();
            Query query = session.createQuery("delete from Student where id = :id");
            query.setInteger("id", id);
            query.executeUpdate();
            trans.commit();
        } catch (RuntimeException e)
        {
            trans.rollback();
            e.printStackTrace();
            throw e;
        } finally
        {
            session.close();
        }
	}
	
	public Student findById(int id)
	{
		  Session session = null;
        Transaction trans = null;
        Student student = null;

        try
        {
            session = HibernateUtil.getSession();
            trans = session.beginTransaction();
            Query query = session.createQuery("select student from Student student where student.id = :id");
            student = (Student)query.setInteger("id", id).uniqueResult();
            trans.commit();
        } catch (RuntimeException e)
        {
            trans.rollback();
            e.printStackTrace();
            throw e;
        } finally
        {
            session.close();
        }
        
        return student;
	}
	
	public Collection find()
	{
		  Session session = null;
        Transaction trans = null;
        Collection students = null;

        try
        {
            session = HibernateUtil.getSession();
            trans = session.beginTransaction();
            Query query = session.createQuery("select student from Student student");
            students = query.list();
            trans.commit();
        } catch (RuntimeException e)
        {
            trans.rollback();
            e.printStackTrace();
            throw e;
        } finally
        {
            session.close();
        }
        
        return students;
	}
}


package com.student.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil
{
    private static SessionFactory factory = null;

    static
    {
        try
        {
            Configuration config = new Configuration();
            factory = config.configure().buildSessionFactory();
        } catch (Throwable e)
        {
            System.err.println("Initial SessionFactory creation failed." + e);
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Session getSession()
    {
        return factory.openSession();
    }
    
    public static Session getCurrentSession()
    {
        return factory.getCurrentSession();
    }
}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值