1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Spring Security X Hibernate X DataSource

Prezados, sou novo no java e comprei recentemente o livro "Programação Java para Web" e até agora tenho conseguido me virar. Na maioria dos exemplos e exercícios a conexão com o banco era feita pelo hibernate.conf.xml e não havia problemas. No capítulo que estou agora o autor propôs melhorar o nível de segurança e utilizar o Spring Framework, mais especificamente o Spring Security para implementação do controle de acesso dos usuários.

Dentro desse contexto as modificações propostas foram:

hibernate.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.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Linhas abaixo removidas para tratamento pelo DataSource JNDI arquivo context.xml
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/financeiro?zeroDateTimeBehavior=convertToNull</property>
        <property name="hibernate.connection.username">user</property>
        <property name="hibernate.connection.password">senha</property> -->
        <property name="hibernate.connection.datasource">java:comp/env/jdbc/FinanceiroDB</property>
        <property name="hibernate.current_session_context_class">thread</property>
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Usando as configurações do C3PO para pool de conexões -->
        <property name="c3po.min_size">5</property>
        <property name="c3po.max_size">20</property>
        <property name="c3po.timeout">300</property>
        <property name="c3po.max_statements">50</property>
        <property name="c3po.idle_test_period">3000</property>

        <!-- Configurações de debug -->
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="generate_statistics">true</property>
        <property name="use_sql_comments">true</property>

        <!-- Mapeando classes -->
        <mapping class="usuario.Usuario"/>     
    </session-factory>
</hibernate-configuration>

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->

<Context reloadable="true">
    <Resource name="jdbc/FinanceiroDB"
              auth="Container"
              type="javax.sql.DataSource"
              maxActive="100"
              maxIdle="30"
              maxWait="10000"
              username="user"
              password="senha"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/financeiro?autoReconnect=true"/>
</Context>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<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-3.0.xsd">

    <bean id="financeiroDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/jdbc/FinanceiroDB</value>
        </property>
    </bean>     
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 
         xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.xhtml</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>DataSource FinanceiroDB</description>
        <res-ref-name>jdbc/FinanceiroDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <!-- Spring Security -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/applicationContext.xml
            /WEB-INF/applicationContext-security.xml
        </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>
    </filter-mapping>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>javaparaweb</groupId>
    <artifactId>financeiro</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Financeiro</name>
    <description>Projeto Financeiro</description>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <repositories>
        <repository>
            <id>jvnet-nexus-releases</id>
            <name>jvnet-nexus-releases</name>
            <url>https://maven.java.net/content/repositories/releases/</url>
        </repository>
        <!-- TAGLIB Spring Security -->
        <repository>
            <id>org.springframework.security.taglibs.facelets</id>
            <url>http://spring-security-facelets-taglib.googlecode.com/svn/repo/</url>
        </repository>
    </repositories>

    <dependencies>
        <!-- Java Server Faces -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.2.12</version>
        </dependency>
        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.1.Final</version>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
            <scope>provided</scope>
        </dependency>
        <!-- Spring Security  -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- TAGLIB Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>facelets-taglib-jsf20-spring-3</artifactId>
            <version>0.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

ConexaoHibernateFilter.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package webFilter;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import util.HibernateUtil;
/**
 *
 * @author Paulinho
 */
@WebFilter (urlPatterns = {"*.jsf"})
public class ConexaoHibernateFilter implements Filter {
    private SessionFactory sf;

    @Override
    public void init(FilterConfig config) throws ServletException{
        this.sf = HibernateUtil.getSessionFactory();
    }

    @Override
    public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse,
            FilterChain chain) throws ServletException{

        Session currentSession = this.sf.getCurrentSession();
        Transaction transaction = null;

        try{
            transaction = currentSession.beginTransaction();
            chain.doFilter(servletRequest, servletResponse);
            transaction.commit();
            if (currentSession.isOpen()){
                currentSession.close();
            }
        } catch (Throwable ex){
            try{
                if (transaction.isActive()){
                    transaction.rollback();
                }
            } catch (Throwable t){
                t.printStackTrace();
            }
            throw new ServletException(ex);
        }
    }
    @Override
    public void destroy(){}
}

Considerando que depois das modificações o sistema perdeu a possibilidade de se conectar ao banco e que agora retorna um erro informando que a transação não está ativa:

Advertência: StandardWrapperValve[FacesServlet]: Servlet.service() for servlet FacesServlet threw exception org.hibernate.HibernateException: save is not valid without active transaction

Sabendo que as classes HibernateUtil e UsuarioBean estavam funcionando corretamente enquanto a configuração de conexão estava no hibernate.cfg.xml, caso alguém possa me ajudar, agradeço antecipadamente.

  • Prezados, se mais alguém conseguir me ajudar, continuo preso no mesmo problema.

    paulorborges   20 de fev de 2016
  • Se não resolveu ainda posta o stacktrace

    Gedson Silva   11 de mar de 2016
  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

1 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags spring-security hibernate ou faça a sua própria pergunta.