Spring RESTful and Hibernate - spring

I have a very simple database in postgres and i have used hibernate to "connect" to it. Everything works fine, i tested the database with hibernate and no problems so far.
Here is my DAO
#Repository("clientsBasicDao")
#Transactional
public class ClientsBasicDaoImpl implements ClientsBasicDao {
private Log log = LogFactory.getLog(ClientsBasicDaoImpl.class);
private SessionFactory sessionFactory;
private Session session;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
session = sessionFactory.openSession();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly=true)
public List<ClientsBasic> findAllClients() throws HibernateException{
return session.createQuery("from ClientsBasic").list();
}
public ClientsBasic findClientById(int id) throws HibernateException {
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findById").setParameter("id", id).uniqueResult();
}
public ClientsBasic findClientByEmail(String email) throws HibernateException{
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findByEmail").setParameter("email", email).uniqueResult();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findDirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findDirectClients").list();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findIndirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findIndirectClients").list();
}
public ClientsBasic save(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
session.saveOrUpdate(client);
tx.commit();
log.info("Client saved with id: " + client.getClientId());
return client;
}
public void delete(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
Set<Resources> res = client.getClientResources();
if(res.size() > 0){ //there are client access resources for this client
Iterator<Resources> it = res.iterator();
while(it.hasNext()){
Resources resource = it.next();
resource.getClientsBasics().remove(client);
}
}
session.delete(client);
tx.commit();
log.info("Client deleted with id: " + client.getClientId());
}
}
Now, i am trying to learn restful web services so after some tutorials i tried my own implementation. It works, except when i try to use the method that connects to the database.
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
//http://localhost:8080/TestProject/greeting
// or
//http://localhost:8080/TestProject/greeting?name=stackoverflow
#RequestMapping("/greeting")
public #ResponseBody String greeting(
#RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name)).toString();
}
//http://localhost:8080/TestProject/testing
#RequestMapping("/testing")
public #ResponseBody String home(){
return "Welcome, the server is now up and running!";
}
//http://localhost:8080/TestProject/client?id=1
#RequestMapping("/client")
public #ResponseBody String client( //FAILS HERE
#RequestParam(value="id", required=true) String id){
ClientServiceBackend cb = new ClientServiceBackend();
return cb.findClient(Integer.parseInt(id));
}
}
and here is the error
HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1284)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:965)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
and dispatcher:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.project.rest" />
<mvc:annotation-driven />
</beans>
like i said, i am trying to learn rest and this is my 2nd week with spring, so this is all kinda new to me, but i would expect this to work since the database is working fine!
NOTE: I am deploying this on Tomcat v7
can someone please give a hand here?
Thank you :-)
EDIT:
I added the hibernate jar to the tomcat classpath, and now the error is
The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.

Related

GlassFish Server status 404 No mapping found for HTTP request with URI in DispatcherServlet

