[Resolvido] Problemas com Connection em Struts 2 + Spring + MySql

Boa tarde pessoal!

Estou tentando utilizar em minha app o Spring para realizar a conexão com o Banco de Dados. Mas, antes de aplicar as alterações em meu projeto resolvi testar a implementação. Pois bem, estou tendo problemas para realizar a conexão com o BD. Ao executar o cadastro do usuário, o console apresenta esse erro devido a falha na conexão:

[quote]“java.lang.NullPointerException
at br.com.dao.UsuarioDao.cadastrar(UsuarioDao.java:29)
at action.UsuarioAction.cadastrar(UsuarioAction.java:33)”[/quote]

Já testei realizar a conexão sem o uso do Spring e funcionou.
Abaixo estarei postando os códigos do teste:

application-servlet.xml:

[code]<?xml version="1.0" encoding="UTF-8"?>

<bean id="dataSource" 
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/redesocial"></property>
		<property name="username" value="root"></property>
		<property name="password" value="brq"></property>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	</bean>
	
<bean id="usuarioDao" 
  class="br.com.dao.UsuarioDao">
  <property name="dataSource"  ref="dataSource" />    

[/code]

UsuarioDao:

package br.com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import usuario.Usuario;

public class UsuarioDao{

	
	
	private DataSource dataSource;

	public void setDataSource(DataSource dataSource){
		this.dataSource = dataSource;
	}

	public void cadastrar(Usuario u) throws SQLException {
		
		Connection con = null;
		PreparedStatement stmt = null;
		
		try {
			
		 
		con = dataSource.getConnection();
		stmt = con.prepareStatement("insert into usuario values(null,?,?,?,?,?)");
		stmt.setString(1, u.getNome());
		stmt.setString(2, u.getLogin());
		stmt.setString(3, u.getSenha());
		stmt.setString(4, u.getCidade());
		stmt.setString(5, u.getEstado());

		stmt.execute();
		}catch (SQLException e) {
			e.printStackTrace();
		}
	}

}[/code]

[b]UsuarioAction[/b]:
[code]package action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import usuario.Usuario;
import br.com.dao.UsuarioDao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class UsuarioAction extends ActionSupport {

	private static final long serialVersionUID = 1144439383053516678L;

	private Usuario usuario;

	public UsuarioAction() {
		usuario = new Usuario();
	}

	@Action(value="/cadastrar", results = @Result(name="success", location="/index.jsp"))
	public String cadastrar() {
		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);

		try {
			UsuarioDao ud = new UsuarioDao();
			ud.cadastrar(usuario);
			request.setAttribute("msg", "cadastrado com sucesso!");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

}

Como devo realizar essa conexão de forma correta?

Agradeço a atenção.

Posta o stacktrace completo.

Stacktrace completo:

java.lang.NullPointerException
	at br.com.dao.UsuarioDao.cadastrar(UsuarioDao.java:29)
	at action.UsuarioAction.cadastrar(UsuarioAction.java:37)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450)
	at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252)
	at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
	at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
	at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
	at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
	at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
	at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
	at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
	at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
	at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
	at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
	at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
	at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
	at java.lang.Thread.run(Unknown Source)

Minha tabela no MySql:

create table usuario(
			 id integer auto_increment primary key,
			 nome varchar(20),
			 login varchar(20),
			 senha varchar(20),
			 cidade varchar(20),
			 estado varchar(20)
			 );
			 
desc usuario;

UsuarioDao:

[code]import javax.sql.DataSource;

import usuario.Usuario;

public class UsuarioDao{

private DataSource dataSource;  
  
public void setDataSource(DataSource dataSource){  
    this.dataSource = dataSource;  
}  

public void cadastrar(Usuario u) throws SQLException {  
      
    Connection con = null;  
    PreparedStatement stmt = null;  
      
    try {  
          
       
    con = dataSource.getConnection();  
    stmt = con.prepareStatement("insert into usuario values(null,?,?,?,?,?)");  
    stmt.setString(1, u.getNome());  
    stmt.setString(2, u.getLogin());  
    stmt.setString(3, u.getSenha());  
    stmt.setString(4, u.getCidade());  
    stmt.setString(5, u.getEstado());  

    stmt.execute();  
    }catch (SQLException e) {  
        e.printStackTrace();  
    }  
}  

} [/code]

UsuarioAction:

[code]package action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Service;

