Can anyone tell me why iam getting this Exception? - java

Exception at org.springframework.beans.factory.BeanCreationException:Error
creating bean with name'myDBAuthenticationService': Injection of autowired dependencies failed; nested exception is Org.springframework.beans.factory.BeanCreationException:Could not autowire field: private org.o7planning.springmvcshopp
AdminController.java
package org.o7planning.springmvcshoppingcart.controller;
import java.util.List;
import org.o7planning.springmvcshoppingcart.dao.OrderDAO;
import org.o7planning.springmvcshoppingcart.dao.ProductDAO;
import org.o7planning.springmvcshoppingcart.model.OrderDetailInfo;
import org.o7planning.springmvcshoppingcart.model.OrderInfo;
import org.o7planning.springmvcshoppingcart.model.PaginationResult;
import org.o7planning.springmvcshoppingcart.model.ProductInfo;
import org.o7planning.springmvcshoppingcart.validator.ProductInfoValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import
org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
#Controller
// Enable Hibernate Transaction.
#Transactional
// Need to use RedirectAttributes
#EnableWebMvc
public class AdminController {
#Autowired
private OrderDAO orderDAO;
#Autowired
private ProductDAO productDAO;
#Autowired
private ProductInfoValidator productInfoValidator;
// Configurated In ApplicationContextConfig.
#Autowired
private ResourceBundleMessageSource messageSource;
#InitBinder
public void myInitBinder(WebDataBinder dataBinder) {
Object target = dataBinder.getTarget();
if (target == null) {
return;
}
System.out.println("Target=" + target);
if (target.getClass() == ProductInfo.class) {
dataBinder.setValidator(productInfoValidator);
// For upload Image.
dataBinder.registerCustomEditor(byte[].class, new
ByteArrayMultipartFileEditor());
}
}
// GET: Show Login Page
#RequestMapping(value = { "/login" }, method = RequestMethod.GET)
public String login(Model model) {
return "login";
}
#RequestMapping(value = { "/accountInfo" }, method = RequestMethod.GET)
public String accountInfo(Model model) {
UserDetails userDetails = (UserDetails)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(userDetails.getPassword());
System.out.println(userDetails.getUsername());
System.out.println(userDetails.isEnabled());
model.addAttribute("userDetails", userDetails);
return "accountInfo";
}
#RequestMapping(value = { "/orderList" }, method = RequestMethod.GET)
public String orderList(Model model, //
#RequestParam(value = "page", defaultValue = "1") String pageStr) {
int page = 1;
try {
page = Integer.parseInt(pageStr);
} catch (Exception e) {
}
final int MAX_RESULT = 5;
final int MAX_NAVIGATION_PAGE = 10;
PaginationResult<OrderInfo> paginationResult //
= orderDAO.listOrderInfo(page, MAX_RESULT, MAX_NAVIGATION_PAGE);
model.addAttribute("paginationResult", paginationResult);
return "orderList";
}
// GET: Show product.
#RequestMapping(value = { "/product" }, method = RequestMethod.GET)
public String product(Model model, #RequestParam(value = "code",
defaultValue = "") String code) {
ProductInfo productInfo = null;
if (code != null && code.length() > 0) {
productInfo = productDAO.findProductInfo(code);
}
if (productInfo == null) {
productInfo = new ProductInfo();
productInfo.setNewProduct(true);
}
model.addAttribute("productForm", productInfo);
return "product";
}
// POST: Save product
#RequestMapping(value = { "/product" }, method = RequestMethod.POST)
// Avoid UnexpectedRollbackException (See more explanations)
#Transactional(propagation = Propagation.NEVER)
public String productSave(Model model, //
#ModelAttribute("productForm") #Validated ProductInfo productInfo,
//
BindingResult result, //
final RedirectAttributes redirectAttributes) {
if (result.hasErrors()) {
return "product";
}
try {
productDAO.save(productInfo);
} catch (Exception e) {
// Need: Propagation.NEVER?
String message = e.getMessage();
model.addAttribute("message", message);
// Show product form.
return "product";
}
return "redirect:/productList";
}
#RequestMapping(value = { "/order" }, method = RequestMethod.GET)
public String orderView(Model model, #RequestParam("orderId") String
orderId) {
OrderInfo orderInfo = null;
if (orderId != null) {
orderInfo = this.orderDAO.getOrderInfo(orderId);
}
if (orderInfo == null) {
return "redirect:/orderList";
}
List<OrderDetailInfo> details =
this.orderDAO.listOrderDetailInfos(orderId);
orderInfo.setDetails(details);
model.addAttribute("orderInfo", orderInfo);
return "order";
}
}
POM.XML
<properties>
<java-version>1.8</java-version>
</properties>
<repositories>
<!-- Repository for ORACLE JDBC Driver -->
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Servlet API -->
<!-- http://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -
->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- Jstl for jsp page -->
<!-- http://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- JSP API -->
<!-- http://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- Apache Commons FileUpload -->
<!-- http://mvnrepository.com/artifact/commons-fileupload/commons-
fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- Spring dependencies -->
<!-- http://mvnrepository.com/artifact/org.springframework/spring-core -
->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-web --
>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc
-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.springframework/spring-orm --
>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<!-- Spring Security Artifacts - START -->
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-web -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-config -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!--
http://mvnrepository.com/artifact/org.springframework.security/spring-
security-taglibs -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
<!-- Spring Security Artifacts - END -->
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-
entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>4.3.11.Final</version>
</dependency>
<!-- MySQL JDBC driver -->
<!-- http://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<!-- Oracle JDBC driver -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<!-- SQLServer JDBC driver (JTDS) -->
<!-- http://mvnrepository.com/artifact/net.sourceforge.jtds/jtds -->
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
<version>1.3.1</version>
</dependency>
<!-- PostgreSQL driver -->
<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
<!-- Email validator,... -->
<!-- http://mvnrepository.com/artifact/commons-validator/commons-
validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.5.0</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMVCANnotationShoppingCart</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source> <!-- yours Java version -->
<target>1.8</target> <!-- yours Java version -->
</configuration>
</plugin>
</plugins>
</build>
</project>
MyDBAuthenticationService.java
package org.o7planning.springmvcshoppingcart.authentication;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
import org.o7planning.springmvcshoppingcart.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import
org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import
org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
#Service
public class MyDBAuthenticationService implements UserDetailsService {
#Autowired
private AccountDAO accountDAO;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
Account account = accountDAO.findAccount(username);
System.out.println("Account= " + account);
if (account == null) {
throw new UsernameNotFoundException("User " //
+ username + " was not found in the database");
}
// EMPLOYEE,MANAGER,..
String role = account.getUserRole();
List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
// ROLE_EMPLOYEE, ROLE_MANAGER
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role);
grantList.add(authority);
boolean enabled = account.isActive();
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
UserDetails userDetails = (UserDetails) new User(account.getUserName(),
//
account.getPassword(), enabled, accountNonExpired, //
credentialsNonExpired, accountNonLocked, grantList);
return userDetails;
}
}
AplicationContextConfig.java
package org.o7planning.springmvcshoppingcart.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.o7planning.springmvcshoppingcart.dao.AccountDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.AccountDAOImpl;
import org.o7planning.springmvcshoppingcart.dao.OrderDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.OrderDAOImpl;
import org.o7planning.springmvcshoppingcart.dao.ProductDAO;
import org.o7planning.springmvcshoppingcart.dao.impl.ProductDAOImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import
org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#ComponentScan("org.o7planning.springmvcshoppingcart.*")
#EnableTransactionManagement
// Load to Environment.
#PropertySource("classpath:ds-hibernate-cfg.properties")
public class ApplicationContextConfig {
// The Environment class serves as the property holder
// and stores all the properties loaded by the #PropertySource
#Autowired
private Environment env;
#Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
// Load property in message/validator.properties
rb.setBasenames(new String[] { "messages/validator" });
return rb;
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
System.out.println("Executing intervnal view Resolver");
InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// Config for Upload.
#Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new
CommonsMultipartResolver();
// Set Max Size...
// commonsMultipartResolver.setMaxUploadSize(...);
return commonsMultipartResolver;
}
#Autowired
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// See: ds-hibernate-cfg.properties
dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
dataSource.setUrl(env.getProperty("ds.url"));
dataSource.setUsername(env.getProperty("ds.username"));
dataSource.setPassword(env.getProperty("ds.password"));
System.out.println("## getDataSource: " + dataSource);
return dataSource;
}
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) throws
Exception {
Properties properties = new Properties();
System.out.println("Datasource");
// See: ds-hibernate-cfg.properties
properties.put("hibernate.dialect",
env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql",
env.getProperty("hibernate.show_sql"));
properties.put("current_session_context_class",
env.getProperty("current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
// Package contain entity classes
factoryBean.setPackagesToScan(new String[] {
"org.o7planning.springmvcshoppingcart.entity" });
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
//
SessionFactory sf = factoryBean.getObject();
System.out.println("## getSessionFactory: " + sf);
return sf;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory
sessionFactory) {
HibernateTransactionManager transactionManager = new
HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Bean(name = "accountDAO")
public AccountDAO getApplicantDAO() {
return new AccountDAOImpl();
}
#Bean(name = "productDAO")
public ProductDAO getProductDAO() {
return new ProductDAOImpl();
}
#Bean(name = "orderDAO")
public OrderDAO getOrderDAO() {
return new OrderDAOImpl();
}
#Bean(name = "accountDAO")
public AccountDAO getAccountDAO() {
return new AccountDAOImpl();
}
}

Please using Hibernate 5 in pom.xml:
<!-- Hibernate -->
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.10.Final</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.2.10.Final</version>
</dependency>

Related

used #Transactional but still getting : Could not obtain transaction-synchronized Session for current thread

I'm having this error for days, please look into my codes:
error codes:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:136)
org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:496)
com.test.dao.DoctorDAOImpl.getDoctor(DoctorDAOImpl.java:34)
com.test.service.MainServiceImpl.getDoctor(MainServiceImpl.java:39)
com.test.controller.MainController.showMain(MainController.java:23)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:566)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:870)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
config.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.test")
#PropertySource({"classpath:persistence-mysql.properties"})
public class Config {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
System.out.println("\ntesting "+env.getProperty("jdbc.url")+"\n\n");
return viewResolver;
}
#Bean
public DataSource myDataSource() {
// create connection pool
ComboPooledDataSource myDataSource = new ComboPooledDataSource();
// set the jdbc driver
try {
myDataSource.setDriverClass("com.mysql.jdbc.Driver");
}
catch (PropertyVetoException exc) {
throw new RuntimeException(exc);
}
// for sanity's sake, let's log url and user ... just to make sure we are reading the data
logger.info("jdbc.url=" + env.getProperty("jdbc.url"));
logger.info("jdbc.user=" + env.getProperty("jdbc.user"));
// set database connection props
myDataSource.setJdbcUrl(env.getProperty("jdbc.url"));
myDataSource.setUser(env.getProperty("jdbc.user"));
myDataSource.setPassword(env.getProperty("jdbc.password"));
// set connection pool props
myDataSource.setInitialPoolSize(getIntProperty("connection.pool.initialPoolSize"));
myDataSource.setMinPoolSize(getIntProperty("connection.pool.minPoolSize"));
myDataSource.setMaxPoolSize(getIntProperty("connection.pool.maxPoolSize"));
myDataSource.setMaxIdleTime(getIntProperty("connection.pool.maxIdleTime"));
return myDataSource;
}
private Properties getHibernateProperties() {
// set hibernate properties
Properties props = new Properties();
props.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
props.setProperty("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
return props;
}
// need a helper method
// read environment property and convert to int
private int getIntProperty(String propName) {
String propVal = env.getProperty(propName);
// now convert to int
int intPropVal = Integer.parseInt(propVal);
return intPropVal;
}
#Bean
public LocalSessionFactoryBean sessionFactory(){
// create session factorys
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
// set the properties
sessionFactory.setDataSource(myDataSource());
sessionFactory.setPackagesToScan(env.getProperty("hibernate.packagesToScan"));
sessionFactory.setHibernateProperties(getHibernateProperties());
return sessionFactory;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
// setup transaction manager based on session factory
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory);
return txManager;
}
}
MainServiceImpl.java
package com.test.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.test.dao.DoctorDAO;
import com.test.dao.PatientDAO;
import com.test.entity.Doctor;
import com.test.entity.Patient;
#Service
public class MainServiceImpl implements MainService {
#Autowired
private PatientDAO patientDao;
#Autowired
private DoctorDAO doctorDao;
#Override
#Transactional
public List<Patient> getPatients() {
System.out.println("inside service: getPatients method");
return patientDao.getPatients();
}
#Override
#Transactional
public Patient getPatient(int theId) {
return patientDao.getPatient(theId);
}
#Override
#Transactional
public Doctor getDoctor(int theId) {
return doctorDao.getDoctor(theId);
}
#Override
#Transactional
public void addPatient(Patient thePatient) {
patientDao.savePatient(thePatient);
}
#Override
#Transactional
public void addDoctor(Doctor theDoctor) {
doctorDao.saveDoctor(theDoctor);
}
#Override
#Transactional
public void deletePatient(int theId) {
patientDao.deletePatient(theId);
}
}
MainController.java
package com.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.test.entity.Doctor;
import com.test.service.MainService;
#Controller
#RequestMapping("main")
public class MainController {
#Autowired
private MainService service;
#RequestMapping("/")
#Transactional
public String showMain(Model theModel) {
System.out.println("inside show Main method");
Doctor theDoctor = service.getDoctor(1);
// List<Patient> thePatients = service.getPatients();
// System.out.println(thePatients);
theModel.addAttribute("doctor", theDoctor);
return "main";
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.practice</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>test</name>
<properties>
<springframework.version>5.0.2.RELEASE</springframework.version>
<springsecurity.version>5.0.0.RELEASE</springsecurity.version>
<hibernate.version>5.4.1.Final</hibernate.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- Spring MVC support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring orm and tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<!-- Spring Security Support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Spring Security JSP tag support -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${springsecurity.version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- Add MySQL and C3P0 support -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- Servlet, JSP and JSTL support -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- to compensate for java 9+ not including jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<finalName>test</finalName>
<pluginManagement>
<plugins>
<plugin>
<!-- Add maven coordinates: maven-war-plugin -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
DoctorDAOImpl.java
package com.test.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.test.entity.Doctor;
import com.test.entity.Patient;
#Repository
public class DoctorDAOImpl implements DoctorDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Patient> getPatients(int theId) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query<Patient> theQuery = session.createQuery("from Patient p where p.doctor.id=:doctorId");
theQuery.setParameter("doctorId", theId);
List<Patient> result = theQuery.getResultList();
session.getTransaction().commit();
return result;
}
#Override
public Doctor getDoctor(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Doctor.class, theId);
}
#Override
public void saveDoctor(Doctor theDoctor) {
Session session = sessionFactory.getCurrentSession();
session.save(theDoctor);
}
}
PatientDAOImpl.java
package com.test.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.test.entity.Patient;
#Repository
public class PatientDAOImpl implements PatientDAO {
#Autowired
private SessionFactory sessionFactory;
#Override
public List<Patient> getPatients() {
System.out.println("inside repository: getPatients method");
Session session = sessionFactory.getCurrentSession();
Query<Patient> theQuery = session.createQuery("from Patient",Patient.class);
return theQuery.getResultList();
}
#Override
public void savePatient(Patient thePatient) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(thePatient);
}
#Override
public Patient getPatient(int theId) {
Session session = sessionFactory.getCurrentSession();
return session.get(Patient.class,theId);
}
#Override
public void deletePatient(int theId) {
Session session = sessionFactory.getCurrentSession();
Query theQuery = session.createQuery("delete from Patient where id=:patientId");
theQuery.setParameter("patientId", theId);
theQuery.executeUpdate();
}
}
I'm sorry that I dumped all my code here, but this is the best I could do.
Please consider using the search before posting a question, as this has been asked multiple times on Stack Overflow. Besides #m-deinum's comment (props go to him!) you would have found the answer e.g. here or here or here: Please add #EnableTransactionManagement annotation.