I'm trying to integrate JSF 2 with Spring and I was following this example and making some modifications to access a DB and execute a Stored Procedure.
But when I run the project I'm getting a Status 404 - Not found from the GlassFish Server. In the console log I'm getting the message:
Warning: No mapping found for HTTP request with URI [/] in DispatcherServlet with name 'dispatcher'
Here is my resulting code:
Folder Structure
Initializer.java
public class Initializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
servletContext.addListener(new ContextLoaderListener(ctx));
servletContext.addListener(new RequestContextListener());
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
AppConfig.java
#Configuration
#ComponentScan("source")
class AppConfig {
#Bean
public Service service() {
DriverManagerDataSource ds = new DriverManagerDataSource("jdbc:mysql://localhost:3306/test?zeroDateTimeBehavior=convertToNull", "root", "rootPass");
ds.setDriverClassName("com.mysql.jdbc.Driver");
return new ServiceImpl(ds);
}
}
ProcBean.java
#ManagedBean(name = "procBean", eager = true)
#RequestScoped
#Component
#RequestMapping("/")
public class ProcBean {
private int input;
private int output;
#Autowired public Service procService;
// Empty constructor, getters/setters
public String callStoredProcedure() {
this.output = procService.callStoredProcedure(input);
return "output";
}
}
ServiceImpl.java
public class ServiceImpl implements Service {
private DataSource dataSource;
private StoredProcedurePrueba prueba;
public ServiceImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
// get/set dataSource
#Override
public int callStoredProcedure(int input) {
this.prueba = new StoredProcedurePrueba(dataSource);
return this.prueba.execute(input);
}
private class StoredProcedurePrueba extends StoredProcedure {
// Implementation tested separately and working correctly
}
}
Configuration
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
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-facesconfig_2_2.xsd">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</application>
</faces-config>
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">
<display-name>JSF 2 + Spring 4 Integration Example</display-name>
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Web pages
<!-- input.xhtml -->
<h:body>
<h3>JSF 2 + Spring 4 Integration Example</h3>
<h:form id="studentForm">
<h:outputLabel value="Enter Student id:" />
<h:inputText value="#{procBean.input}" /> <br />
<h:commandButton value="Submit" action="#{procBean.callStoredProcedure()}"/>
</h:form>
</h:body>
<!-- output.xhtml -->
<h:body>
<h3>JSF 2 + Spring 4 Integration Example</h3>
<p>#{procBean.output}</p>
</h:body>
I was trying some other solutions but none of them works for me. Any idea? What am I missing?
Thanks in advance for your answers.
Not using Spring but I would think you need a welcome-file in web.xml like
<welcome-file-list>
<welcome-file>input.xhtml</welcome-file>
</welcome-file-list>

how to autowire bean in the servlet filters in spring application?

