Project Structure:
TestController.java:
package com.mypack;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
/**
* Servlet implementation class Test
*/
#WebServlet("/test")
#Controller
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
#Autowired
private TestManager testManager;
public TestManager getTestManager() {
return testManager;
}
public void setTestManager(TestManager testManager) {
this.testManager = testManager;
}
public TestController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
String name=testManager.getName();
PrintWriter pw=response.getWriter();
pw.write(name);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
TestManager.java:
package com.mypack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
#Service("testManager")
public class TestManager {
#Autowired
private TestDao testDao;
public String getName(){
return testDao.getName();
}
public TestDao getTestDao() {
return testDao;
}
public void setTestDao(TestDao testDao) {
this.testDao = testDao;
}
}
TestDao.java:
package com.mypack;
import org.springframework.stereotype.Repository;
#Repository("testDao")
public class TestDao {
public String getName(){
return "Randhir";
}
}
spring.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"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!-- Enable Spring Application Context -->
<context:spring-configured />
<!-- Scan class file in class path for annotated component -> #Component, #Repository, #Service, and #Controller -->
<context:component-scan base-package="com.mypack" />
</beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>SpringIOCWeb</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring.xml
</param-value>
</context-param>
</web-app>
Server Console:
INFO: 1 Spring WebApplicationInitializers detected on classpath
Jan 21, 2017 7:50:39 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Jan 21, 2017 7:50:39 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Jan 21, 2017 7:50:39 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Sat Jan 21 19:50:39 IST 2017]; root of context hierarchy
Jan 21, 2017 7:50:39 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/spring.xml]
Jan 21, 2017 7:50:40 PM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 731 ms
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8090"]
Jan 21, 2017 7:50:40 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Jan 21, 2017 7:50:40 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2836 ms
Jan 21, 2017 7:50:45 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [com.mypack.TestController] in context with path [] threw exception
java.lang.NullPointerException
at com.mypack.TestController.doGet(TestController.java:43)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:724)
IOC Container will instantiate the bean and assign the object reference using setter method. Is my concept is right ?
But here #Autowired doesn't assign the object reference. Till I have used using main method with ApplicationContext and getBean to learn Spring.
But how the bean configuration works with servlet?
Your testManager is null.
You are mixing Servlet and Spring controllers.
You should use Spring dispatcher servlet :
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/spring/*</url-pattern>
</servlet-mapping>
The DispatcherServlet is one unique servlet, like a front controller (in a MVC2 pattern), that dispatches the request to Spring controllers (a spring component).
Then in your controller TestController, remove the inheritance of HttpServlet and override methods (doGet, doPost..), and use #RequestMapping.
In that way you will use the dependency injection of Spring framework.
#Controller
#RequestMapping("/test")
public class TestController {
#Autowired
private TestManager testManager;
#RequestMapping
#ResponseBody
public String handleRequest(final HttpServletRequest request, final HttpServletResponse response) {
String name=testManager.getName();
return name;
}
}
Since you are using servlet and not controller you could autowire it with the code
#WebServlet("/test")
public class TestController extends HttpServlet {
private static final long serialVersionUID = 1L;
private AutowireCapableBeanFactory ctx;
#Autowired
private TestManager testManager;
#Override
public void init() throws ServletException {
super.init();
WebApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(getServletContext());
ctx = context.getAutowireCapableBeanFactory();
ctx.autowireBean(this);
}
...
}
You already have integrated Spring using its own context listener
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Related
I´m updating my project from spring 2.5 to 5 with MVC configuration
I try to make java based config with some problems this is my code:
Web.xml
<web-app
xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Publisher Portal</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
com.netsol.publisher.config.AppConfig
</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>1000</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>publisher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.netsol.publisher.config.SpringWebMvcConfig</param-value>
</init-param>
<description>Spring MVC Dispatcher Servlet</description>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>publisher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
my AppConfig.java
#Configuration
#ComponentScan(excludeFilters=#Filter(org.springframework.stereotype.Controller.class)})
public class AppConfig {
private static final Logger LOG = LoggerFactory.getLogger(AppConfig.class);
#Autowired
private Environment env;
}
And my SpringWebMvcConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.netsol.publisher.controller" })
public class SpringWebMvcConfig implements WebMvcConfigurer {
private static final int CACHE_PERIOD = 31556926; // one year
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/jsp/", ".jsp");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
//this will map uri to jsp view directly without a controller
registry.addViewController("/hi").setViewName("hello");
registry.addViewController("/").setViewName("home.do");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
// Serving static files using the Servlet container's default Servlet.
configurer.enable();
}
#Override
public void addFormatters(FormatterRegistry formatterRegistry) {
// add your custom formatters
}
#Bean
PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("publisher-portal.properties"));
ppc.setIgnoreUnresolvablePlaceholders(true);
return ppc;
}
#Bean
public SimpleUrlHandlerMapping simpleUrlHandlerMapping () {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Integer.MAX_VALUE - 2);
Properties urlProperties = new Properties();
urlProperties.put("/home", "LoginController");
mapping.setMappings(urlProperties);
return mapping;
}
}
My controllers:
#Controller
#RequestMapping(value = "/home")
public class LoginController extends BaseController {
static final String sccsId = "%TC-INFO%";
#Autowired
private PublisherFacade publisherFacade;
private static Log log = LogFactory.getLog(LoginController.class);
#RequestMapping(value = "/index.do", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView showLoginPage(HttpServletRequest request, HttpServletResponse response)
throws Exception {
return getLoginView(request, Constants.USER_LOGIN_PAGE);
}
The problem is that
INFO: Initializing Spring FrameworkServlet 'publisher'
- FrameworkServlet 'publisher': initialization started
- Refreshing WebApplicationContext for namespace 'publisher-servlet': startup date [Wed Sep 19 16:12:08 ART 2018]; parent: Root WebApplicationContext
- No annotated classes found for specified class/package [com.netsol.publisher.config.SpringWebMvcConfig]
- JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
- Looking for #ControllerAdvice: WebApplicationContext for namespace 'publisher-servlet': startup date [Wed Sep 19 16:12:08 ART 2018]; parent: Root WebApplicationContext
- FrameworkServlet 'publisher': initialization completed in 1146 ms
sep 19, 2018 4:12:10 PM org.apache.catalina.core.ApplicationContext log
INFO: Marking servlet [PendingOrderCheckerServlet] as unavailable
sep 19, 2018 4:12:10 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [PendingOrderCheckerServlet] in web application [/publisher-portal] threw load() exception
java.lang.ClassNotFoundException: com.netsol.publisher.batch.PendingOrderCheckerServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1309)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1137)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:546)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:527)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:150)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1044)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4978)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5290)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1420)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1410)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
sep 19, 2018 4:12:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
sep 19, 2018 4:12:10 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
sep 19, 2018 4:12:10 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 31382 ms
- No mapping found for HTTP request with URI [/publisher-portal/home/index.do] in DispatcherServlet with name 'publisher'
- No mapping found for HTTP request with URI [/publisher-portal/home/index.do] in DispatcherServlet with name 'publisher'
I want to know if my configuration its ok and why I cannot found the mappings of my controllers
Trying to run simple spring code, getting NoSuchBeanDefinitionException.
Defined a class in beans.xml with id - "sayHelloImpl".
Created applicationContext of ClassPathXmlApplicationContext class and provided a path to the beans.xml file. When invoking .getBean("sayHelloImpl") getting NoSuchBeanDefinitionException.
beans.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<bean id="sayHelloImpl" class = "com.Impl.SayHelloImpl"></bean>
</beans>
SayHelloImpl.java file
package com.Impl;
import org.springframework.stereotype.Service;
import com.Interface.SayHello;
#Service("sayHelloImpl")
public class SayHelloImpl implements SayHello {
#Override
public String helloSpring() {
System.out.println("inside helloSpring()");
return "Hello Spring 4.1.7";
}
}
Main.java file
package com.Main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.Interface.SayHello;
public class Main {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
"classpath*:beans.xml");
SayHello hello = (SayHelloImpl) applicationContext
.getBean("sayHelloImpl");
System.out.println(hello.helloSpring());
}
}
After executing this main file I am getting below exception on console,
Jan 14, 2018 4:51:15 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#5d099f62: startup date [Sun Jan 14 16:51:15 IST 2018]; root of context hierarchy
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'sayHelloImpl' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1168)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:281)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at com.Main.Main.main(Main.java:14)
Snapshot of the project structure
Just 2 days into java & spring.
Trying to pull data from mySQL DB using spring in a maven project.
Following a tutorial.
But when the code is run, getting the following error(Only a portion of the error is attached).
All the codes are attached below.
error:
Jul 25, 2015 11:00:15 PM
org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext#da2dbb: startup date [Sat Jul 25 23:00:15 IST 2015]; root of context hierarchy
Jul 25, 2015 11:00:15 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/caveofprogramming/spring/test/beans/Beans.xml]
Jul 25, 2015 11:00:16 PM
org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [com/caveofprogramming/spring/props/jdbc.properties]
Jul 25, 2015 11:00:16 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Jul 25, 2015 11:00:16 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'offersDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.caveofprogramming.spring.test.OffersDAO.setDataSource(javax.sql.DataSource); nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at
App.java
package com.caveofprogramming.spring.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/caveofprogramming/spring/test/beans/Beans.xml");
OffersDAO offersDao = (OffersDAO)context.getBean("offersDao");
List<Offer> offers = offersDao.getOffers();
for(Offer offer:offers){
System.out.println(offer);
}
((ClassPathXmlApplicationContext)context).close();
}
}
Offer.java
package com.caveofprogramming.spring.test;
public class Offer {
private String author;
private String title;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "Offer [author=" + author + ", title=" + title + "]";
}
}
OffersDAO.java
package com.caveofprogramming.spring.test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("offersDao")
public class OffersDAO {
private JdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
System.out.println("TESTINGGGGGGGGG in setDataSource");
this.jdbc = new JdbcTemplate(jdbc);
}
public List<Offer> getOffers(){
return jdbc.query("select * from library.book", new RowMapper<Offer>(){
public Offer mapRow(ResultSet rs, int rowNum) throws SQLException {
Offer offer = new Offer();
offer.setTitle(rs.getString("title"));
offer.setAuthor(rs.getString("author"));
return offer;
}});
}
}
jdbc.properties
jdbc.username = root
jdbc.password = 123456
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/library
Beans.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.caveofprogramming.spring.test"> </context:component-scan>
<context:property-placeholder
location="com/caveofprogramming/spring/props/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
</bean>
</beans>
Do ask, if more clarity is needed.
Thanks in advance
Your exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool which basically means the required java class is not on the class path.
The problem is due to commons-pool not being in your class path.
Ideally this should be availed when your add the apache tomcat server as a server in your project and doing will get the commons-pool from the server
If this is not the case then kindly add it in the lib folder by downloading it
If it's a maven project then it has it in the pom.xml
commons-pool
commons-pool
1.5.6
I have following web.xml configuration where exception is thrown at com.mkyong.context.ContextSecond in contextInitialized() method. In that case deployment does not stop and app.war keep servicing. How I can stop deployment when exception occurs?
Using weblogic 12c
Archetype Created Web Application
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>com.mkyong.context.ContextFirst</listener-class>
</listener>
<listener>
<listener-class>com.mkyong.context.ContextSecond</listener-class>
</listener>
ContextFirst .java
package com.mkyong.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextFirst implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ContextFirst:contextDestroyed");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ContextFirst:contextInitialized");
}
}
ContextSecond .java
package com.mkyong.context;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextSecond implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("ContextSecond:contextDestroyed");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("ContextSecond:contextInitialized");
throw new RuntimeException();
}
}
Log:
<Nov 19, 2014 1:52:36 PM EET> <Warning> <Deployer> <BEA-149124> <Failures were detected while initiating remove task for application "webservices". Error is: "[Deployer:149001]No a
pplication named "webservices" exists for operation "undeploy".">
ContextFirst:contextInitialized
ContextSecond:contextInitialized
<Nov 19, 2014 1:53:05 PM EET> <Warning> <HTTP> <BEA-101162> <User defined listener com.mkyong.context.ContextSecond failed: java.lang.RuntimeException.
java.lang.RuntimeException
at com.mkyong.context.ContextSecond.contextInitialized(ContextSecond.java:18)
at weblogic.servlet.internal.EventsManager$FireContextListenerAction.run(EventsManager.java:678)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
I am new in hibernate and i want to do hibernate annotation and auto generate table in mysql as i submit data.but i have some error like sql grammar.please help me to solve this error.my all code is below..
My Jsp File
<html>
<head>
</head>
<body>
<form action="controller" method="post">
Id : <input type="text" name="id"><br>
First-Name : <input type="text" name="fName"><br>
Last-Name : <input type="text" name="lName"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
This is My Pojo Class
package com.connection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "csl_emp")
public class Employee {
#Id
private int id;
private String firstName, lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
This is my servler
package com.connection;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class controller
*/
public class controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public controller() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("in the controller");
String id = request.getParameter("id");
String fname = request.getParameter("fName");
String lname = request.getParameter("lName");
System.out.println(id + fname + lname);
Employee employee = new Employee();
employee.setFirstName(fname);
employee.setLastName(lname);
employee.setId(Integer.parseInt(id));
EmpDao dao = new EmpDao();
dao.addData(employee);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/success.jsp");
requestDispatcher.forward(request, response);
}
}
This is mY dao class
package com.connection;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
public class EmpDao {
public void addData(Employee employee) {
Session session = new AnnotationConfiguration().configure().buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.saveOrUpdate(employee);
transaction.commit();
session.close();
}
}
And This is my Configuration File
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javadb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">true</property>
<mapping class="com.connection.Employee"/>
</session-factory>
</hibernate-configuration>
And I have getting error like this
Sep 12, 2013 11:49:25 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\java\jdk1.6.0_43\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin/server;C:/Program Files/java/jdk1.6.0_43/bin/../jre/bin;C:/Program Files/java/jdk1.6.0_43/bin/../jre/lib/amd64;C:\Windows\System32;C:\Program Files\java\jdk1.6.0_43\bin;C:\Program Files\apache-ant-1.8.4\bin;C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin;D:\eclipse;;.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:jspcrud' did not find a matching property.
Sep 12, 2013 11:49:26 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Hibernate-J2EE-Annotation' did not find a matching property.
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:27 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:27 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2769 ms
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Sep 12, 2013 11:49:27 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.40
Sep 12, 2013 11:49:28 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [203] milliseconds.
Sep 12, 2013 11:49:30 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(E:\projects\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Hibernate-J2EE-Annotation\WEB-INF\lib\servlet-api-2.4.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Sep 12, 2013 11:49:31 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Sep 12, 2013 11:49:31 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 3324 ms
in the controller
1chiragsoni
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Sep 12, 2013 11:49:48 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [controller] in context with path [/Hibernate-J2EE-Annotation] threw exception
org.hibernate.exception.SQLGrammarException: could not retrieve snapshot: [com.connection.Employee#1]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1039)
at org.hibernate.engine.StatefulPersistenceContext.getDatabaseSnapshot(StatefulPersistenceContext.java:232)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:189)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState(AbstractSaveEventListener.java:487)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:84)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
at com.connection.EmpDao.addData(EmpDao.java:12)
at com.connection.controller.doPost(controller.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1008)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
at java.lang.Thread.run(Thread.java:662)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.csl_emp' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2624)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2127)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2293)
at org.hibernate.persister.entity.AbstractEntityPersister.getDatabaseSnapshot(AbstractEntityPersister.java:1012)
... 28 more
In your configuration file add this property:
<property name="hibernate.hbm2ddl.auto" value="update" />
and also, very useful are these:
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
From Hibernate docs
Change your configuration file property as below
<property name="hibernate.hbm2ddl.auto" value="create"/>
instead of
<property name="hbm2ddl.auto">true</property>