import usuario.Usuario;
import br.com.dao.UsuarioDao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UsuarioAction extends ActionSupport {

	private static final long serialVersionUID = 1144439383053516678L;


private UsuarioDao ud;
private Usuario usuario;

public UsuarioAction() {
	ud = new UsuarioDao();
	usuario = new Usuario();
}

@Action(value="/cadastrar", results = @Result(name="success", location="/index.jsp"))
public String cadastrar() {
	HttpServletRequest request = (HttpServletRequest) ActionContext
			.getContext().get(ServletActionContext.HTTP_REQUEST);

	try {
		
		ud.cadastrar(usuario);
		request.setAttribute("msg", "cadastrado com sucesso!");

	} catch (Exception e) {
		e.printStackTrace();
	}
	return SUCCESS;
}

public Usuario getUsuario() {
	return usuario;
}

public void setUsuario(Usuario usuario) {
	this.usuario = usuario;
}

public UsuarioDao getUd() {
	return ud;
}

public void setUd(UsuarioDao ud) {
	this.ud = ud;
}

}
[/code]

Agradeço pela atenção!

Coloca um @Autowired antes do private do seu DataSource e um @Override no seu setDataSource, ficando assim

[code]@Autowired
private DataSource dataSource;

@Override
public DataSource getDataSource() {
return dataSource;
}[/code]

No seu application-service.xml, coloque essa a taglib no cabeçalho do seu xml e as linhas antes do seu datasource

<context:annotation-config/> <!-- Scanner @Autowired --> <context:component-scan base-package="seu_package_base"/> <!-- Scanner @Repository @Service -->

Testa aí e qualquer coisa fala!

Fiz as modificações, mas não surtiram efeito… :frowning:

Ficou dessa forma:

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns:tx="http://www.springframework.org/schema/tx" xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">


	<context:annotation-config />
	<context:component-scan base-package="br.com.dao, br.com.action" />

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/redesocial"></property>
		<property name="username" value="root"></property>
		<property name="password" value="brq"></property>
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	</bean>

	<bean id="usuarioDao" class="br.com.dao.UsuarioDao">
		<property name="dataSource" ref="dataSource" />
	</bean>

</beans>
package br.com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import usuario.Usuario;



public class UsuarioDao{

	@Autowired  
	private DataSource dataSource;  
	
      
    public void cadastrar(Usuario u)throws SQLException{  
    	Connection con = null;    
        PreparedStatement stmt = null;    
            
        try {    
                     
        con = dataSource.getConnection();    
        stmt = con.prepareStatement("insert into usuario values(null,?,?,?,?,?)");    
        stmt.setString(1, u.getNome());    
        stmt.setString(2, u.getLogin());    
        stmt.setString(3, u.getSenha());    
        stmt.setString(4, u.getCidade());    
        stmt.setString(5, u.getEstado());    
    
        stmt.execute();    
        }catch (SQLException e) {    
            e.printStackTrace();    
        }    
       
        
    }
    public DataSource getDataSource() {
		return dataSource;
	}
    public void setDataSource(DataSource dataSource){  
        this.dataSource = dataSource;  
    }  

	
    
}  
package action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import usuario.Usuario;
import br.com.dao.UsuarioDao;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;


public class UsuarioAction extends ActionSupport {

		private static final long serialVersionUID = 1144439383053516678L;
	
	
	private UsuarioDao ud;
	private Usuario usuario;
	
	public UsuarioAction() {
		ud = new UsuarioDao();
		usuario = new Usuario();
	}

	@Action(value="/cadastrar", results = @Result(name="success", location="/index.jsp"))
	public String cadastrar() {
		HttpServletRequest request = (HttpServletRequest) ActionContext
				.getContext().get(ServletActionContext.HTTP_REQUEST);

		try {
			
			ud.cadastrar(usuario);
			request.setAttribute("msg", "cadastrado com sucesso!");

		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public UsuarioDao getUd() {
		return ud;
	}

	public void setUd(UsuarioDao ud) {
		this.ud = ud;
	}
	

}

O StackTrace no console:

java.lang.NullPointerException at br.com.dao.UsuarioDao.cadastrar(UsuarioDao.java:27) at br.com.action.UsuarioAction.cadastrar(UsuarioAction.java:36) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:450) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:289) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:252) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Unknown Source)

Já tentei de várias formas mas sempre cai no mesmo erro…

Agradeço pela ajuda… se tiver mais alguma sugestão…

Abs!

Coloca o @Override no seu método getDataSource e no seu application-context.xml, deixa apenas br.com no package-base.

1 curtida

Nada ainda meu camarada…

O estranho é que a anotação @Override gera um erro no método getDataSource… fica sublinhado em vermelho. Já verifiquei a versão do meu compilador e está correta. Em todo caso a aplicação “roda”, mas não consigo gravar no Bando de Dados as informações…

Não sei se ajuda, mas veja como eu faço:

http://rfavero.blogspot.com.br/p/blog-page_30.html

[quote=Roselito Fávero da Silva]Não sei se ajuda, mas veja como eu faço:

