Spring Exception Handling : org.springframework.beans.factory.CannotLoadBeanClassException - java

I am getting error :
java.lang.ClassNotFoundException:
org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
I am hitting URL : http://localhost:8080/SpringMvcExceptionHandling/student on my local machine
Full Strack Trace is :
I have already checked most of the question/answer but not getting any help to resolve my issue,Please help.
Here is what I have done :
I am working on Spring Exception Handling with Jars(Spring-3.1.2). I am not using maven.
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMvcExceptionHandling-servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.exceptionhandling.mvc.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.
SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.exceptionhandling.mvc.controller.SpringException">
ExceptionPage
</prop>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
<property name="defaultErrorView" value="/error" />
</bean>
</beans>
StudentController.java
package com.exceptionhandling.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.servlet.ModelAndView;
import com.exceptionhandling.mvc.model.Student;
#Controller
public class StudentController {
#RequestMapping(value = "/student")
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
#ExceptionHandler({SpringException.class})
public String addStudent(#ModelAttribute("SpringMvcExceptionHandling") Student student,
ModelMap model) {
if (student.getName().length() < 5) {
throw new SpringException("Given name is too short");
} else {
model.addAttribute("name", student.getName());
}
if (student.getAge() < 10) {
throw new SpringException("Given age is too low");
} else {
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
SpringException.java
package com.exceptionhandling.mvc.controller;
public class SpringException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String exceptionMsg;
public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
My Project Structure Looks Like
Jars
Added Two External Jars :

In your SpringMvcExceptionHandling-servlet.xml file, your bean class name must be fully qualified (with no spaces in between).
So your solution must be:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

Related

HTTP Status 500 - Servlet.init() for servlet spring threw exception here is my code

controller,service and dao are in different package UserSer interface and UserService class is on package com.service UserDa interface and UserDao class is on package com.dao and Controller is on Package com.controller please help me with this , if i am doing this all on the same package its working but for different package its not working
thankyou
#Controller
public class UserController {
#Autowired
public UserSer userSer;
#RequestMapping(value="/get")
public void dummytest()
{
System.out.println(userSer.SayHii());
}
}
#Service("UserSer")
public class UserService implements UserSer{
#Autowired
public UserDa userDa;
public String SayHii() {
return userDa.Say();
}
}
#Repository("UserDa")
public class UserDao implements UserDa {
public String Say()
{
return "hiiiiiiiiiiiii";
}
}
web.xml
* <servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>*
spring-servlet.xml
*<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:ctx="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
">
<ctx:annotation-config></ctx:annotation-config>
<mvc:annotation-driven/>
<ctx:component-scan base-package="com.controller"></ctx:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</bean>*

Cannot access to resources when I add method = RequestMethod.POST

I have a problem with get access to resources folder with css and js and more in my project.
When I add #RequestMapping with a method = RequestMethod.POST I lose access to resource. Before everything is ok.
My Structure:
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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>medicine</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<context:component-scan base-package="pl.tomo" />
<jpa:repositories base-package="pl.tomo.repository"/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
<mvc:annotation-driven />
<tx:annotation-driven/>
</beans>
My controller
package pl.tomo.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.tomo.entity.Lek;
import pl.tomo.entity.Medicament;
import pl.tomo.service.LekService;
import pl.tomo.service.MedicamentService;
#Controller
public class IndexController {
#Autowired
private MedicamentService medicamentService;
#Autowired
private LekService lekService;
private List<Lek> listLek = new ArrayList<Lek>();
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index(Model model)
{
listLek = lekService.findAll();
model.addAttribute("listLek", listLek);
model.addAttribute("lek", new Lek());
return "index";
}
#RequestMapping(name = "/index", method = RequestMethod.POST)
public String add(#ModelAttribute("lek") Lek lek)
{
try {
lek.setDateOpen(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringOpen()));
lek.setDateExpiration(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringExpiration()));
lek.setDateEnd(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringEnd()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Medicament medicament = medicamentService.findOne(lek.getLiczba());
lek.setMedicament(medicament);
lekService.save(lek);
return "redirect:/index";
}
}
and form from index.jsp
<form:form method="POST" commandName="lek" class="form-inline">
<form:input path="dateStringOpen" cssClass="form-control" />
<form:input path="dateStringExpiration" cssClass="form-control" />
<form:input path="dateStringEnd" cssClass="form-control" />
<input type="submit" value="Dodaj lek" Class="btn btn-default" />
</form:form>
And i want to get to localhost:8080/resources/core/css/bootstrap.min.css and i have
HTTP ERROR 405
Problem accessing /resources/core/css/bootstrap.min.css. Reason:
Request method 'GET' not supported
When I remove
#RequestMapping(name = "/index", method = RequestMethod.POST)
public String add(#ModelAttribute("lek") Lek lek)
{
try {
lek.setDateOpen(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringOpen()));
lek.setDateExpiration(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringExpiration()));
lek.setDateEnd(new SimpleDateFormat("yyyy-MM-dd").parse(lek.getDateStringEnd()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Medicament medicament = medicamentService.findOne(lek.getLiczba());
lek.setMedicament(medicament);
lekService.save(lek);
return "redirect:/index";
}
I have access to file localhost:8080/resources/core/css/bootstrap.min.css
Can you help me?
I've configured access to my resources differently. For starters, I use annotations only. From there, I added a resource handler:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
I have changed servlet mapping from
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
to
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.json</url-pattern>
<url-pattern>*.xml</url-pattern>
</servlet-mapping>
and it works

Unable to apply aspect in spring MVC

In my project i want to apply AOP in Spring MVC . and show the output in webpage .but unable to show and unable apply advice in the controller class.
Logging.java:-
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.springframework.stereotype.Component;
#Aspect
public class Logging {
/** Following is the definition for a pointcut to select
* all the methods available. So advice will be called
* for all the methods.
*/
#Pointcut("execution(* com.*.*(..))")
private void selectAll(){}
/**
* This is the method which I would like to execute
* before a selected method execution.
*/
#Before("selectAll()")
public void beforeAdvice(){
System.out.println("Going to setup student profile.");
}
/**
* This is the method which I would like to execute
* after a selected method execution.
*/
#After("selectAll()")
public void afterAdvice(){
System.out.println("Student profile has been setup.");
}
/**
* This is the method which I would like to execute
* when any method returns.
*/
#AfterReturning(pointcut = "selectAll()", returning="retVal")
public void afterReturningAdvice(Object retVal){
System.out.println("Returning:" + retVal.toString() );
}
/**
* This is the method which I would like to execute
* if there is an exception raised by any method.
*/
#AfterThrowing(pointcut = "selectAll()", throwing = "ex")
public void AfterThrowingAdvice(IllegalArgumentException ex){
System.out.println("There has been an exception: " + ex.toString());
}
#Around("selectAll()")
public Object aroundAdvice(ProceedingJoinPoint p) throws Throwable{
System.out.println("Before around");
Object o=p.proceed();
System.out.println("After around");
return o;
}
}
pojo class
Student.java:-
public class Student {
private Integer age;
private String name;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
System.out.println("Age : " + age );
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
System.out.println("Name : " + name );
return name;
}
}
UserController.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class UserController implements Controller {
public ModelAndView handleRequest(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception
{
ApplicationContext context =
new FileSystemXmlApplicationContext("C:/Users/pcuser/Desktop/zspringmvcannotation/WebContent/WEB-INF/applicationContext.xml");
Student student = (Student) context.getBean("student");
student.getName();
student.getAge();
return new ModelAndView("success","student",student);
// return new ModelAndView("/WEB-INF/jsp/success.jsp");
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean p:suffix=".jsp" p:prefix="/WEB-INF/jsp/"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="viewResolver" />
<!-- AOP support -->
<bean id="logging" class="Logging" />
<aop:aspectj-autoproxy>
<aop:include name='logging' />
</aop:aspectj-autoproxy>
<!-- Definition for student bean -->
<bean id="student" class="Student">
<property name="name" value="Tapajyoti" />
<property name="age" value="22" />
</bean>
<bean id="userController" class="UserController" />
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/hello.htm">userController</prop>
</props>
</property>
</bean>
</beans>
Dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<import resource="applicationContext.xml"></import>
</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
SpringMVC</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
I agree with M.Deinum, please correct these notes first of all. Further you should delete your Dispatcher-servlet.xml because you have a FileSystemXmlApplicationContext and have defined all of your beans in xml loaded there. Then please delete <listener> and <context-param> elements in web.xml and configure your aspect like this:
<aop:aspectj-autoproxy />
<!-- Aspect -->
<bean id="loggingAspect" class="Logging" />

Returning object with EJB 3

I'm trying to work with the EJB 3, but I'm missing something.
Initially I created a stateless bean that I called through the controller of the mvc.
The bean contained a method that returned a String.
Now, I'm wiling to go to the next level, namely I'm trying to create a bean that returns an object instead of a string.
Persona.java
package com.pojo;
import java.io.Serializable;
public class Persona implements Serializable {
private static final long serialVersionUID = 1L;
String nome;
int eta;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getEta() {
return eta;
}
public void setEta(int eta) {
this.eta = eta;
}
}
RitornaPersonaRemote.java
package com.demo.view;
import com.pojo.Persona;
public interface RitornaPersonaRemote {
public Persona getPersona();
}
RitornaPersona.java
package com.demo;
import com.demo.view.RitornaPersonaRemote;
#Stateless
#Remote(RitornaPersonaRemote.class)
public class RitornaPersona implements RitornaPersonaRemote {
public Persona getPersona(){
Persona p = new Persona();
p.setEta(18);
p.setNome("tizio");
return p;
}
}
Client side
My_controller.java
package controller;
import javax.ejb.EJB;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.demo.view.RitornaPersonaRemote;
#Controller
public class My_Controller {
#EJB
private RitornaPersonaRemote rp;
#RequestMapping("testpage")
public ModelAndView mostraPagina(){
ModelAndView model = new ModelAndView();
model.setViewName("testpage");
model.addObject("hello", "nome --> " + persona.getPersona().getNome());
return model;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<!-- enable autowire -->
<context:annotation-config/>
<context:spring-configured/>
<jee:local-slsb id="RitornaPersona"
jndi-name="java:app/RitornaPersonaSenzaClient/RitornaPersona!com.demo.view.RitornaPersonaRemote"
business-interface="com.demo.view.RitornaPersonaRemote" />
</beans>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
<context:component-scan base-package="controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<jee:jndi-lookup id="RitornaPersonaSenzaClient" jndi-name="com.demo.view.RitornaPersonaRemote"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor">
<property name="alwaysUseJndiLookup" value="true" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 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_2_5.xsd">
<display-name>RitornaPersonaWeb</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>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<display-name>spring</display-name>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<ejb-ref>
<description>
</description>
<ejb-ref-name>RitornaPersonaSenzaClient</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<home></home>
<remote>com.demo.view.RitornaPersonaRemote</remote>
<ejb-link>RitornaPersona</ejb-link>
</ejb-ref>
</web-app>
The errors that I'm getting are pasted here:
http://justpaste.it/gfs3
Please, can someone tell me were are my mistakes?
I looked on lots of guide, but I lost the path.

Transactionrequiredexception, no transaction in progress

I've been currently working on a Maven + Spring + Hibernate project. Actually, this is just a test project just to get familiar on how Spring works with Hibernate (+Maven). I've already setup and prepare the necessary dependencies. i.e. the appcontext.xml for Spring, the persistence.xml for Hibernate, the entity and DAO objects for JPA/Persistence/Hibernate.
During debug, persist method throws Transactionrequiredexception, no transaction in progress. I don't know what's causing this
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" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-datasource.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
application-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="com.names.home" />
<!-- Default locale set -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<!-- Tell Spring to not try to map things in these directories to controllers -->
<!-- Order must be set to supercede the handler configured by the mvc:annotation-driven annotation -->
<mvc:resources order="-10" location="/img/" mapping="/img/**" />
<mvc:resources order="-10" location="/css/" mapping="/css/**" />
<mvc:resources order="-10" location="/js/" mapping="/js/**" />
<mvc:resources order="-10" location="/fonts/" mapping="/fonts/**" />
<mvc:resources order="-10" location="favicon.ico" mapping="favicon.ico" />
<mvc:resources order="-10" location="robots.txt" mapping="robots.txt" />
</beans>
applicationContext-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The "webDS" data source is the main data source for names. It is referenced and
should be configured via JNDI in your particular environment. -->
<jee:jndi-lookup id="datasource" jndi-name="jdbc/web"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
<property name="persistenceUnitName" value="wzpu"/>
<property name="dataSource" ref="datasource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
admincontroller.java
package com.names.home;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AdminController {
#Resource(name="profiledao")
protected ProfileDao profiledao;
#RequestMapping(value="/admin/insert")
#Transactional
public String insert(){
Profile pr = new Profile();
pr.setId(1);
profiledao.save(pr);
return "home";
}
}
ProfileDao.java
package com.names.home;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
#Repository
public class ProfileDao {
#PersistenceContext(unitName = "wzpu")
protected EntityManager em;
public Profile find(){
return this.em.find(Profile.class, 2);
}
public void save(Profile profile){
this.em.persist(profile);
em.flush();
}
}
Profile.java
package com.names.home;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "profile")
public class Profile implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "PROFILE_ID",nullable=false,unique=true)
protected int id;
public Profile() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Profile other = (Profile) obj;
if (id != other.id)
return false;
return true;
}
}
Please help me resolving this
The root of your issue is that the bean you've annotated with the #Transactional annotation is not being picked up by the context that contains the tx:annotation-driven post processor. You have a couple options. Move the #Transactional to a bean that is loaded by the context that contains the tx:annotation-driven post processor or move the tx:annotation-driven post processor into the same context that the #Transactional bean is being loaded.
The answer here is a similar situation.

Categories