I'm starting to learn Java-based config. Postman don't see my query and return error 404

enter image description herei ran my program without java-based config with web.xml. when i use java-based config my postman don't see any query and return error 404.
I thought this problem is due to beans. placed everywhere anotation.
package com.lesson3.hometask.Controller;
import com.google.gson.Gson;
import com.lesson3.hometask.Model.Storage;
import com.lesson3.hometask.Service.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
#Controller
#Component
public class StorageController{
private Service service;
#Autowired
public StorageController(Service service) {
this.service = service;
}
#RequestMapping(method = RequestMethod.POST, value = "/storageSave")
public #ResponseBody
String save(HttpServletRequest req) throws IOException {
return service.save(readValuesPostman(req), Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.GET, value = "/storageFind")
public #ResponseBody
String findById(HttpServletRequest req) throws IOException {
return service.findById(Storage.class, Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.DELETE, value = "/storageDelete")
public #ResponseBody
String delete(HttpServletRequest req) throws IOException {
service.delete(Storage.class, Integer.parseInt(req.getParameter("id")));
return service.findById(Storage.class, Integer.parseInt(req.getParameter("id"))).toString();
}
#RequestMapping(method = RequestMethod.PUT, value = "/storageUpdate")
public #ResponseBody
String update(HttpServletRequest req) throws IOException {
service.update(readValuesPostman(req));
return readValuesPostman(req).toString();
}
private Storage readValuesPostman(HttpServletRequest req) throws IOException {
Storage storage;
try(BufferedReader reader = req.getReader()) {
Gson gson = new Gson();
storage = gson.fromJson(reader, Storage.class);
}
return storage;
}
}
package com.lesson3.hometask.Model;
import javax.persistence.*;
import java.util.Arrays;
#Entity
#Table(name = "STORAGE")
public class Storage {
#Id
#SequenceGenerator(name = "STORAGE_SEQ", sequenceName = "STORAGE_ID_SEQ", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STORAGE_SEQ")
#Column(name = "ID")
private int id;
#Column(name = "FORMATS_SUPPORTED")
private String formatsSupported;
#Column(name = "STORAGE_COUNTRY")
private String storageCountry;
#Column(name = "STORAGE_MAX_SIZE")
private Long storageMaxSize;
public Storage() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFormatsSupported() {
return formatsSupported;
}
public void setFormatsSupported(String formatsSupported) {
this.formatsSupported = formatsSupported;
}
public String getStorageCountry() {
return storageCountry;
}
public void setStorageCountry(String storageCountry) {
this.storageCountry = storageCountry;
}
public long getStorageMaxSize() {
return storageMaxSize;
}
public void setStorageMaxSize(Long storageMaxSize) {
this.storageMaxSize = storageMaxSize;
}
#Override
public String toString() {
return "Storage{" +
"id=" + id +
", formatsSupported='" + formatsSupported + '\'' +
", storageCountry='" + storageCountry + '\'' +
", storageMaxSize=" + storageMaxSize +
'}';
}
}
package config;
import com.lesson3.hometask.DAO.DAO;
import com.lesson3.hometask.Service.Service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
#Configuration
#ComponentScan({"com"})
#EnableWebMvc
public class AppContext implements WebMvcConfigurer {
#Bean(name = "service")
public Service service(){
return new Service();
}
#Bean(name = "DAO")
public DAO dao(){
return new DAO();
}
}
package config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class Initializer implements WebApplicationInitializer {
// Указываем имя нашему Servlet Dispatcher для мапинга
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
// Регистрируем в контексте конфигурационный класс, который мы создадим ниже
ctx.register(AppContext.class);
servletContext.addListener(new ContextLoaderListener(ctx));
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Spring1.3</groupId>
<artifactId>Spring1.3</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc8</artifactId>
<version>18.3.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugin</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
postman return error 404 = "The origin server did not find a current representation for the target resource or is not
willing to disclose that one exists".

Spring boot application not rendering index.jsp

After searching out all the possible solutions I'm posting this out.
My spring boot application was running fine few days ago. I was able to deploy it on tomcat and also export the war and deploy it on my application server. But suddenly it is showing blank page on deployment. What could be the possible reasons?
In pom.xml I've all the dependencies:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sdigital</groupId>
<artifactId>cheapTravelTicket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name></name>
<description>cheap Travel Ticket</description>
<!-- Default from spring boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Web Application -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring data jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Spring Webservices -->
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.4.01</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.w3c/dom -->
<dependency>
<groupId>org.w3c</groupId>
<artifactId>dom</artifactId>
<version>2.3.0-jaxb-1.0.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/sax/sax -->
<dependency>
<groupId>sax</groupId>
<artifactId>sax</artifactId>
<version>2.0.1</version>
</dependency>
<!-- Embedded Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Slug generator -->
<dependency>
<groupId>com.github.slugify</groupId>
<artifactId>slugify</artifactId>
<version>2.1.7</version>
</dependency>
<!-- Common String -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- JSTL for JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<!-- Need this to compile JSP -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!-- Need this to compile JSP,
tomcat-embed-jasper version is not working, no idea why -->
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency>
<!-- Optional, test for static content, bootstrap CSS-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jcabi/jcabi-xml -->
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-xml</artifactId>
<version>0.18.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring boot maven support -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application class is as follows:
package com.sdigital;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.sdigital.cache.ExpiringMap;
/**
* The Class CTTApplication.
*/
#SpringBootApplication
public class CTTApplication {
/**
* The main method.
*boots the application
*
*/
public static void main(String[] args) {
SpringApplication.run(CTTApplication.class, args);
}
#Bean
public Map<String, Object> getCache(){
Map<String, Object> map = ExpiringMap.builder()
.maxSize(200)
.expiration(12, TimeUnit.HOURS)
.build();
return map;
}
}
ServletInitializer
package com.sdigital;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
// TODO: Auto-generated Javadoc
/**
* The Class ServletInitializer.
*/
public class ServletInitializer extends SpringBootServletInitializer {
/* (non-Javadoc)
* SpringApplication Builder
*/
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CTTApplication.class);
}
}
Controller
package com.sdigital.controller;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import com.sdigital.bus.distribution.domain.ConnectionRequest;
import com.sdigital.cache.SearchCache;
import com.sdigital.domain.JourneyRequest;
import com.sdigital.domain.TimeTableRequest;
import com.sdigital.domain.XmlUrl;
import com.sdigital.domain.XmlUrlSet;
import com.sdigital.model.BusProvider;
import com.sdigital.model.City;
import com.sdigital.model.CustomForm;
import com.sdigital.model.Route;
import com.sdigital.model.SeoConfig;
import com.sdigital.model.SiteMap;
import com.sdigital.repositories.BusProviderRepository;
import com.sdigital.repositories.CityRepository;
import com.sdigital.repositories.RouteRepository;
import com.sdigital.repositories.SeoConfigRepository;
import com.sdigital.repositories.SiteMapRepository;
import com.sdigital.repositories.StationConfigRepository;
import com.sdigital.service.AppService;
import com.sdigital.utils.CTTConstant;
import com.sdigital.utils.CommonUtils;
#Controller
#SessionAttributes({"searchRequest", "searchBusRequest"})
public class AppController {
#Autowired
private AppService appServc;
#Autowired
private StationConfigRepository strepo;
#Autowired
private RouteRepository rtrepo;
#Autowired
private CityRepository ctrepo;
#Autowired
private BusProviderRepository busrepo;
#Autowired
private SeoConfigRepository repo;
#Autowired
private SearchCache searchCache;
#Autowired
private SiteMapRepository siteMap;
#RequestMapping("/")
public ModelAndView home(){
//List<Route> cttPopular = rtrepo.findOneByPopularType(CTTConstant.CTT_POPULAR_TYPE);
List<City> cttPopular = ctrepo.findAllByOrderByPriorityAsc();
List<Route> popular = rtrepo.findByPopularType(CTTConstant.POPULAR_TYPE);
ModelAndView model = new ModelAndView("index");
model.addObject("cttPopular", cttPopular);
model.addObject("popular", popular);
SeoConfig seoCon = repo.findByPageType(3);
model.addObject("title", seoCon.getPageTitle());
model.addObject("meta_title", seoCon.getMetaTitle());
model.addObject("meta_description", seoCon.getMetaDescription());
model.addObject("meta_keywords", seoCon.getMetaKeywords());
model.addObject("seo_url", seoCon.getSeoUrl());
model.addObject("description", seoCon.getDescription());
model.addObject("desc1", seoCon.getDesc1());
model.addObject("desc2", seoCon.getDesc2());
model.addObject("desc3", seoCon.getDesc3());
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
model.addObject("topCities", topCities);
model.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
model.addObject("topBusProviders", topBusProviders);
return model;
}
#RequestMapping(value = "/book")
public ModelAndView portalBook(#ModelAttribute("journeyRequest") JourneyRequest journeyRequest) throws URISyntaxException {
ModelAndView m = null;
m = appServc.getView(journeyRequest);
return m;
}
#RequestMapping(value="/search")
public ModelAndView portalSearch(#ModelAttribute("searchRequest") TimeTableRequest searchRequest,
#RequestParam(name="sort_by", required = false) String sortBy,
#RequestParam(name="s", required = false) String start,
#RequestParam(name="orig", required = false) String originuic,
#RequestParam(name="dest", required = false) String destinationuic, HttpSession session){
/*System.out.println("*** Session data ***");
Enumeration<String> e = session.getAttributeNames();
while (e.hasMoreElements()){
String s = e.nextElement();
System.out.println(s);
System.out.println("**" + session.getAttribute(s));
}*/
if(originuic!=null && destinationuic!=null){
searchRequest.setChildren(0);
searchRequest.setRailcards(null);
searchRequest.setTravelclass("standard");
searchRequest.setRetdatetime(null);
searchRequest.setAdults(1);
searchRequest.setDestinationuic(destinationuic);
searchRequest.setOriginuic(originuic);
searchRequest.setReturnjry(false);
searchRequest.setOutdatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
searchRequest.setOutsearchTime(CommonUtils.getCurrentUTCTimeSearchable(false));
}
ModelAndView m = appServc.getView(searchRequest, sortBy, start);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("currentDate", CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
return m;
}
#ModelAttribute("searchRequest")
public TimeTableRequest createFormModelAttribute(HttpSession session) {
TimeTableRequest req = (TimeTableRequest)session.getAttribute("searchRequest");
if(req!=null)
return req;
TimeTableRequest req1 = new TimeTableRequest();
req1.setAdults(1);
req1.setOutdatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
req1.setOutsearchTime(CommonUtils.getCurrentUTCTimeSearchable(false));
req1.setRetsearchTime(CommonUtils.getCurrentUTCTimeSearchable(true));
return req1;
}
#RequestMapping(value="/bus-search")
public ModelAndView portalSearch(#ModelAttribute("searchBusRequest") ConnectionRequest searchRequest,
#RequestParam(name="sort_by", required = false) String sortBy,
#RequestParam(name="s", required = false) String start,
#RequestParam(name="orig", required = false) String originuic,
#RequestParam(name="dest", required = false) String destinationuic, HttpSession session){
if(originuic!=null && destinationuic!=null){
searchRequest.setChildren1(0);
searchRequest.setRetdatetime(null);
searchRequest.setAdults1(1);
searchRequest.setDestinationuic1(destinationuic);
searchRequest.setOriginuic1(originuic);
searchRequest.setReturnjry(false);
searchRequest.setCurrency("EUR");
searchRequest.setDatetime(CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
}
ModelAndView m = appServc.getView(searchRequest, sortBy, start);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("currentDate", CommonUtils.getFormatedDate(CTTConstant.DEFAULT_SEARCH_FORMAT, new Date()));
return m;
}
#ModelAttribute("searchBusRequest")
public ConnectionRequest createFormModelAttribute() {
return new ConnectionRequest();
}
#ModelAttribute("journeyRequest")
public JourneyRequest createFormModelAttribute1() {
return new JourneyRequest();
}
#RequestMapping(value="/{seo:.+}")
public ModelAndView portalLocation(#PathVariable("seo") String seo, HttpServletResponse response, #RequestParam(name="status", required = false) String status){
ModelAndView m = appServc.getView(seo, response, status);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
return m;
}
#RequestMapping(value="/{seo1}/{seo2:.+}")
public ModelAndView portalChildLocation(#PathVariable("seo1") String seo1, #PathVariable("seo2") String seo2, HttpServletResponse response, #RequestParam(name="status", required = false) String status){
ModelAndView m = appServc.getView(seo1+"/"+seo2, response, status);
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
return m;
}
#ResponseBody
#RequestMapping(value="/schedular/trains")
public boolean portalSchedularToUpdateTrains(){
appServc.updateTrainsForCityToCity();
return true;
}
#RequestMapping(value = "/robots.txt")
#ResponseBody
public String getRobots(HttpServletRequest request) {
return "User-agent: * \n Disallow: /";
}
#RequestMapping(value = "/sitemap.xml", method = RequestMethod.GET)
#ResponseBody
public XmlUrlSet getSiteMap(HttpServletRequest request) {
XmlUrlSet xmlUrlSet = new XmlUrlSet();
create(xmlUrlSet, "", "1.0", request);
List<SiteMap> seoUrls = siteMap.findByPublish(1);
for(SiteMap sUrl : seoUrls){
create(xmlUrlSet, "/"+sUrl.getSeoUrl(), null, request);
}
return xmlUrlSet;
}
private void create(XmlUrlSet xmlUrlSet, String link, String priority, HttpServletRequest request) {
String rootUrl = request.getScheme() + "://" + request.getServerName() + request.getContextPath();
xmlUrlSet.addUrl(new XmlUrl(rootUrl + link, priority));
}
#RequestMapping(value="/information/rail-cards")
public ModelAndView railCardInfo(){
ModelAndView model = new ModelAndView("railinfo");
return model;
}
#RequestMapping(value="/form/post")
public String formPost(#ModelAttribute("addRequest") CustomForm addRequest){
String r = appServc.addData(addRequest);
return r;
}
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
ModelAndView m = new ModelAndView("exception");
List<City> topCities = ctrepo.findTop10ByOrderByPriorityAsc();
List<Route> topRoutes = rtrepo.findTop10ByOrderByPriorityAsc();
m.addObject("topCities", topCities);
m.addObject("topRoutes", topRoutes);
List<BusProvider> topBusProviders = busrepo.findTop10ByPublishOrderByPriorityAsc(true);
m.addObject("topBusProviders", topBusProviders);
m.addObject("searchRequest", new TimeTableRequest());
return m;
}
}
Adding my answer in case anyone else faces same issue.
Problem was with the context path. Updated the context path in project properties in eclipse. then ran clean and build. Most important part was to remove the server configuration and again ran it on tomcat, it worked.
Since I was not clearing the server configurations from eclipse updated context path was not picking up.

Error Creating Bean - Autowiring of dependencies failed

I am getting this error when I run my spring-mvc application :
Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
Error creating bean with name 'personDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.PersonDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.config.SpringConfig: Invocation of init method failed; nested exception is java.lang.AbstractMethodError
I have also checked the dependencies in my pom.xml
<!-- Spring -->
<spring-framework.version>4.2.4.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.2.1.Final</hibernate.version>
Apart from this, I have specified ${spring-framework.version} and ${hibernate.version} in the version of all the dependencies
//////////////////////////////Spring Configuration//////////////
package com.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import com.model.Person;
import com.service.PersonService;
#Configuration
#EnableWebMvc
#ComponentScan({ "com.*" })
#EnableTransactionManagement
public class SpringConfig extends WebMvcConfigurerAdapter {
#Autowired
private Environment environment;
#Autowired
private PersonService ps;
#Bean #Autowired
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setAnnotatedClasses(Person.class);
sessionFactory.setPackagesToScan(new String[] { "com.model" });
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean #Autowired
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/myschema");
dataSource.setUsername("root");
dataSource.setPassword("admin123");
return dataSource;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
registry.addResourceHandler("/resources/**").addResourceLocations(
"/resources/*");
}
#Bean #Autowired
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver res = new InternalResourceViewResolver();
res.setPrefix("/WEB-INF/view/");
res.setSuffix(".jsp");
return res;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.search.default.directory_provider", "org.hibernate.search.store.impl.FSDirectoryProvider");
properties.put("hibernate.search.default.indexBase", "H:/MyWorkspace/MainAssignment3/indexes");
return properties;
}
#Bean #Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
}
///////////////////////////////////POM////////////////////////////////
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.samples.service.service</groupId>
<artifactId>MainAssignment3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Web -->
<jsp.version>2.2</jsp.version>
<jstl.version>1.2</jstl.version>
<servlet.version>2.5</servlet.version>
<!-- Spring -->
<spring-framework.version>4.2.1.RELEASE</spring-framework.version>
<!-- Hibernate / JPA -->
<hibernate.version>5.1.1.Final</hibernate.version>
<!-- Logging -->
<logback.version>1.0.13</logback.version>
<slf4j.version>1.7.5</slf4j.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId>
<version>1.1</version> </dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!-- Other Web dependencies -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring and Transactions -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Logging with SLF4J & LogBack -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>
<!-- Test Artifacts -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
</project>
///////////////////////////////DAO File//////////////////////////////
package com.dao;
import java.util.List;
import com.model.Person;
public interface PersonDAO {
public void save(Person p);
public List<Person> list();
public void updatePerson(Integer id);
public Person getPersonById(int id);
public void removePerson(Integer id);
public void indexPersons() throws Exception;
public List<Person> searchForPerson(String searchText) throws Exception;
}
//////////////////////////DAO Impl///////////////////////////
package com.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.model.Person;
#Transactional
#Repository
public class PersonDAOImpl implements PersonDAO, java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = (Logger) LoggerFactory
.getLogger(PersonDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
public void save(Person p) {
// TODO Auto-generated method stub
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(p);
tx.commit();
s.close();
System.out.println("Record successfully inserted");
}
#SuppressWarnings("deprecation")
public List<Person> list() {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
#SuppressWarnings("unchecked")
List<Person> personsList = session.createQuery("from Person").list();
for (Person p : personsList) {
logger.info("Person List::" + p);
}
return personsList;
}
public void updatePerson(Integer id) {
Session session = new Configuration().configure().buildSessionFactory()
.openSession();
Person p = new Person();
Person person = session.get(Person.class, p.getId());
//Transaction t = session.beginTransaction();
Query query = session.createQuery("from Person");
person.setName(p.getName()); // modify the loaded object somehow
session.update(person);
//t.commit();
session.close();
}
public Person getPersonById(int id) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
Person p = (Person) session.load(Person.class, new Integer(id));
logger.info("Person loaded successfully, Person details=" + p);
return p;
}
public void removePerson(Integer id) {
Session session = sessionFactory.getCurrentSession();
// Transaction t = session.beginTransaction();
Person p = (Person) session.load(Person.class, new Integer(id));
session.delete(p);
// t.commit();
logger.info("Person deleted successfully, person details=");
}
#Transactional
public void indexPersons() throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
}
catch(Exception e)
{
throw e;
}
}
public List<Person> searchForPerson(String searchText) throws Exception{
// TODO Auto-generated method stub
try
{
Session session = sessionFactory.getCurrentSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
QueryBuilder qb = fullTextSession.getSearchFactory()
.buildQueryBuilder().forEntity(Person.class).get();
org.apache.lucene.search.Query query = qb
.keyword().onFields("name", "address", "salary","gender")
.matching(searchText)
.createQuery();
org.hibernate.Query hibQuery =
fullTextSession.createFullTextQuery(query, Person.class);
List<Person> results = hibQuery.list();
return results;
}
catch(Exception e)
{
throw e;
}
}
}
According to docs you should update your Spring dependency to 4.3 if you want to use Hibernate 5.2.
Also you have to correct dependencies for Hibernate search (it's releases are different then Hibernate's core).
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-orm</artifactId>
<version>5.5.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search-engine</artifactId>
<version>5.5.4.Final</version>
</dependency>

