`
fantlam
  • 浏览: 99030 次
  • 性别: Icon_minigender_1
  • 来自: 佛山
社区版块
存档分类
最新评论

我的SSH项目之旅(3.用户注册--后台)

阅读更多


以上是做好前台验证,接下来是做DAO接口,往数据库里插数据

UserDAO.java

package dj.fantlam.myssh.dao;



import dj.fantlam.myssh.vo.User;



public interface UserDAO {

  //注册

  public void register(User user)throws Exception;



}

 

 

UserDAOImpl.java

 

package dj.fantlam.myssh.daoimpl;



import org.springframework.orm.hibernate3.support.HibernateDaoSupport;



import dj.fantlam.myssh.dao.UserDAO;

import dj.fantlam.myssh.vo.User;

注意要继承自HibernateDaoSupport

public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {



  public void register(User user) throws Exception {

    // TODO Auto-generated method stub

    super.getSession().save(user);



  }



}

 

 

直接用JAVA代码测试,先把数据源改为JDBC方式
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">



<beans>

  <bean id="dataSource"

    class="org.apache.commons.dbcp.BasicDataSource"

    destroy-method="close">

    <property name="driverClassName">

      <value>org.gjt.mm.mysql.Driver</value>

    </property>

    <property name="url">

      <value>jdbc:mysql://localhost:3306/myssh</value>

    </property>

    <property name="username">

      <value>root</value>

    </property>

    <property name="password">

      <value>123456</value>

    </property>

</bean>

  <!-- 

    <bean id="dataSource"

    class="org.springframework.jndi.JndiObjectFactoryBean">

    <property name="jndiName">

    <value>java:comp/env/jdbc/myssh</value>

    </property>

    </beans>

  -->

  <bean id="sessionFactory"

    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">

      <ref bean="dataSource" />

    </property>

    <property name="hibernateProperties">

      <props>

        <prop key="hibernate.dialect">

            org.hibernate.dialect.MySQLDialect

        </prop>

        <!-- 表示允许自动提交 -->

        <prop key="hibernate.connection.autocommit">true</prop>

        <!-- 显示sql语句 -->

        <prop key="hibernate.show_sql">true</prop>

      </props>

    </property>

    <property name="mappingResources">

      <list>

        <value>dj/fantlam/myssh/vo/User.hbm.xml</value>

      </list>

    </property>



  </bean>

  <bean id="hibernateTemplate"

    class="org.springframework.orm.hibernate3.HibernateTemplate">

    <property name="sessionFactory">

      <ref bean="sessionFactory" />

    </property>



  </bean>

  <bean id="userdao" class="dj.fantlam.myssh.dao.UserDAO"

    abstract="true">

  </bean>

  <bean id="userdaoimpl" class="dj.fantlam.myssh.daoimpl.UserDAOImpl"

    parent="userdao">

    <property name="hibernateTemplate">

      <ref bean="hibernateTemplate" />

    </property>

  </bean>



</beans>
 
写一个测试类
UserdaoTest.java
可以成功插入数据 证明后台hibernatespring的整合已经没有问题
package dj.fantlam.myssh.test;



import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



import dj.fantlam.myssh.daoimpl.UserDAOImpl;

import dj.fantlam.myssh.vo.User;



public class UserdaoTest {



  /**

  * @param args

  * @throws Exception 

  */

  public static void main(String[] args) throws Exception {

    // TODO Auto-generated method stub

    ApplicationContext context = null;

        context = new ClassPathXmlApplicationContext("applicationContext.xml");

    UserDAOImpl udi = (UserDAOImpl) context.getBean("userdaoimpl");

    User user = new User();

    //user.setId(123);

    user.setUserid("22");

    udi.register(user);



  }



}

 
出现的错误

1.

Error creating bean with name 'dataSource' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is javax.naming.NoInitialContextException:

java代码直接测试由于连接池要用到tomcat的问题,先改为JDBC连接方式




2.
Unknown entity: dj.fantlam.myssh.vo.User 没有在spring配置

    <property name="mappingResources">
      <list>
        <value>org/lxh/myzngt/vo/User.hbm.xml</value>
      </list>
    </property>





3.

Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not insert: [dj.fantlam.myssh.vo.User]

Caused by: java.sql.SQLException: Table 'myssh.myssh__user' doesn't exist

User.hbm.xml里面

<hibernate-mapping>
<class name="dj.fantlam.myssh.vo.User" table="user"
catalog="myssh"去掉>
   
  </class>
</hibernate-mapping>



4.
严重: IOException while loading persisted sessions: java.io.EOFException
严重: Exception loading sessions from persistent storage


原因是tomcat对硬盘的session读取失败,彻底解决办法一下:将tomcatwork目录下面的文件清空,主要是*.ser文件,或者只是删除掉session.ser即可以解决。




5.
Struts无法验证 因为Struts默认执行public ActionForward execute

用分发Action的时候注意把execute的名字改掉




6.
UserForm里面 最好所有属性都有settergetter方法

由于type没有settergetter方法 导致UserForm都无法验证错误信息 生成之后问题解决






7.
spring没有把dataSource配上去 user.do会找不到

index.html
<html>
<head>
  <title>fantlam</title>
  <META NAME="Generator" CONTENT="Struts + Spring + Hibernate + MySQL + Tomcat + CP">

  <META NAME="Author" CONTENT="fantlam">
  <META NAME="Keywords" CONTENT="SSH,tomcat,mysql">
  <META NAME="Description" CONTENT=" http://fantlam.blogbus.com">
  <META HTTP-EQUIV="refresh" CONTENT="0;URL=jsp/index.jsp">跳转页面
</head>
<body>
</body>
</html>
     

UserAction.java register 插入数据 密码进行加密

      MD5Code mc=new MD5Code();
      User user = new User();
      user.setUserid(userForm.getUserid());
      user.setUserpwd(mc.getMD5ofStr(userForm.getUserpwd()));
      user.setUserques(userForm.getUserques());
      user.setUserans(userForm.getUserans());
      user.setGrade(1);
      this.userdao.register(user);

      request.getSession().setAttribute("userid", user.getUserid());
      request.getSession().setAttribute("grade", user.getGrade());
      return mapping.findForward("regsuc");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return mapping.findForward("regfail");
    }

8. 
this.userdao.register(user);
出现空指针异常java.lang.NullPointerException
出现原因:没有把struts交给spring管理 没有实例化UserDAO
解决办法:
applicationContext.xml中加入
<bean name="/jsp/user" class="dj.fantlam.myssh.struts.action.UserAction">
  <property name="userdao">
    <ref bean="userdaoimpl" />
  </property>
</bean>


index.jsp

<logic:present name="userid" scope="session">
欢迎${userid}光临
头衔:${grade}

</logic:present>



进行注册测试,可以成功插入



以上用JDBC连接方式可以成功注册用户

现在改为用 JNDI 数据源 又出现了这样的问题



org.hibernate.exception.GenericJDBCException: Cannot open connection

这个地方暂时还没解决 以后的代码只能用JDBC方式代替了


 

 

在注册之前要检查用户ID是否已经存在,不存在才插入,存在要返回错误信息

UserDAOImpl.java

  public User queryByUserid(String userid) throws Exception {
    // TODO Auto-generated method stub
  // HibernateDaoSupport的方法取得session
  // protected net.sf.hibernate.Session getSession()
    User user=null;
    String hql="from User as u where u.userid=?";
User注意不要写成user
    Query q=super.getSession().createQuery(hql);
    q.setString(0, userid);
    List l=q.list();
    if(l.size()>0){
      user=(User)l.get(0);
     
    }
    return user;
  }

org.hibernate.QueryException: Expected positional parameter count: 1, actual parameters: [] [from user as u where u.userid=?]

原因是忘了设值q.setString(0, userid);





UserActionregister方法





    User user =this.userdao.queryByUserid(userForm.getUserid());
      if (user == null) {
        user.setUserid(userForm.getUserid());
        user.setUserpwd(mc.getMD5ofStr(userForm.getUserpwd()));
        user.setUserques(userForm.getUserques());
        user.setUserans(userForm.getUserans());
        user.setGrade(1);

        this.userdao.register(user);
  request.getSession().setAttribute("userid", user.getUserid());
  request.getSession().setAttribute("grade", user.getGrade());
        return mapping.findForward("regsuc");
      } else {
        ActionMessages errors = new ActionMessages();
        errors.add("exist", new ActionMessage("user.id.exist"));
        super.saveErrors(request, errors);
        return mapping.getInputForward();

      }



2
1
分享到:
评论
2 楼 fantlam 2008-09-03  
引用
这个还要写配置文件,你写了吗?

谢谢指点,这些问题已经解决了,只是后面的文章还没贴上来
1 楼 Jason(aijun) 2008-09-02  
引用
org.hibernate.exception.GenericJDBCException: Cannot open connection
这个地方暂时还没解决 以后的代码只能用JDBC方式代替了


这个还要写配置文件,你写了吗?

相关推荐

Global site tag (gtag.js) - Google Analytics