http://rfavero.blogspot.com.br/p/blog-page_30.html[/quote]

Obrigado pela orientação.

Eu ainda não consegui realizar essa conexão com o BD. Ontem e hj eu refiz esse teste umas 3 vezes…

Estou utilizando o eclipse Kepler e as .jars que estão sendo usadas são:

[list]
antlr-2.7.2.jar
asm-3.3.jar
asm-commons-3.3.jar
commons-beanutils-1.7.0.jar
commons-digester-1.8.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang-2.4.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
commons-logging-1.1.jar
commons-logging-api-1.1.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
mysql-connector-java-5.0.3-bin.jar
ognl-3.0.6.jar
org.springframework.aop-3.1.0.RELEASE.jar
org.springframework.asm-3.1.0.RELEASE.jar
org.springframework.aspects-3.1.0.RELEASE.jar
org.springframework.beans-3.1.0.RELEASE.jar
org.springframework.context-3.1.0.RELEASE.jar
org.springframework.context.support-3.1.0.RELEASE.jar
org.springframework.core-3.1.0.RELEASE.jar
org.springframework.expression-3.1.0.RELEASE.jar
org.springframework.instrument-3.1.0.RELEASE.jar
org.springframework.instrument.tomcat-3.1.0.RELEASE.jar
org.springframework.jdbc-3.1.0.RELEASE.jar
org.springframework.jms-3.1.0.RELEASE.jar
org.springframework.orm-3.1.0.RELEASE.jar
org.springframework.oxm-3.1.0.RELEASE.jar
org.springframework.test-3.1.0.RELEASE.jar
org.springframework.transaction-3.1.0.RELEASE.jar
org.springframework.web-3.1.0.RELEASE.jar
org.springframework.web.portlet-3.1.0.RELEASE.jar
org.springframework.web.servlet-3.1.0.RELEASE.jar
org.springframework.web.struts-3.1.0.RELEASE.jar
servlet-api.jar
struts2-convention-plugin-2.3.15.1.jar
struts2-core-2.3.15.1.jar
xwork-core-2.3.15.1.jar[/list]

Continuo no aguardo para novas sugestões.

obrigado!

Não sei se pode ser isto, mas anote a classe UsuarioDao com @Repository. Não tenho certeza se o Spring consegue conciliar as anotações e a declaração no XML sem anotar o bean, também…

Bom pessoal! Depois de muito pesquisar, consegui achar a solução!!! :slight_smile:

Eu havia esquecido de um detalhe em minha classe Action. Mais especificamente essas linhas:

ApplicationContext context = new ClassPathXmlApplicationContext("spring/dataSource.xml"); ud = (UsuarioDao)context.getBean("usuarioDao");

Não sei se há outra forma de realizar essa conexão sem a utilização dessas linhas, mas para mim já está suficientemente bom. Agradeço a atenção de todos!!!

Eu criei um pacote chamado spring em /Java Ressources/src… e nele alterei o nome de application-servlet.xml para dataSource.xml.
Ficou dessa forma:

web.xml:

[code]<?xml version="1.0" encoding="ISO-8859-1"?>

Struts 2

index.jsp struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* org.springframework.web.context.ContextLoaderListener [/code]

dataSource.xml:

[code]<?xml version="1.0" encoding="UTF-8"?>

   <bean id="dataSource" 
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/redesocial" />
		<property name="username" value="root" />
		<property name="password" value="brq" />
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	</bean>
	
	<bean id="usuarioDao" class="br.com.dao.UsuarioDao">
		<property name="dataSource" ref="dataSource" />
	</bean>

[/code]

UsuarioDao:

[code]package br.com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import br.com.usuario.Usuario;

public class UsuarioDao {

Connection con;
PreparedStatement stmt;
ResultSet rs;

private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
	this.dataSource = dataSource;
}

public void cadastrar(Usuario u)throws Exception{
	
	con = dataSource.getConnection();
	stmt = con.prepareStatement("insert into usuario values (null, ?,?,?,?,?)");
	stmt.setString(1, u.getNome());
	stmt.setString(2, u.getLogin());
	stmt.setString(3, u.getSenha());
	stmt.setString(4, u.getCidade());
	stmt.setString(5, u.getEstado());
	
	stmt.execute();
	
}

}

[/code]

usuarioAction:

[code]package br.com.action;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import br.com.dao.UsuarioDao;
import br.com.usuario.Usuario;

import com.opensymphony.xwork2.ActionSupport;