I have a spring-boot application.
I have no ApplicationContext.xml or web.xml files in my project. I prefer to avoid them and have everything configured in Java code.
I have read the following the posts about bean injection in servlet filters.
How can I get a Spring bean in a servlet filter?
http://www.deadcoderising.com/2015-05-04-dependency-injection-into-filters-using-delegatingfilterproxy/
spring injection in servlet filter
After reading them, I started to use DelegatingFilterProxy.
My question is how to autowire the bean into filter and avoid using xml files especially for DelegatingFilterProxy configuration.
The code snipped is available from the second post hosted in github.
public class AuditHandler {
public void auditRequest(String appName, ServletRequest request) {
System.out.println(appName + ": Received request from " + request.getRemoteAddr() );
}
}
public class AuditFilter implements Filter {
private final AuditHandler auditHandler;
private String appName;
public AuditFilter(AuditHandler auditHandler) {
this.auditHandler = auditHandler;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
auditHandler.auditRequest(appName, request);
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
appName = filterConfig.getInitParameter("appName");
}
public void destroy() {}
}
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="auditHandler" class="com.deadcoderising.AuditHandler">
</bean>
<bean id="auditFilter" class="com.deadcoderising.AuditFilter">
<constructor-arg ref="auditHandler"/>
</bean>
</beans>
web.xml
<web-app version="3.0"
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_3_0.xsd"
metadata-complete="true">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<filter>
<filter-name>auditFilter</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>appName</param-name>
<param-value>di-example</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>auditFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
You should add a FilterRegistrationBean to your main Application class (class annotated with #SpringBootApplication) and let Spring provide instance of the AuditHandler:
#Bean
#Autowired
public FilterRegistrationBean auditFilterRegistration(AuditHandler handler) {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new AuditFilter(handler));
filterRegistrationBean.setOrder(3); // ordering in the filter chain
return filterRegistrationBean;
}
If this doesn't work (e.g. your AuditHandler implementation is not annotated properly or it's not on the default package scanning path) you can instruct Spring to provide it (also in your #SpringBootApplication annotated class):
#Bean
public AuditHandler auditHandler() {
return new AuditHandlerImplementation();
}

Request processing failed; nested exception is java.lang.NullPointerException with root cause java.lang.NullPointerException

Here is a brief description of what I am doing.
The application has the form elements in JSP which redirects to the Controller class after pressing submit. The controller calls the service layer which in turn calls DAO and finally adds the records to the data base. The issue I am having is that in the Controller class, I can receive the request parameters (POST) but the thing is that there is an issue while calling the addStudent() of the service layer. The issue is with the Null Pointer Exception on object. Could you guys review the code and provide me suggestions?
Here is the full Stacktrace, throwing errors with pointing the object, i.s nullPointerException.
INFO: Server startup in 4385 ms
Apr 28, 2014 11:45:38 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springDispatcher] in context with path [/StudentManagementSystem] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.vastika.controllers.SpringController.addStudent(SpringController.java:42)
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 org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Here are the codes
SpringController class
package com.vastika.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.vastika.student.model.StudentModel;
import com.vastika.student.services.StudentServiceImpl;
#Controller
#RequestMapping("/students/*")
public class SpringController {
private StudentServiceImpl studentService;
public void setStudentService(StudentServiceImpl studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/students/addstud", method = RequestMethod.POST)
public String addStudent(#RequestParam(value = "name") String name,
#RequestParam(value = "age") String age,
#RequestParam(value = "address") String address,
#RequestParam(value = "email") String email) {
StudentModel student = new StudentModel();
student.setName(name);
student.setAge(age);
student.setAddress(address);
student.setEmail(email);
if (studentService.addStudentService(student)) {
return "Student is added to the database";
}
return "Student is not added to the database";
}
}
StudentServiceImpl Class
package com.vastika.student.services;
import java.util.List;
import com.vastika.student.dao.StudentDaoImpl;
import com.vastika.student.model.StudentModel;
public class StudentServiceImpl implements IStudentService {
private StudentDaoImpl studentDao;
public void setStudentDao(StudentDaoImpl studentDao) {
this.studentDao = studentDao;
}
#Override
public boolean addStudentService(StudentModel student) {
if(studentDao.addStudentDao(student)){
return true;
}
return false;
}
#Override
public boolean delStudentService(int id) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean updateStudentService(StudentModel student) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean getStudentByIdService(int id) {
// TODO Auto-generated method stub
return false;
}
#Override
public List<StudentModel> getAllStudentsService() {
// TODO Auto-generated method stub
return null;
}
}
Model Class:
package com.vastika.student.model;
public class StudentModel {
private int studentId;
private String name;
private String age;
private String address;
private String email;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
spring.xml file
<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="student" class="com.vastika.student.model.StudentModel"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="studentService" class="com.vastika.student.services.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.vastika.student.dao.StudentDaoImpl"/>
<bean id="studentController" class="com.vastika.controllers.SpringController">
<property name="studentService" ref="studentService"></property>
</bean>
</beans>
springdispatcher-servlet.xml file
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.vastika.controllers" />
<!-- <bean id="studentService" class="com.vastika.student.services.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.vastika.student.dao.StudentDaoImpl"/>
<bean id="studentModel" class="com.vastika.student.model.StudentModel"/> -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml file
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springDispatcher-servlet.xml;classpath:spring.xml</param-value>
</context-param>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
-->
</web-app>
index.jsp file
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springDispatcher-servlet.xml;classpath:spring.xml</param-value>
</context-param>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
-->
</web-app>
Check whether the Deployment Descriptor is 3.1 or not, I suppose you have 2.4 version as your Deployment Descriptor which is why the Apache Tomcat could not run.
Then check whether web.xml is placed under
Deployed Resources/WEB-INF/web.xml

Spring: How to define database config?

I try to execute simple request to MySql database via jdbcTemplate but I have an error when framework load and parse xml file whicj define my datasource:
<?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:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_training"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringTrainingTemplate</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml /WEB-INF/jdbc-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and Controller that invoke it:
#Controller
public class HomeController {
#Autowired
private ExampleService exampleService;
#RequestMapping(value = "/details", method = RequestMethod.GET)
public String details(Model model) {
ApplicationContext context = new ClassPathXmlApplicationContext("jdbc-config.xml");
ExampleDao dao = (ExampleDao) context.getBean("ExampleDao");
List<Application> list = dao.getAllApplications();
model.addAttribute("application", list.get(0).getName());
model.addAttribute("descriptionOfApplication", list.get(0).getDescription());
return "details";
}
}
public class ExampleDao {
private String request = "select * from application";
private JdbcTemplate jdbcTemplate;
#Autowired
private DataSource dataSource;
public ExampleDao(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Application> getAllApplications() {
List<Application> applications = this.jdbcTemplate.query(request, new RowMapper<Application>() {
#Override
public Application mapRow(ResultSet rs, int i) throws SQLException {
Application application = new Application();
application.setName(rs.getString("name"));
application.setType(rs.getString("type"));
application.setDescription(rs.getString("description"));
application.setDownloads(rs.getInt("downloads"));
return application;
}
});
return applications;
}
}
Whe I run it and input http://localhost:8080/details I have got an 500 exception with stacktrace with this message:
root cause
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [jdbc-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [jdbc-config.xml] cannot be opened because it does not exist
Can you explain me how to configure jdbc connection in rigth way or if my approach is correct where I should look for a solution of my issue? All help would be appreciated. Thanks.
Spring cannot find your jdbc-config.xml configuration file.
You can put it in your classpath instead of the WEB-INF folder and load it in your web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml,classpath:jdbc-config.xml</param-value>
</context-param>
A good practice is to create folders main and resources in your src folder and to add them in the classpath. Then you can put the spring config file in the src/resources folder.
class path resource [jdbc-config.xml] cannot be opened because it does
not exist
Is the file name correct, where is it located? the file specifying the db connection is not where you said it should be - on the classpath.

Spring web application- java.lang.NullPointerException with jdbcTemplate

I am writing a simple spring 3.0 restful webservice with jdbcTemplate
but i get a java.lang.NullPointerException each time i try to access a resource.
I have created a DAO like this
public interface MisCodeDao {
public void setDataSource(DataSource ds);
//the remaining method declarations
}
}
And my DAOImpl like this
public class MisCodeDAOImp implements MisCodeDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<MisCode> findAll() throws MisCodeDAOException {
if(this.jdbcTemplate==null)
{
System.out.print("JDBC TEMPLATE IS NULL");
}
return (List<MisCode>) this.jdbcTemplate.query("SELECT misCode, misClass, codeDesc, active from miscode", new RowMapper<MisCode>() {
public MisCode mapRow(ResultSet resultSet, int row) throws SQLException {
MisCode miscode = new MisCode();
miscode.setMisCode(resultSet.getString("misCode"));
System.out.print(resultSet.getString("misCode"));
miscode.setMisClass(resultSet.getString("misClass"));
miscode.setCodeDesc(resultSet.getString("codeDesc"));
String charValueStr=resultSet.getString("active");
miscode.setActive(charValueStr.charAt(0));
return miscode;
}
});
}
Here is what my application-context.xml looks like
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driver}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="misCodeDAO" class="com.tavia.bacponline.DaoImpl.MisCodeDAOImp">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
The full stack strace is here:
WARNING: StandardWrapperValve[bacponline]: PWC1406: Servlet.service() for servlet bacponline threw exception
java.lang.NullPointerException
at com.tavia.bacponline.DaoImpl.MisCodeDAOImp.findAll(MisCodeDAOImp.java:67)
at com.tavia.bacponline.controller.MisCodeController.getMisCodes(MisCodeController.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:619)
Here is my controller:
#Controller
public class MisCodeController {
private Jaxb2Marshaller jaxb2Mashaller;
public void setJaxb2Mashaller(Jaxb2Marshaller jaxb2Mashaller) {
this.jaxb2Mashaller = jaxb2Mashaller;
}
private static final String XML_VIEW_NAME = "miscodes";
private MisCodeDAOImp miscodeImpl = new MisCodeDAOImp();
#RequestMapping(method=RequestMethod.GET, value="/miscodes")
public ModelAndView getMisCodes() throws MisCodeDAOException {
List<MisCode> miscodes = miscodeImpl.findAll();
MisCodeList list = new MisCodeList(miscodes);
return new ModelAndView(XML_VIEW_NAME, "miscodes", list);
}
}
And my web.xml looks like this
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>com.tavia.bacponline</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/bacponline-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>bacponline</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bacponline</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks
I may be missing something in your post... but here goes...
The Controller is an annotation based, please indicate the same to spring in the app context file.. also indicate the components to be scanned using
Rather than using
private MisCodeDAOImp miscodeImpl = new MisCodeDAOImp();
use the following for autowiring
#Autowire
private MisCodeDAOImp miscodeImpl;
Since you have already defined the bean in app context file, it should autowire.

Resources