I am using Spring and integrating with hibernate 4 as persistence Provider, here what i ma trying is to do crud operation
on student Entity,
All my select operations are working fine, but add and update operation are not working,
My persistence.xml,
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="forSpring" transaction-type="JTA">
<class>com.entity.Student</class>
</persistence-unit>
</persistence>
My Spring-bean.xml,
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
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/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.*" />
<jee:jndi-lookup id="datasourceId" jndi-name="jdbc/myPrac" resource-ref="true" />
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager" />
<!-- Spring integration with JPA -->
<bean id="vendorAdaptor-inj" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="DERBY" />
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
<bean id="entityMgrFactory-inj" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="datasourceId" />
<property name="persistenceUnitName" value="forSpring" />
<property name="jpaVendorAdapter" ref="vendorAdaptor-inj" />
</bean>
</beans>
This is my StudentDAO,
package com.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.entity.Student;
#Repository("studentSpringDao-inj")
#Transactional(value="txManager",readOnly=true)
public class StudentSpringDAO {
#PersistenceContext(unitName="forSpring")
private EntityManager em;
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public List<Student> getStudentList() throws Exception{
System.out.println(" \n\n\n LOADING... \n\n\n ");
String query = "select s from Student s order by s.studentId desc";
TypedQuery<Student> studentQuery = em.createQuery(query,Student.class);
return studentQuery.getResultList();
}
public Integer latestStudent() throws Exception{
String query = "select max(s.studentId) from Student s";
TypedQuery<Integer> studentQuery = em.createQuery(query,Integer.class);
return studentQuery.getResultList().get(0);
}
#Transactional(value="txManager",readOnly=false,propagation=Propagation.REQUIRES_NEW)
public Student saveStudent(Student student) throws Exception{
return em.merge(student);
}
}
Just for the information, i am using jndi look-up name "jdbc/myPrac" to look-up the datasource,
Can you help me out with this, do i am missing any configuration in spring-bean.xml
#Transactional(value="txManager",readOnly=true)
What do you think readOnly=true means and have you tried it with readOnly=false?
replace the class org.springframework.transaction.jta.JtaTransactionManager
with org.springframework.orm.jpa.JpaTransactionManager and add tx:annotation-driven
Related
I am trying to migrate a project from a traditional (working) Java servlet application to Spring MVC in the NetBeans IDE, but my program absolutely refuses to ping the Controller. On the client side, I see the following 404 errors:
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
index.do?displayType=table:1 Failed to load resource: the server responded with a status of 404 (Not Found)
I invoke the controller methods like so:
$.get("index.do","displayType=table", function( data ) {
jstring = JSON.parse(data.substr(12).slice(0, -1));
});
$.get("index.do","displayType=pivot",function(unparsedJSON) {});
$.post("index.do","jsonString=" + JSON.stringify(hot.getData()));
Below are my controller and xml configuration files:
MappingControl.java
package controllers;
import infoLoader.JsonWriter;
import infoLoader.getJSON;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.springframework.http.HttpMethod.GET;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
#RequestMapping("/")
public class MappingControl {
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
}
applicationContext.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</beans>
dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" xmlns:mvc="http://www.springframework.org/schema/mvc">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index.htm">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
<mvc:resources mapping="/resources/**" location="/resources" />
<context:component-scan base-package="controllers" />
</beans>
I've been building this based on the default Spring-MVC template provided by NetBeans, so if any of you believe the template is poorly formatted and should be changed in some way, I would appreciate any input you might have.
Thanks so much for your time, guys, and let me know if anything is unclear.
You need add #ResponseBody to your method,due to in your case,you want to return the json data,if you missing #ResponseBody it will return to the view page,however you do not specify any view page in your code,thus will cause 404 error
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.GET)
public String populatePivotAndSheet(#RequestParam("displayType") String type) {
String returnedJSON = "";
try {
returnedJSON = getJSON.getJSON(type);
} catch (Exception ex) {
System.out.println("Unable to retrieve JSON");
}
return returnedJSON;
}
#ResponseBody
#RequestMapping(value="/index.do", method=RequestMethod.POST)
public void deliverSheet(#RequestParam("jsonString") String writableJSON) {
String returnedJSON = "";
JsonWriter.writeJSON(writableJSON);
}
I'm trying to get Memcache working in Spring.
I've setup a local Memcached server using Docker and Kitematic:
I can access the Memcached server using telnet: telnet 192.168.99.100 32780 and then run stats or stats items (which only prints out END if the cache is empty);
My pom.xml:
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>simple-spring-memcached</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>spring-cache</artifactId>
<version>3.6.0</version>
</dependency>
<dependency>
<groupId>com.google.code.simple-spring-memcached</groupId>
<artifactId>xmemcached-provider</artifactId>
<version>3.6.0</version>
</dependency>
In my applicationContext.xml I have the following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
...
<import resource="cacheContext.xml" />
...
In cacheContext.xml my config is as follow:
<?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:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy/>
<cache:annotation-driven/>
<context:component-scan base-package="com.google.code.ssm"/>
<context:component-scan base-package="com.mycee.application"/>
<bean id="cacheBase" class="com.google.code.ssm.aop.CacheBase"/>
<bean id="readThroughSingleCache" class="com.google.code.ssm.aop.ReadThroughSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughMultiCache" class="com.google.code.ssm.aop.ReadThroughMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readThroughAssignCache" class="com.google.code.ssm.aop.ReadThroughAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateSingleCache" class="com.google.code.ssm.aop.UpdateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateMultiCache" class="com.google.code.ssm.aop.UpdateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateAssignCache" class="com.google.code.ssm.aop.UpdateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateSingleCache" class="com.google.code.ssm.aop.InvalidateSingleCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateMultiCache" class="com.google.code.ssm.aop.InvalidateMultiCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="invalidateAssignCache" class="com.google.code.ssm.aop.InvalidateAssignCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="incrementCounterInCache" class="com.google.code.ssm.aop.counter.IncrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="decrementCounterInCache" class="com.google.code.ssm.aop.counter.DecrementCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="readCounterFromCache" class="com.google.code.ssm.aop.counter.ReadCounterFromCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean id="updateCounterInCache" class="com.google.code.ssm.aop.counter.UpdateCounterInCacheAdvice">
<property name="cacheBase" ref="cacheBase"/>
</bean>
<bean name="cacheManager" class="com.google.code.ssm.spring.SSMCacheManager">
<property name="caches">
<set>
<bean class="com.google.code.ssm.spring.SSMCache">
<constructor-arg name="cache" index="0" ref="defaultCache"/>
<constructor-arg name="expiration" index="1" value="300"/>
<constructor-arg name="allowClear" index="2" value="false"/>
</bean>
</set>
</property>
</bean>
<bean name="defaultCache" class="com.google.code.ssm.CacheFactory" depends-on="cacheBase">
<property name="cacheName" value="defaultCache"/>
<property name="cacheClientFactory">
<bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/>
</property>
<property name="addressProvider">
<bean class="com.google.code.ssm.config.DefaultAddressProvider">
<property name="address" value="localhost:11211"/>
</bean>
</property>
<property name="configuration">
<bean class="com.google.code.ssm.providers.CacheConfiguration">
<property name="consistentHashing" value="true"/>
</bean>
</property>
</bean>
</beans>
I've created three different methods, each using different caching mechanisms:
#Component("cacheEndpoint")
public class CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
To access it I do:
#Autowired
CacheClass c;
...
// caches perfectly
c.getDateTime1("test");
// doesn't do any caching
c.getDateTime2("test");
// doesn't do any caching
c.getDateTime3("test");
After placing runtime exceptions in getDateTime2 and getDateTime3, it was established that the interceptors aren't being invoked.
Any idea what could be the cause of #Cachable and #ReadThroughSingleCache not doing their interception magic?
Update based on Matjaž Pečan's response:
CacheClass Interface:
public interface CacheClass {
public String getDateTime1(String anything);
public String getDateTime2(String anything);
public String getDateTime3(String anything);
}
CacheClass Implementation:
#Component("cacheEndpoint")
public class CacheClassImpl implements CacheClass {
#Autowired
SSMCacheManager cache;
public String getDateTime1(String anything) {
SSMCache c = cache.getCache("defaultCache");
String s = c.get(anything, String.class);
if (s != null) {
return s;
}
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
c.put(anything, response);
return response;
}
#Cacheable("defaultCache")
public String getDateTime2(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(String anything) {
Date d = new Date();
String response = d.toString() + " - " + d.getTime();
return response;
}
}
SOAP Endpoint where I'm testing the cache:
#Endpoint
public class PingEndpoint {
#Autowired
CacheClass c;
#ResponsePayload
#PayloadRoot(localPart = "PingRequest", namespace = "http://www.mycee.com/Application")
public PingResponse doPing(#RequestPayload PingRequest request) {
// caches perfectly
System.out.println(c.getDateTime1("test"));
// doesn't do any caching
System.out.println(c.getDateTime2("test"));
// doesn't do any caching
System.out.println(c.getDateTime3("test"));
}
}
cacheContext.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:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<cache:annotation-driven/>
...
There is an error in SSM 3.6.0, please downgrade to 3.5.0 to solve the issue or try to add
depends-on="cacheBase"
to defaultCache bean definition.
Update 1
Self invocations don't work. A call won't be intercepted and result won't be cached if a invocation is through this object. Make sure that method defined in a bean is invoked from another Spring bean.
Update 2
For SSM method has to be annotated as below:
#ReadThroughSingleCache(namespace = "defaultCache", expiration = 15000)
public String getDateTime3(#ParameterValueKeyProvider String anything) {
...
}
Still interceptors for some reasons aren't triggered.
Spring proxying mechanisms differ depending on which implementation is used.
The default is AspectJ which requires interfaces (proxy-by-interface) and those interfaces will then be implemented by the actual proxy wrapped around your bean. Since your bean is only a class and does not have an interface, it is not proxied with AspectJ.
There are two possible solutions:
Implement an interface for CacheClass and use that interface in wiring to other beans
Use CGLib proxying (you will need to add a runtime dependency on CGLib) and add proxy-target-class in your aspectj-proxy element:
<aop:aspectj-autoproxy proxy-target-class="true"/>
I am trying to get an object from my database using Spring REST API. The problem is that I am not receiving the content correctly.
My log output:
/hello
Hibernate: select this_.id as id0_0_, this_.countryCode as countryC2_0_0_ from Country this_ where this_.countryCode=?
Found: at
And the controller I use:
import java.util.Iterator;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.mahlzeit.datamodel.HibernateTest;
import com.mahlzeit.datamodel.address.Country;
#RestController
public class HelloWorldController {
#RequestMapping(value = "/hello")//, method = RequestMethod.GET)
public Country hello(ModelMap model) {
System.out.println("/hello");
HibernateTest hbt = new HibernateTest();
Session session = hbt.sessionFactory.openSession();
Criteria cr = session.createCriteria(Country.class);
cr.add(Restrictions.eq("countryCode", "at"));
List<Country> queryAustria = cr.list();
if (queryAustria.isEmpty() == true) {
System.err.println("at not found");
return null;
}
Country austria = null;
for (Iterator<Country> iterator = queryAustria.iterator(); iterator
.hasNext();) {
Country country = (Country) iterator.next();
if (country.getCountryCode().equals("at")) {
austria = country;
break;
}
}
System.out.println("Found: "+ austria.getCountryCode());
return austria;
}
}
So, I am getting back my desired object from Hibernate but what I am actually getting back is
HTTP Status 404
This is Country.java:
#Entity
public class Country implements Serializable {
private static final long serialVersionUID = -2060021861139912774L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#NotNull
#Column(length=2,unique=true)
private String countryCode;
// Setter & Getter ..
}
Config file:
<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"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
If you are using the InternalResourceViewResolver then Spring will try to resolve the View based on view name that you are passing. So it will look for the file /WEB-INF/austria.jsp assuming the controller is returning the value as "austria". So that is the reason you are getting 404 error.
So to fix the issue, add <mvc:annotation-driven /> in Spring configuration 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:mvc="http://www.springframework.org/schema/mvc"
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">
<context:component-scan base-package="com.mahlzeit.server.mobile" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
Also you need to have the JSON related Jars in your classpath -- WEB-INF/lib folder:
jackson-core-asl-1.9.13.jar & jackson-mapper-asl-1.9.13.jar
I am trying to develop Springs-Hibernate login application with springs security. When i am trying to retrieve users from DB with Hibernate. I have proper working Springs-Hibernate Configuration. Everytime getter returning sessionFactory null (I am printing address in getSessionFactory method). I have one method getLoginDetails() which is working perfectly if i am not invoking method at login time (Checked with just simple anchor tag), but when i am logging in its not working. Here is my code:
Springs-security.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:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- This is where we configure Spring-Security -->
<security:http auto-config="true" use-expressions="true" access-denied-page="/auth/denied" >
<security:intercept-url pattern="/auth/login" access="permitAll"/>
<security:intercept-url pattern="/main/admin" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/main/common" access="hasRole('ROLE_USER')"/>
<security:form-login
login-page="/auth/login"
authentication-failure-url="/auth/hi"
authentication-success-handler-ref="myAuthenticationSuccessHandler"/>
<security:logout
invalidate-session="true"
logout-success-url="/loggedout" />
</security:http>
<!-- A custom service where Spring will retrieve users and their corresponding access levels -->
<bean id="customUserDetailsService" class="com.springs.service.CustomUserDetailsService"/>
<!--A service where spring will redirect to proper view after successfull login-->
<bean id="myAuthenticationSuccessHandler" class="com.springs.controller.MySimpleUrlAuthenticationSuccessHandler" />
<!-- Declare an authentication-manager to use a custom userDetailsService -->
<security:authentication-manager>
<security:authentication-provider user-service-ref="customUserDetailsService">
</security:authentication-provider>
</security:authentication-manager>
</beans>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<bean id="DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="DataSource"/>
<property name="packagesToScan" value="com.hibernate.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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">
<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Scan only for #Controllers -->
<context:component-scan base-package="com.springs">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<mvc:annotation-driven />
<tx:annotation-driven/>
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="index">indexController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="indexController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="index" />
</beans>
CustomerUserDetailsService.java
package com.springs.service;
import com.hibernate.model.DbUser;
import com.springs.dao.UserDAO;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {
#Autowired
private UserDAO userDAO ;
#Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
UserDetails user = null;
try {
DbUser dbUser;
userDAO=new UserDAO();
dbUser = userDAO.getLoginDetails(username);
user = new User(
dbUser.getUsername(),
dbUser.getPassword().toLowerCase(),
true,
true,
true,
true,
getAuthorities(dbUser.getAccess()));
} catch (Exception e) {
System.out.println("\n\n\n\n\n");
e.printStackTrace();
throw new UsernameNotFoundException("Error in retrieving user");
}
return user;
}
public Collection<SimpleGrantedAuthority> getAuthorities(Integer access) {
List<SimpleGrantedAuthority> authList = new ArrayList<SimpleGrantedAuthority>(2);
if (access.compareTo(1) == 0) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
} else {
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
}
return authList;
}
}
UserDAO.java
#Repository
public class UserDAO {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
System.out.println("session factory: "+sessionFactory);
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public int getdata(String username) {
String hql = "select count(*) from Userdetails";
Userdetails u = (Userdetails) getSessionFactory().openSession().get(Userdetails.class, username);
System.out.println(u.getName());
Long l = (Long) getSessionFactory().openSession().createQuery(hql).uniqueResult();
return l.intValue();
}
public DbUser getLoginDetails(String username) {
DbUser user = new DbUser();
Userdetails u = (Userdetails) getSessionFactory().openSession().get(Userdetails.class, username);
user.setUsername(u.getName());
user.setPassword(u.getPassword());
user.getAccess();
Set userroles = u.getUserroles();
Iterator it = userroles.iterator();
while (it.hasNext()) {
Userrole ux=(Userrole) it.next();
user.setAccess(ux.getRollid());
}
System.out.println("accss is: "+user.getAccess());
System.out.println("username is: "+user.getUsername());
System.out.println("pw is "+user.getPassword());
return user;
}
}
message in server log :
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/SpringSecurity] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.springs.dao.UserDAO.getdata(UserDAO.java:42)
at com.springs.controller.testController.getUser(testController.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
I am not able to figure out sessionFactory is null if i am using it at Login activity otherwise its not null. First I was missing tx annotation in xml which i added later for #Transactional annotation. How can i solve this?
Sorry, I do not see the problem. But I'd like to attache similar files from myy sample project regarding to security. I hope it helps you:
applicationContext-security.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-3.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd
">
<!-- HTTP security configurations -->
<http auto-config="true" use-expressions="true">
<form-login login-processing-url="/resources/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
<logout logout-url="/resources/j_spring_security_logout" />
<!-- Configure these elements to secure URIs in your application -->
<intercept-url pattern="/login-user/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/member/**" access="isAuthenticated()" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/login/**" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<!-- Configure Authentication mechanism -->
<authentication-manager alias="authenticationManager">
<!-- SHA-256 values can be produced using 'echo -n your_desired_password | sha256sum' (using normal *nix environments) -->
<authentication-provider>
<password-encoder hash="sha-256" />
<user-service>
<user name="admin" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" authorities="ROLE_ADMIN" />
<user name="user" password="04f8996da763b7a969b1028ee3007569eaf3a635486ddab211d512c85b9df8fb" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<context:property-placeholder location="classpath*:META-INF/spring/*.properties"/>
<context:spring-configured/>
<context:component-scan base-package="org.sample.login">
<context:exclude-filter expression=".*_Roo_.*" type="regex"/>
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
</context:component-scan>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="1800000"/>
<property name="numTestsPerEvictionRun" value="3"/>
<property name="minEvictableIdleTimeMillis" value="1800000"/>
<property name="validationQuery" value="SELECT version();"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
MyUser.java:
package org.sample.login.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Table(name = "my_user")
#Entity
public class MyUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Long id;
#Version
#Column(name = "version")
private Integer version;
/**
*/
#NotNull
#Size(min = 6)
private String name;
/**
*/
#NotNull
#Size(min = 6)
private String password;
#Override
public String toString() {
return "MyUser [name=" + name + ", password=" + password + "]";
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.servlet.mvc.support.RedirectAttributes]: Specified class is an interface
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:102)
at org.springframework.web.servlet.mvc.multiaction.MultiActionController.newCommandObject(MultiActionController.java:521)
This is my controller code
public String loginControl(HttpServletRequest request,HttpServletResponse response,RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException{
boolean status = false;
String redirect = "home";
String userName = request.getParameter("username");
String password = request.getParameter("password");
if(Utils.isNotNullNotEmptyNotWhiteSpaceOnly(userName) && Utils.isNotNullNotEmptyNotWhiteSpaceOnly(password)){
User user = homeService.checkLogin(userName, password);
if(user != null){
HttpSession session = request.getSession(true);
session.setAttribute("loggedUser", user);
redirectAttributes.addFlashAttribute("status", "success");
redirectAttributes.addFlashAttribute("messageHdr", "Password changed successfully");
return "redirect:/home.mth";
}
}
In my application-servlet I have included <mvc:annotation-driven/> as well.
Any help appreciated.
<?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"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="urlHandler" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/web/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans
>