Transactionrequiredexception, no transaction in progress - java

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.

Related

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'servicePersonalUrgenciasImplementacion'

So, I am pretty new to Spring MVC, and I think I'm having problems with configuration and I'm going crazy.
I've tried the solution here but either I'm unable to make it work or my mistake is something different
The error I'm getting is:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'servicioPersonalUrgenciasImplementacion': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.modelo.dao.PersonalUrgenciasDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
My components are:
Controller. in com.controladores package
#Controller
public class LoginController {
private ServicioPersonalUrgenciasLogin service;
#Autowired
public void setServicioPersonalUrgenciasLogin( ServicioPersonalUrgenciasLogin service) {
this.service = service;
}
#GetMapping("login")
public String login(Model model) {
PersonalUrgenciasLogin login = new PersonalUrgenciasLogin();
//Add customers to the model
model.addAttribute("login", login);
return "login";
}
...
}
Service interface and Service implementation, both in com.modelo.servicios
#Service
public interface ServicioPersonalUrgenciasLogin {
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
public void cambiarContrasenia(String username, String newpwd);
}
#Service
public class ServicioPersonalUrgenciasLoginImplementacion implements ServicioPersonalUrgenciasLogin {
#Autowired
private PersonalUrgenciasLoginDAO dao;
#Override
#Transactional
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
return dao.login(username, pwd);
}
#Override
#Transactional
public void cambiarContrasenia(String username, String newpwd) {
// I have to implement this,
}
}
DAO Interface and Implementation, both in com.modelo.dao package
I know this is not the way to implement a login, but I wanted something fast
public interface PersonalUrgenciasLoginDAO {
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
public void cambiarContrasenia(String username, String newpwd);
}
#Repository
public class PersonalUrgenciasLoginDAOImplementacion implements PersonalUrgenciasLoginDAO{
#Autowired
private SessionFactory factoria;
#Override
public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Session sesion = factoria.getCurrentSession();
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] hashInOne = md5.digest(pwd.getBytes("UTF-8"));
String hashMD5String = getString(hashInOne);
Query<String> query2 = sesion.createQuery(
"SELECT usuario FROM PersonalUrgencias WHERE contrasenia=: pwd AND usuario =:user", String.class);
query2.setParameter("user", username);
query2.setParameter("pwd", hashMD5String);
List<String> haLogueado = query2.getResultList();
return !haLogueado.isEmpty();
}
#Override
public void cambiarContrasenia(String username, String newpwd) {
// TODO Auto-generated method stub
}
private static String getString( byte[] bytes )
{
StringBuffer sb = new StringBuffer();
for( int i=0; i<bytes.length; i++ )
{
byte b = bytes[ i ];
String hex = Integer.toHexString((int) 0x00FF & b);
if (hex.length() == 1)
{
sb.append("0");
}
sb.append( hex );
}
return sb.toString();
}
My Entity. I know it is not wired, but I don't want it to be
And then, my 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>triaje</display-name>
<absolute-ordering />
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
And this is my applicationContext.xml
I've tried just writting com in <context:component-scan...> too
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Add support for component scanning -->
<context:component-scan base-package="com, com.controladores, com.modelo.dao, com.modelo.entidades, com.modelo.servicios" />
<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3316/trj?useSSL=false&serverTimezone=UTC" />
<property name="user" value="root" />
<property name="password" value="root" />
<!-- these are connection pool properties for C3P0 -->
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="30000" />
</bean>
<!-- Step 2: Setup Hibernate session factory -->
<bean id="factoria"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.modelo.entidades" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="factoria"/>
</bean>
<!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />
<!-- Add support for reading web resources: css, images, js... -->
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
I'm both grateful and sorry for anybody who has read through all of this

NPE in my service class of rest using jersey with spring