No mapping found for HTTP request with URI… in DispatcherServlet with name

When performing a request to http://localhost:8080/SquirrelAuth/api/groups/.json I get this error:
Mar 24, 2015 5:55:52 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SquirrelAuth/api/groups/.json] in DispatcherServlet with name 'dispatcher'
I've been spinning on this one forever and can't seem to find any answers out there that work for me. Can anyone help me through this?
Pom Dependencies/Properties
<properties>
<spring.version>4.1.5.RELEASE</spring.version>
<oauth.version>2.0.7.RELEASE</oauth.version>
<taglibs.version>3.2.6.RELEASE</taglibs.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<log4j.version>2.2</log4j.version>
<jdk.version>1.7</jdk.version>
<jackson.version>2.5.1</jackson.version>
<jstl.version>1.2</jstl.version>
<mysql.version>5.1.6</mysql.version>
<liquibase.version>3.3.2</liquibase.version>
<javax.version>3.1.0</javax.version>
<mavenWar.version>2.6</mavenWar.version>
<mavenCompiler.version>3.2</mavenCompiler.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${oauth.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${taglibs.version}</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.version}</version>
</dependency>
</dependencies>
Web Application Intializer
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.squirrels.config");
return context;
}
}
PersistenceJPAConfig
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.squirrels.controller", "com.squirrels.services", "com.squirrels.persistence.dao" })
#PropertySource(value = { "classpath:squirrel.properties" })
public class PersistenceJPAConfig {
#Autowired
private Environment environment;
#Bean
public SpringLiquibase liquibase() {
SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setDataSource(dataSource());
liquibase.setDefaultSchema(environment.getRequiredProperty("db_schema"));
liquibase.setChangeLog("classpath:/db/changelog/db.changelog-master.xml");
return liquibase;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "com.squirrels.persistence.model" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("db_driverClass"));
dataSource.setUrl(environment.getRequiredProperty("db_jdbcUrl"));
dataSource.setUsername(environment.getRequiredProperty("db_user"));
dataSource.setPassword(environment.getRequiredProperty("db_password"));
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", environment.getRequiredProperty("db_hibernateDialect"));
return properties;
}
}
Groups Controller
package com.squirrels.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import com.squirrels.dto.GroupDTO;
import com.squirrels.services.GroupUtil;
#Controller
public class GroupsController {
#Autowired
GroupUtil groupUtil;
static final Logger logger = LogManager.getLogger(GroupsController.class);
#RequestMapping(value = "/api/groups/", method = RequestMethod.GET)
public #ResponseBody List<GroupDTO> getGroups() {
List<GroupDTO> groupList = null;
try {
groupList = groupUtil.getAll();
} catch (Exception e) {
e.printStackTrace();
}
return groupList;
}
}
WebMvcConfig
package com.squirrels.config;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
/*
* Configure ContentNegotiationManager
*/
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).defaultContentType(MediaType.TEXT_HTML);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
resolvers.add(jsonViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide JSON output using JACKSON library to
* convert object in JSON format.
*/
#Bean
public ViewResolver jsonViewResolver() {
return new JsonViewResolver();
}
}
The RequestMappingHandlerMapping that spring uses to resolve #RequestMapping annotations has a property alwaysUseFullPath which defaults to false. This means that the mappings you set on handlers (i.e. your #RequestMapping annotations) are resolved relative to the dispatcher servlet mapping which in your case is /api .
Seems that you have not overriden it so make the base mapping path of the controller /groups instead of /api/groups
see reference for details
I ended up solving it finally last night.
I added this to the WebMvcConfig class and all is well.
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
};

Categories

Resources