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

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

Not using Spring but I would think you need a welcome-file in web.xml like
<welcome-file-list>
<welcome-file>input.xhtml</welcome-file>
</welcome-file-list>

Related

Tomcat war deployment gives 404 when using annotations instead of web.xml

I am trying to learn Spring framework. When I use Spring annotation for configuration instead of web.xml and deploy war file on Tomcat in Docker container, it gives 404 error. After switching to web.xml and servlet.xml configuration, it gives no error.
My config file:
package com.janfranco.mvctutorial.config;
...
#Configuration
#EnableWebMvc
#ComponentScan
public class AppConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
My servlet file:
package com.janfranco.mvctutorial.config;
...
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I use Maven for management. Here is my Dockerfile:
FROM tomcat:8.0.20-jre8
COPY target/mvctutorial.war /usr/local/tomcat/webapps/
How can I use annotations and get rid of xml configs?
Edit:
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>mvctutorial</display-name>
<absolute-ordering />
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

problem in dispatching to j_spring_security_check from managed bean in spring security?

I want to configure JSF (primefaces) with spring but i have a problem in using spring security.
for some reason (checking captcha later) i dispatch to "j_spring_security_check" from managedbean, after inserting the username and password and so on and submitting the request the method of the managedbean is called and then blow error message is appread in console and so authentication is failed:
Feb 01, 2020 5:29:06 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping for POST /common/form/j_spring_security_check
Feb 1, 2020 5:29:06,156 PM IRST Warning org.springframework.web.servlet.PageNotFound BEA-000000 No mapping for POST /common/form/j_spring_security_check
anyone can help what should i do to solve this problem (preferred java config)? thank you.
login.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Login</title>
</h:head>
<h:body>
<h:form id="loginFormId" prependId="false">
<p:panelGrid columns="1" styleClass="ui-fluid center ui-noborder">
<h2>Please login</h2>
<p:outputLabel value="Login failed!" styleClass="red"
rendered="${!empty param['error']}" />
<p:inputText id="username" placeholder="User name" />
<p:password id="password" placeholder="Password" />
<p:commandButton value="Login" ajax="false" action="#{loginCtrl.login}"/>
</p:panelGrid>
</h:form>
</h:body>
</html>
WebInitializer.java
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{WebConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebConfig.java
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages = "mcom")
#ComponentScan(basePackages = {"mcom.*"})
#Import(SecurityConfig.class)
#PropertySource("classpath:mcom/m2/common/config/Application.properties")
public class WebConfig {
#Autowired
private Environment environment;
#Bean
DataSource dataSource(){
System.out.println("WebConfig.dataSource");
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("db.driver"));
dataSource.setUrl(environment.getRequiredProperty("db.url"));
dataSource.setUsername(environment.getRequiredProperty("db.username"));
dataSource.setPassword(environment.getRequiredProperty("db.password"));
return dataSource;
}
#Bean
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource){
System.out.println("WebConfig.entityManagerFactoryBean");
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource);
entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
entityManagerFactoryBean.setPackagesToScan("mcom");
Properties properties = new Properties();
properties.setProperty("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.setProperty("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.setProperty("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
entityManagerFactoryBean.setJpaProperties(properties);
return entityManagerFactoryBean;
}
#Bean
JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
System.out.println("WebConfig.transactionManager");
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
SecurityInitializer.java
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
SecurityConfig.java
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
System.out.println("SecurityConfig.configureGlobal");
try {
builder.inMemoryAuthentication().withUser("kobe")
.password("{noop}1234").roles("USER").and()
.withUser("james").password("{noop}1414").roles("ADMIN", "USER");
}catch (Exception e){
e.printStackTrace();
throw e;
}
}
#Override
public void configure(HttpSecurity http) throws Exception{
System.out.println("SecurityConfig.configure");
try {
http.addFilterBefore(new customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.authorizeRequests().antMatchers("/javax.faces.resource/**","/form/login.xhtml").permitAll().anyRequest().authenticated();
http.formLogin().loginPage("/form/login.xhtml").loginProcessingUrl("/j_spring_security_check").permitAll().defaultSuccessUrl("/form/home.xhtml").failureUrl("/form/login.xhtml?error=true");
http.csrf().disable();
}catch (Exception e){
e.printStackTrace();
throw e;
}
}
}
LoginCtrl.java
try {
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
RequestDispatcher dispatcher = ((ServletRequest)context.getRequest()).getRequestDispatcher("j_spring_security_check");
dispatcher.forward((ServletRequest)context.getRequest(), (ServletResponse)context.getResponse());
FacesContext.getCurrentInstance().responseComplete();
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.FACELETS_LIBRARIES</param-name>
<param-value>/WEB-INF/springsecurity.taglib.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
</web-app>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>

NoSuchBeanDefinitionException: No qualifying bean of type found for dependency using annotaition

I have such project structure:
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/PostgreSQLDS</jta-data-source>
<class>server.entity.Holiday</class>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
</persistence>
Web.xml (As you can see, I'm using context Class where I will use JSON):
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="false">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</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>server.config</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WebAppConfig.class:
#Configuration
#EnableWebMvc
#ComponentScan("server")
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(new ObjectMapper());
converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
converters.add(converter);
}
#Bean
public InternalResourceViewResolver setupViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
HolidayController.class
#RestController
#RequestMapping("/holidays")
public class HolidayController {
#Autowired
private HolidayRepository holidayRepository;
#RequestMapping(value = "", method = RequestMethod.GET)
#ResponseBody
public List<Holiday> getAllHolidays() {
// List<User> list = userRepository.findAll();
return holidayRepository.findAll();
}
HolidayRepository.class:
#Repository
public interface HolidayRepository extends JpaRepository<Holiday, Long> {
}
I've got this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [server.repository.HolidayRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Help me, please.
I seems you need #EnableJpaRepositories in your JavaConfig
See secton 3.2 -> http://docs.spring.io/spring-data/jpa/docs/1.9.4.RELEASE/reference/html/#repositories.definition
Create a new JavaConfig class:
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#EnableJpaRepositories
class JpaSpringDataConfig {}
Or add this to your XML config:
<jpa:repositories base-package="server.repository"/>
Since your log says it expects a WebApplicationInitializer, remove your web.xml and include a class like:
public class RestWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { JpaSpringDataConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Add the annotation #Repository to the implementation of HolidayRepository interface.

Trouble spring injection in JSF2 Bean with annotation

I have a trouble with Spring Injection in my web project. I must use in a JSF2 bean.
Show my work :
SgbdServiceImpl.java (shorted)
#Service
public class SgbdServiceImpl implements SgbdService {
#Override
public List<Sgbd> findAll() {
return null;
}
#Override
public Sgbd findOneByName(String nom) {
return null;
}
}
SgbdBean
#Component
#SessionScoped
#ManagedBean(name="sgbd")
public class SgbdBean {
#Autowired
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
I put this configuration in the file : web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
This Spring configuration in applicationContext.xml :
<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">
<context:annotation-config />
<context:component-scan base-package="main.java.com.erdf.agir.services" />
</beans>
And, in faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd"
version="2.1">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
I would like call findAll() from service but i obtain all time nullPointerException from sgbdService attribut (Autowired failled ?)
I follow this example : http://rsuna.blogspot.fr/2013/05/how-to-integrate-jsf-20-with-spring-3.html
Did I miss anything ?
You have a context clash; using both #Component and #ManagedBean on the same class definition put your bean in two contexts: JSF and Spring's. Let's now establish that #Autowired will not work in the JSF context.
You could get rid of the spring-based annotations and go with a JSF-centric setup. What this will leave with you with
#SessionScoped
#ManagedBean(name="sgbd")
public class SgbdBean {
#ManagedProperty(value="#{sgbdServiceImpl}")
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
You could stick with a strictly spring-centric approach with
#Component
public class SgbdBean {
#Autowired
SgbdService sgbdService;
public List<Sgbd> findAll(){
return sgbdService.findAll();
}
}
Things I have encountered
1) Better to mention service name with annotation - #Service("sgbdService")
2) Rather than #ManagedBean it is better to use #Qualifier annotation -
#Qualifier("sgbdBean")
3) Add <context:sping-configured/> entry to applicationContext.xml file
4) Try with top level component scan entry as
<context:component-scan base-package="main.java.com.erdf" />

Spring RESTful and Hibernate

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

Resources