-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 
Author Message
 Post subject: Hibernate and Spring
PostPosted: Thu Jun 17, 2010 7:54 am 
Beginner
Beginner

Joined: Thu Jun 17, 2010 7:36 am
Posts: 26
Hello,

Im new to Spring and Hibernate in general and I am trying to create my first small webapplication.
I am using Spring MVC, Spring Security and Hibernate.

I have a login page, a register page and links for users and admins. Registering does not work because I waited with implementing it until I use Hibernate.

Well, I have two really dumb questions, but I hope that you can help me.
I configured my dataSource-beans and the hibernate stuff (except the hibernate.cfg.xml) in my security-config.xml. Ive got a SessionFactory there. Then I have a class called HibernateDao which extends HibernateDaoSupport. There I can call getHibernateTemplate() and do some actions. This class HibernateDao which is referenced with my SessionFactory is configured also as a bean in my security-config.
And that is my problem. From another class, for example my RegisterController.java, I dont know how to access this bean!!! Its really stupid, I guess, but please tell me how to do it!!

The other question I have is according spring security authentication manager: is the configuration <sec:jdbc-user-service data-source-ref="securityDataSource"/> right?
and, which now comes in my mind - is class="org.apache.commons.dbcp.BasicDataSource" the right to use for my dataSource?

Please help me with my dumb questions and please, if you see another mistake or if you could give me an advice in how to develope such applications better (or easier)- please tell me.

Here are some of my configurations: (I tried to mark the most important things so that it is easier to look through) (I actually noticed that marking things in code does not work. Well, I let the {b}s there so you can see what I would have marked - maybe easier although its not written fat.... )

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

     <sec:authentication-manager>
        <sec:authentication-provider>
           <sec:password-encoder hash="plaintext"/>
[b]         <sec:jdbc-user-service data-source-ref="securityDataSource"/>[/b]
        </sec:authentication-provider>
     </sec:authentication-manager>

   <sec:http auto-config="true">

      <sec:form-login login-page="/index"
                  default-target-url="/index"
                  always-use-default-target="true"
                  authentication-failure-url="/index?login_error=1"/>
                  
      <sec:logout logout-success-url="/logout" />
      
      <sec:intercept-url pattern="/**/admin" access="ROLE_ADMIN"/>
      <sec:intercept-url pattern="/**/user" access="ROLE_USER, ROLE_ADMIN"/>
      <sec:intercept-url pattern="/index" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
      
      <sec:session-management invalid-session-url="/index" session-fixation-protection="newSession">
            <sec:concurrency-control max-sessions="1" error-if-maximum-exceeded="true"/>
        </sec:session-management>

   </sec:http>
   
[b]<bean id="projectDao" class="com.security.mvc.HibernateDao">
   <property name="sessionFactory" ref="sessionFactory"/>
</bean>[/b]

[b]<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource" ref="securityDataSource"/>  [/b]
    <property name="mappingResources">
   
      <list>
         <value>mappingdatei.hbm.xml</value>
      </list>
   </property>
   <property name="hibernateProperties">
      <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
      </props>
   </property>
</bean>

[b]   <bean id="securityDataSource" destroy-method="close"
      class="org.apache.commons.dbcp.BasicDataSource">[/b]
        <property name="driverClassName" value="${db.driver}"/>
        <property name="url" value="${db.url}"/>
        <property name="username" value="${db.user}"/>
        <property name="password" value="${db.password}"/>
   </bean>
   
   <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
         <property name="location" value="WEB-INF/db.properties"/>
   </bean>

  </beans>


web.xml
Code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

     <filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

<servlet>
    <servlet-name>jspDispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value>
            /WEB-INF/spring/jspDispatcher-servlet.xml
         </param-value>
      </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>jspDispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>
[b]          /WEB-INF/security-config.xml[/b]
     </param-value>
  </context-param>

  <filter>
     <filter-name>springSecurityFilterChain</filter-name>
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
 
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
  </filter-mapping>

  <listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
   </listener> 
   
    <listener>
      <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
    </listener>
   
[b]  <filter>
      <filter-name>HibernateSession</filter-name>
      <filter-class>
         org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
      </filter-class>
   </filter>[/b]

<filter-mapping>
[b]   <filter-name>HibernateSession</filter-name>
      <url-pattern>/*</url-pattern>[/b]
          <dispatcher>REQUEST</dispatcher>
          <dispatcher>FORWARD</dispatcher>
          <dispatcher>INCLUDE</dispatcher>
          <dispatcher>ERROR</dispatcher>
</filter-mapping>

</web-app>


HibernateDao.java
Code:
package com.security.mvc;

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

public class HibernateDao extends HibernateDaoSupport {

   public void saveUsers(Users u){
      getHibernateTemplate().save(u);   
   }
}


RegisterController.java
Code:
package com.security.mvc;

import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/register")
public class RegisterController {

   private Logger logger = org.slf4j.LoggerFactory.getLogger(WelcomeController.class);

   @RequestMapping(method = RequestMethod.GET)
   public void welcome() {
      logger.info("Register HP GET!");
   }
   
   @RequestMapping(method = RequestMethod.POST)
   public void register(@RequestParam String username, @RequestParam String password, Model model) {

      Users user = new Users();
      user.setUsername(username);
      user.setPassword(password);
      user.setEnabled(true);

[b]      /*thats how I used to do it without webapplication!!
      ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "security-config.xml" });
      BeanFactory factory = context;
      HibernateDao projectDao = (HibernateDao) factory.getBean("projectDao");
      projectDao.saveUser(user);
      */[/b]

   }
}



thanks for your help!!!


Top
 Profile  
 
 Post subject: Re: Hibernate and Spring
PostPosted: Thu Jun 17, 2010 10:48 am 
Beginner
Beginner

Joined: Thu Jun 17, 2010 7:36 am
Posts: 26
well I tried to solve it with uncommenting the part in the RegisterController.java

Code:
      ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "security-config.xml" });
      BeanFactory factory = context;
      HibernateDao projectDao = (HibernateDao) factory.getBean("projectDao");
      projectDao.saveNewUser(user);
      projectDao.saveNewAuthorities(auth);

      


And adding this to web.xml
Code:
  <context-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>
          <!-- /WEB-INF/security-config.xml --> 
          classpath:security-config.xml
     </param-value>
  </context-param>


So I can access from web.xml a file which lies in the classpath and in my java-file I can access the security-config.xml too
But that cant be right, because so it will be called twice: from web.xml and from RegisterController.java - is that right?!?


Top
 Profile  
 
 Post subject: Re: Hibernate and Spring
PostPosted: Fri Jun 18, 2010 9:49 am 
Beginner
Beginner

Joined: Thu Jun 17, 2010 7:36 am
Posts: 26
I dont know... but if someone is interested:
working with member variablen and dependency injection is, I guess, the simple answer.
thanks.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 3 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.