public class UsuarioAction extends ActionSupport{

private static final long serialVersionUID = -9090971944172362897L;

private Usuario usuario;
private UsuarioDao ud;

public UsuarioAction() {
 ud = new UsuarioDao();
 usuario = new Usuario();
}

@Action(value="cadastrar", results = @Result(name = "success" , location = "/index.jsp"))
public String Cadastrar(){
	
	try {
		ApplicationContext context =  new ClassPathXmlApplicationContext("spring/dataSource.xml");
		ud = (UsuarioDao)context.getBean("usuarioDao");
		ud.cadastrar(usuario);
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	return SUCCESS;
}

public Usuario getUsuario() {
	return usuario;
}

public void setUsuario(Usuario usuario) {
	this.usuario = usuario;
}

public UsuarioDao getUd() {
	return ud;
}

public void setUd(UsuarioDao ud) {
	this.ud = ud;
}

}
[/code]

Mas eu ainda tenho uma dúvida:
Eu preciso, ainda, utilizar as anotações @Autowired, @Repository, @Service…?

Resolvi voltar a esse post pois estava com a resolução errada… pelo menos em parte.

Bom, na verdade por algum motivo em meu teste tive que manter o arquivo xml (application.xml) na pasta WEB-INF. Sem esse arquivo, o console apresenta erro no mapeamento desse arquivo, e antes que alguém me conteste sobre o local que defini no web.xml, eu já redefini de várias formas, mas sem sucesso. Pesquisei em vários fóruns de fora a respeito desse problema e ainda não achei uma resposta. Bom vou deixar aqui como ficou o teste funcional:

web.xml:

[code]<?xml version="1.0" encoding="ISO-8859-1"?>

Struts 2

index.jsp struts2 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter struts2 /* org.springframework.web.context.ContextLoaderListener applicationContext /WEB-INF/applicationContext.xml

[/code]

applicationContext.xml (este arquivo DEVE estar na pasta WEB-INF como definido no web.xml, e SIM, foi só isso que criei nesse arquivo):

[code]<?xml version="1.0" encoding="UTF-8"?>


[/code]

dataSource.xml (eu aloquei este arquivo na pasta SRC, junto aos pacotes que criei para as classes. Porém ele não está dentro de nenhum sub-pacote ou sub-pasta):

[code]<?xml version="1.0" encoding="UTF-8"?>

    <bean id="dataSource"   
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="url" value="jdbc:mysql://localhost:3306/redesocial" />  
        <property name="username" value="root" />  
        <property name="password" value="brq" />  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
    </bean>  
    <bean id="usuarioDao" class="br.com.dao.UsuarioDao">  
        <property name="dataSource" ref="dataSource" />  
    </bean>

[/code]

usuarioDao:

[code]package br.com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import br.com.usuario.Usuario;

public class UsuarioDao{

Connection con;
PreparedStatement stmt;
ResultSet rs;

private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
	this.dataSource = dataSource;
}

public void cadastrar(Usuario u)throws Exception{
	
	con = dataSource.getConnection();
	stmt = con.prepareStatement("insert into usuario values (null, ?,?,?,?,?)");
	stmt.setString(1, u.getNome());
	stmt.setString(2, u.getLogin());
	stmt.setString(3, u.getSenha());
	stmt.setString(4, u.getCidade());
	stmt.setString(5, u.getEstado());
	
	stmt.execute();
	
}

}

[/code]

usuarioAction:

[code]package br.com.action;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import br.com.dao.UsuarioDao;
import br.com.usuario.Usuario;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UsuarioAction extends ActionSupport {

private static final long serialVersionUID = -9090971944172362897L;

private Usuario usuario;
private UsuarioDao ud;

public UsuarioAction() {
	ud = new UsuarioDao();
	usuario = new Usuario();
}

@Action(value = "cadastrar", results = @Result(name = "success", location = "/index.jsp"))
public String Cadastrar() {

	HttpServletRequest request = (HttpServletRequest) ActionContext
			.getContext().get(ServletActionContext.HTTP_REQUEST);

	try {

		ApplicationContext context = new ClassPathXmlApplicationContext(
				"dataSource.xml");
		ud = (UsuarioDao) context.getBean("usuarioDao");
		ud.cadastrar(usuario);
		request.setAttribute("msg", "Usuário cadastrado com sucesso!");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return SUCCESS;
}

public Usuario getUsuario() {
	return usuario;
}

public void setUsuario(Usuario usuario) {
	this.usuario = usuario;
}

public UsuarioDao getUd() {
	return ud;
}

public void setUd(UsuarioDao ud) {
	this.ud = ud;
}

}
[/code]

Estrutura:


Lembrando que já havia criado a Classe Usuario (desnecessário postá-la).

Espero que isso ajude a alguém que passe pelo mesmo problema que o meu… e por favor, não deixem de postar alguma correção ou diferentes forma de realizar esse teste.

Agradeço toda a ajuda que foi oferecida!

T+!