spring+struct2+hibernate

最近在做一个ssh的框架遇到了一些问题,把这些错误的情况都记下来


(1)启动失败

在web.xml配置Listener的时候

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
只导入了Spring-web.jar包,显示无错,但是编译不起来。

最后导入了spring-webmvc系列的包才得以解决。


(2)NullPointerException

在struct.xml中需要配置

<struts>
    <constant name="struts.objectFactory" value="spring" />
</struts>

在访问该Action时,会通过class对应值去spring中寻找相同id值的bean。 也可以复制struts2-spring-plugin-x-x-x.jar到WEB-INF/lib目录下。 
在struts2-spring-plugin-x-x-x.jar中有一个struts-plugin.xml配置文件


下面是一个ssh的简单的例子,


首先这是项目结构,这是一个登录的例子,那么先介绍一个been

@Entity
@Table(name = "tb_user", schema = "test")
public class TbUserEntity {
    private Integer id;
    private String username;
    private String pwd;
    private String usertype;


    @Id
    @Column(name = "id")
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Basic
    @Column(name = "username")
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "pwd")
    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Basic
    @Column(name = "usertype")
    public String getUsertype() {
        return usertype;
    }

    public void setUsertype(String usertype) {
        this.usertype = usertype;
    }

我们来编写一个通用dao

public abstract class BaseDao<T> {
    private Class<T> entityClass;

    @SuppressWarnings("unchecked")
    public BaseDao() {
        Type type=getClass().getGenericSuperclass();
        entityClass=(Class<T>) ((ParameterizedType)type).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> getList() {
        Session session = HibernateUtil.getSession();
        List<T> list=null;
        try {
            list=session.createCriteria(entityClass).list();
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return list;
    }

    @SuppressWarnings("unchecked")
    public T getById(String id) {
        Session session = HibernateUtil.getSession();
        try {
            return (T) session.get(entityClass, id);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int add(T t) {
        Session session = HibernateUtil.getSession();
        try {
            session.save(t);
            return 1;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return -1;
    }



    public int delete(T t) {
        Session session = HibernateUtil.getSession();
        try {
            session.delete(t);
            return 1;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public int update(T t) {
        Session session = HibernateUtil.getSession();
        try {
            session.update(t);
            return 1;
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return -1;
    }
    

}
通用dao中实现了crud

下面定义一个userdao的接口

public interface UserDao {
    public TbUserEntity login(String username, String password);
   
}
以及它的实现

public class UserDaoImpl extends BaseDao<TbUserEntity> implements  UserDao{
    @Override
    public TbUserEntity login(String username, String password) {
        try {
            Session session= HibernateUtil.getSession();
            return (TbUserEntity) session.createQuery("from TbUserEntity where username=:username and pwd=:pwd")
                    .setString("username", username)
                    .setString("pwd",password)
                    .uniqueResult();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
    }}

在service中写入userservice 以及它的实现


public interface UserService {

    public int add(TbUserEntity webUser);
    public TbUserEntity login(String username, String password);
}


public class UserServiceImpl implements UserService{
    private UserDao userDao = new UserDaoImpl();

   
    @Override
    public TbUserEntity login(String username, String password) {
        return userDao.login(username,password);
    }

     
}

下面配置hibernate:

利用hibernate 的注解配置,下面是hibernate的工具类

package cn.edu.zucc.util;

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

public class HibernateUtil {
   private static Configuration configuration=null;
   private static ServiceRegistry registry=null;
   private static SessionFactory factory=null;
   private static ThreadLocal<Session> threadLocal=null;
   static {
      configuration=new Configuration().configure();
      registry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
      factory=configuration.buildSessionFactory(registry);
      threadLocal=new ThreadLocal<Session>();
   }
   public static Session getSession(){
      Session session=threadLocal.get();
      if(session==null){
         threadLocal.set(factory.openSession());
         session=threadLocal.get();
      }
      return session;
   }
   public static void closeSession(){
      Session session=threadLocal.get();
      if(session!=null){
         session.close();
         threadLocal.set(null);
      }
   }
}
hibernate .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>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.useUnicode">true</property>
        <property name="connection.characterEncoding">utf8</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <property name="connection.username">root</property>
        <property name="connection.password">zucc</property>

      
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>


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

        <property name="show_sql">true</property>

        <mapping class="cn.edu.zucc.model.TbUserEntity"/> //been的路径

    </session-factory>

好了首先这样一个hibernate简单的就完成了,我们可以简易

public class test {
    public static void main(String[] args) {
/**
 * 测试hibernate
 */      System.out.println("Hibernate测试,取得用户列表:");
         Session session = HibernateUtil.getSession();
         List list=session.createCriteria(TbUserEntity.class).list();
         Iterator iterator = list.iterator();
         while(iterator.hasNext()){
             TbUserEntity userEntity = (TbUserEntity) iterator.next();
             System.out.print(userEntity.getUsername()+ "\t");
             System.out.println(userEntity.getPwd());

         }}


可以看到结果。

接下来配置struct2

写一个UserAction.java

public class UserAction extends ActionSupport {
    private UserService userService;
    private TbUserEntity user = new TbUserEntity();
    public UserAction(){}


    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


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

    public TbUserEntity getUser() {
        return user;
    }


    public String login() throws Exception {
        System.out.println("username=" + this.getUser().getUsername());
        System.out.println("pwd=" + this.getUser().getPwd());
        user = userService.login(this.getUser().getUsername(), this.getUser().getPwd());
        if (user != null) {
            ActionContext.getContext().getSession().put("username",
                    this.getUser().getUsername());
            if(user.getUsertype().equals("normal")){
            return "showuser";}
            else if(user.getUsertype().equals("admin")){
            return "admin";
            }
        }
        return "error";
    }
 可以看到  这里  private UserService userService;
使用了依赖注入的方法。这是在之后配置spring做的铺垫。

下面是struct.xml

<struts>



    <package name="cn.edu.zucc.action" extends="struts-default">
        <action name="UserAction_login" class="cn.edu.zucc.action.UserAction" method="login">
            <result name="showuser">/showuser.jsp</result>
            <result name="error">/index.jsp</result>
            <result name="admin">/admin.jsp</result>
        </action>

</package>
</struts>

可以看到它的名字是

UserAction_login 以及它的所在类

我们在index.jsp中写一个账户登录的页面



<%@ page language="java" contentType="text/html; charset=utf-8"
         pageEncoding="utf-8"%>
<%@ 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=utf-8">
  <title>first struts2</title>
</head>
<body>
<form action="UserAction_login.action" method="post">
  <input   type="text" name="user.username" />
  <input   type="text" name="user.pwd"  />
  <input    type="submit" value="登录" />
  <input    type="reset" value="重填" />
  <input    type="button" value="注册" οnclick="window.location.href='register.jsp';"/>

</form>
</body>
</html>
action指向我们写好的structs.xml中,找到这个名字,然后到达所在的action类,并使用login方法


下面介绍的是spring

先构建一个ApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="UserAction" class="cn.edu.zucc.action.UserAction"  >
      <property name="userService" ref="userService" ></property>
   </bean>
   <bean id="userService" class="cn.edu.zucc.service.UserServiceImpl" />

</beans>

写入对应的名字以及类。



在web.xml中的listener会自动加载ApplicationContext.xml,将userService注入到action中,供action使用。


第一次写,可能写的不是太清晰,见谅。。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值