I am new to spring and rest i am still learning it. I have a problem while calling the resource from my rest api through a client.
I have some data in my database and i am using spring to inject the values and get connection.
When i am making a GET request from the client i am getting a NPE.
Below is my DAO Class
public interface CustomerDao {
public List<Customer> getCustomersDao();
}
DAOImpl
public class CustomerDaoImpl implements CustomerDao {
private JdbcTemplate template;
#Autowired
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public List<Customer> getCustomersDao() {
return template.query("SELECT * FROM books.customers", new RowMapper<Customer>() {
#Override
public Customer mapRow(ResultSet rs, int rownumber) throws SQLException {
Customer e = new Customer();
e.setId(rs.getString(1));
e.setName(rs.getString(2));
e.setAge(rs.getString(3));
return e;
}
});
}
Service class
public class CustomerService {
#Autowired
CustomerDao customersConnection;
public List<Customer> getAllCustomers() {
return new ArrayList<Customer>(customersConnection.getCustomersDao());
}
Resource
#Path("/persons")
public class CustomerResource {
#Autowired
CustomerService customerService;
#GET
#Produces(MediaType.APPLICATION_JSON)
public List<Customer> getAllCustomers {
return customerService.getAllCustomers();
}
}
My bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.sumanth.customers" />
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="--:--://----/---" />
<property name="username" value="----" />
<property name="password" value="-----" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="customerService" class="com.sumanth.customer.db.CustomerDaoImpl">
<property name="template" ref="jdbcTemplate"></property>
</bean>
</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">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.sumanth.customer</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Error:
Caused by: java.lang.NullPointerException
at com.sumanth.customer.resource.CustomerResource.getAllCustomers(CustomerResource.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
Error line 23 :
return customerService.getAllCustomers();
I used the #Autowired to wire the beans.I know that i did a mistake while wiring them can anybody please help me out
Thank you
I have made some modifications to the web xml and my bean.xml
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/bean.xml</param-value>
</context-param>
Modified my service class
#Component annotation in my service class
My bean.xml added the below
<context:annotation-config />
My Impl class.I have added the annotation above my class
#Repository("customerService")

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

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">

Jersey API with Spring SessionFactory NullpointerException

Images of All Jars
This is the error image from the console.
I am trying to use the Jersey API along with Spring and Hibernate. However, defining session factory says NullPointerException. Can anybody help me to solve this? Added Full configuration with spring, hibernate and Jersey. Images of error and jar on top.
---------------------Dao Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Dao;
public interface AuthenticationDao extends Dao{
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------DaoHibernate Class:
package com.org.restservice.bo.user;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.type.StringType;
import org.springframework.orm.hibernate3.HibernateCallback;
import com.org.restservice.common.BaseDaoHibernate;
import com.org.restservice.common.Constant;
public class AuthenticationDaoHibernate extends BaseDaoHibernate implements AuthenticationDao{
private Log log = LogFactory.getLog(AuthenticationDaoHibernate.class);
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
System.out.println("Called Me>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
List<AuthenticationVo> findlist = new ArrayList<AuthenticationVo>();
final String sqlQuery = "SELECT USER_ID, ROLE_ID from STTM_USER_MASTER";
System.out.println("sqlQuery: "+sqlQuery);
List results = (List) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
SQLQuery sq = session.createSQLQuery(sqlQuery);
sq.addScalar("USER_ID", StringType.INSTANCE);
sq.addScalar("ROLE_ID", StringType.INSTANCE);
return sq.list();
}
});
try {
if (results.size() > 0) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
authenticationVo = new AuthenticationVo();
Object[] row = (Object[]) itr.next();
authenticationVo.setUser_id((String) row[0]);
authenticationVo.setRole_id((String) row[1]);
findlist.add(authenticationVo);
}
}
} catch (Exception e) {
System.out.println("FunctonVos error:" + e.getMessage());
}
System.out.println("Size of User List is: "
+ findlist.size());
System.out.println("Procedure call ended.");
return findlist;
}
}
---------------------Facade Class:
package com.org.restservice.bo.user;
import java.util.List;
import com.org.restservice.common.Facade;
public interface AuthenticationFacade extends Facade{
public void setAuthenticationDao(AuthenticationDao authenticationDao);
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception;
}
---------------------FacadeImpl Class:
package com.org.restservice.bo.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.common.BaseFacade;
public class AuthenticationFacadeImpl extends BaseFacade implements AuthenticationFacade{
private static final Log log = LogFactory.getLog(AuthenticationFacadeImpl.class);
private AuthenticationDao authenticationDao;
public void setAuthenticationDao(AuthenticationDao authenticationDao) {
this.authenticationDao = authenticationDao;
}
/*
* User Information List
*/
public List userInfo(AuthenticationVo authenticationVo) throws Exception{
return authenticationDao.userInfo(authenticationVo);
}
}
---------------------Business Object Class:
package com.org.restservice.bo.user;
import com.org.restservice.common.BaseObject;
public class AuthenticationVo extends BaseObject{
private static final long serialVersionUID = 1L;
private String user_id;
private String role_id;
public AuthenticationVo(String user_id, String role_id) {
super();
this.user_id = user_id;
this.role_id = role_id;
}
public AuthenticationVo() {
super();
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getRole_id() {
return role_id;
}
public void setRole_id(String role_id) {
this.role_id = role_id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((role_id == null) ? 0 : role_id.hashCode());
result = prime * result + ((user_id == null) ? 0 : user_id.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AuthenticationVo other = (AuthenticationVo) obj;
if (role_id == null) {
if (other.role_id != null)
return false;
} else if (!role_id.equals(other.role_id))
return false;
if (user_id == null) {
if (other.user_id != null)
return false;
} else if (!user_id.equals(other.user_id))
return false;
return true;
}
#Override
public String toString() {
return "AuthenticationVo [user_id=" + user_id + ", role_id=" + role_id + "]";
}
}
---------------------Action Class Declaration:
package com.org.restservice.portal.user;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.org.restservice.bo.user.AuthenticationFacade;
import com.org.restservice.bo.user.AuthenticationVo;
#Path("userService")
public class UserAction{
private final Log log = LogFactory.getLog(UserAction.class);
AuthenticationVo authenticationVo = new AuthenticationVo();
private AuthenticationFacade authenticationFacade = null;
private List<AuthenticationVo> listofUsers = new ArrayList<AuthenticationVo>();
public AuthenticationVo getAuthenticationVo() {
return authenticationVo;
}
public void setAuthenticationVo(AuthenticationVo authenticationVo) {
this.authenticationVo = authenticationVo;
}
public AuthenticationFacade getAuthenticationFacade() {
return authenticationFacade;
}
public void setAuthenticationFacade(AuthenticationFacade authenticationFacade) {
this.authenticationFacade = authenticationFacade;
}
public List<AuthenticationVo> getListofUsers() {
return listofUsers;
}
public void setListofUsers(List<AuthenticationVo> listofUsers) {
this.listofUsers = listofUsers;
}
#GET
#Produces( "application/json" )
public List<AuthenticationVo> customAction(){
if (log.isDebugEnabled()) {
log.debug("Entering into loadusers Method of AuthenticationAction: " +authenticationFacade);
}
try {
listofUsers = authenticationFacade.userInfo(authenticationVo);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>" +listofUsers.size());
/*authenticationVo.setUser_id("1234");
authenticationVo.setRole_id("134352");
listofUsers.add(authenticationVo);*/
return listofUsers;
}
}
---------------------Spring Beans Declaration:
<!-- <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> -->
<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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Database connection using jndi properties-->
<import resource="config/applicationContext-jndi.xml"/>
<import resource="config/applicationContext.xml"/>
<!-- List and Setup -->
<import resource="config/applicationContext-auth.xml"/>
</beans>
---------------------Application Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
<prop key="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</prop>
</props>
</property>
</bean>
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Transaction template for Facade -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<!-- DAO bean -->
<!-- Generic DAO - can be used when doing standard CRUD -->
<bean id="dao" class="com.org.restservice.common.BaseDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Generic Facade that can be used to do basic CRUD operations on any
objects -->
<bean id="facade" parent="txProxyTemplate">
<property name="target">
<bean class="com.org.restservice.common.BaseFacade">
<property name="Dao" ref="dao" />
</bean>
</property>
</bean>
</beans>
--------------------- Context Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- Transaction declarations for business services. -->
<bean id="authenticationFacade" parent="txProxyTemplate">
<property name="target">
<bean
class="com.org.restservice.bo.user.AuthenticationFacadeImpl">
<property name="authenticationDao">
<ref bean="authenticationDao" />
</property>
</bean>
</property>
</bean>
<!-- authenticationDao: Hibernate implementation -->
<bean id="authenticationDao"
class="com.org.restservice.bo.user.AuthenticationDaoHibernate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
</beans>
---------------------Jndi Declaration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<!-- author: Sarkar Zahir Ahamed <ahamed.sarkar#dbbl.com.bd> -->
<beans>
<!-- ========================= PERSISTENCE DEFINITIONS ========================= -->
<!-- JNDI DataSource for J2EE environments -->
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:/comp/env/jndi/orcl</value>
</property>
</bean>
</beans>
---------------------Web XML Declaration:
<?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" id="WebApp_ID" version="3.0">
<display-name>RestWebService</display-name>
<!-- Spring Listener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Jersey Servlet -->
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<!-- Register resources and providers -->
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.org.restservice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<!-- loading Spring Context for registering beans with ApplicationContext -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/classes/SpringBeans.xml</param-value>
</context-param>
<!-- welcome file -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

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" />

Categories