I am creating a simple login functionality using Spring with MongoDB. In my spring-context.xml, i defined the configuration for mongo but when I am using it inside my controller, it is showing null pointer Exception.
Spring-context.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:c="http://www.springframework.org/schema/c" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<!-- Scans the classpath of this application for #Components to deploy as beans -->
<context:component-scan base-package="Controller" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="welcome"/>
<!-- Configures Handler Interceptors -->
<mvc:interceptors>
<!-- Changes the locale when a 'locale' request parameter is sent; e.g. /?locale=de -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<mongo:mongo host="localhost" port="27017">
<mongo:options
connections-per-host="5"
connect-timeout="30000"
max-wait-time="10000"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
<mongo:db-factory dbname="Test"
mongo-ref="mongo"
/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Controller:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
private DBCollection getCollection(String collectionName)
{
System.out.println("MongoTemplate"+mongoTemplate);
return mongoTemplate.getCollection(collectionName);
}
#RequestMapping(value="/addU", method=RequestMethod.POST)
public #ResponseBody String add(#ModelAttribute("AddUser")User user, BindingResult result, ModelMap model)
{
String returnText="";
System.out.println("Inside response");
DBCollection table=getCollection("User");
BasicDBObject document = new BasicDBObject();
document.put("name", user.getName());
document.put("password", user.getPassword());
DBCursor cur = table.find(document);
if(cur.hasNext())
{
returnText="User Found Successfully";
}
else
{
returnText="User not Found";
}
return returnText;
}
}
Can anybody let me know the root cause of this error?
It looks as though you've missed the #Autowired annotation in your controller.
Try:
#Controller
public class LoginController {
private MongoTemplate mongoTemplate;
#Autowired
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
Or autowire the field directly:
#Controller
public class LoginController {
#Autowired
private MongoTemplate mongoTemplate;
Related
Question: How to set/Inject resources lazily like how it is done using the XML config in Java config.
We have spring batch program that is currently using XML configuration for uploading multiple files using the MultiResourcePartitioner. This works as intended see below config.
<?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:batch="http://www.springframework.org/schema/batch"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-3.0.xsd">
<job id="fileLoaderJob" xmlns="http://www.springframework.org/schema/batch">
<step id="moveFiles" next="batchFileUploader">
<tasklet ref="moveFilesTasklet" />
</step>
<step id="batchFileUploader" parent="batchFileUpload:master" >
<next on="*" to="archiveFiles" />
</step>
<step id="archiveFiles" >
<batch:tasklet ref="archiveFilesTasklet" />
</step>
</job>
<!--This Tasklet moves the file from say Input to Work dir -->
<bean id="moveFilesTasklet" class="com.spring.batch.fileloader.MoveFilesTasklet" scope="step" />
<step id="batchFileUpload" xmlns="http://www.springframework.org/schema/batch">
<tasklet>
<chunk reader="fileReader"
commit-interval="10000"
writer="fileWriter"
/>
</tasklet>
</step>
<bean name="batchFileUpload:master" class="org.springframework.batch.core.partition.support.PartitionStep">
<property name="jobRepository" ref="jobRepository"/>
<property name="stepExecutionSplitter">
<bean class="org.springframework.batch.core.partition.support.SimpleStepExecutionSplitter">
<constructor-arg ref="jobRepository"/>
<constructor-arg ref="batchFileUpload"/>
<constructor-arg>
<bean class="org.springframework.batch.core.partition.support.MultiResourcePartitioner" scope="step">
<property name="resources" ref="fileResources" />
</bean>
</constructor-arg>
</bean>
</property>
<property name="partitionHandler">
<bean class="org.springframework.batch.core.partition.support.TaskExecutorPartitionHandler">
<property name="taskExecutor">
<bean class="org.springframework.core.task.SimpleAsyncTaskExecutor">
<property name="concurrencyLimit" value="5" />
</bean>
</property>
<property name="step" ref="batchFileUpload"/>
</bean>
</property>
</bean>
<bean id="fileResources" class="com.spring.batch.fileloader.fileResources" />
<bean id="fileReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
<property name="resource" value="#{stepExecutionContext[fileName]}" />
<property name="lineMapper">
<bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
<property name="lineTokenizer">
<bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
<property name="delimiter" value="," />
</bean>
</property>
<property name="fieldSetMapper">
<bean class="...fileFieldSetMapper" />
</property>
</bean>
</property>
</bean>
<bean id="fileWriter" class="....fileWriter" scope="step" />
<bean id="archiveFilesTasklet" class="....ArchiveFilesTasklet" scope="step" />
</beans>
This works well. When I try to covert this to Java Config. I am getting the resources as NULL. Here is my config class.
#Configuration
#EnableBatchProcessing
#ComponentScan(basePackages = {"com.spring.batch.fileloader"})
public class SpringBatchConfig{
#Autowired
private JobBuilderFactory jobBuilders;
#Autowired
private StepBuilderFactory stepBuilders;
#Autowired
private DataSource dataSource;
#Autowired
private ResourcePatternResolver resourcePatternResolver;
#Autowired
private ReadPropertiesFile properties;
#Bean
BatchConfigurer configurer(#Qualifier("dataSource") DataSource dataSource){
return new DefaultBatchConfigurer(dataSource);
}
#Bean(name = "fileLoaderJob")
public Job csiAuditFileLoaderJob() throws Exception{
return jobBuilders.get("csiAuditFileLoaderJob")
.start(moveFiles())
.next(batchFileUploader())
.next(archiveFiles())
.build();
}
#Bean
public Step moveFiles(){
return stepBuilders.get("moveFiles")
.tasklet(new MoveFilesTasklet(properties))
.build();
}
#Bean
#Lazy
public Step batchFileUploader() throws Exception{
return stepBuilders.get("batchFileUploader")
.partitioner(batchFileUploadStep().getName(), partitioner())
.step(batchFileUploadStep())
.taskExecutor(taskExecutor())
.build();
}
#Bean
public Step archiveFiles(){
return stepBuilders.get("archiveFiles")
.tasklet(new ArchiveFilesTasklet(properties))
.build();
}
#Bean
public Step batchFileUploadStep(){
return stepBuilders.get("batchFileUploadStep")
.<MyDomain, MyDomain>chunk(10000)
.reader(fileReader(null))
.writer(fileWriter())
.build();
}
#Bean
#Lazy
public Partitioner partitioner() throws Exception{
MultiResourcePartitioner partitioner = new MultiResourcePartitioner();
Resource[] resources;
try{
/*
Here the resources is selected from a path where the previous MoveFilesTasklet moves the file
This returns null since Spring Initialize this bean eagerly before the step is called for execution.
*/
resources = resourcePatternResolver.getResources("file:" + properties.getPath() + "/*.csv");
}
catch(IOException e){
throw new RuntimeException("I/O problems when resolving the input file pattern.", e);
}
partitioner.setResources(resources);
return partitioner;
}
#Bean
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setMaxPoolSize(5);
taskExecutor.afterPropertiesSet();
return taskExecutor;
}
#Bean
#StepScope
public FlatFileItemReader<MyDomain> fileReader(
#Value("#{stepExecutionContext['fileName']}") String filename){
FlatFileItemReader<MyDomain> reader = new FlatFileItemReader<>();
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
DefaultLineMapper<MyDomain> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(new MyFieldSetMapper());
lineMapper.afterPropertiesSet();
reader.setLineMapper(lineMapper);
reader.setResource(new PathResource(filename));
return reader;
}
#Bean
public ItemWriter<MyDomain> fileWriter(){
return new FileWriter();
}
private JobRepository getJobRepository() throws Exception{
JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
jobRepositoryFactoryBean.setDataSource(dataSource);
jobRepositoryFactoryBean.setTransactionManager(getTransactionManager());
jobRepositoryFactoryBean.setDatabaseType("MySql");
jobRepositoryFactoryBean.afterPropertiesSet();
return jobRepositoryFactoryBean.getObject();
}
private PlatformTransactionManager getTransactionManager(){
return new ResourcelessTransactionManager();
}
#Bean
public JobLauncher jobLauncher() throws Exception{
SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
}
Below might be the issue
1 No need to do reader.setResource(new PathResource(filename)); inside FlatFileItemReader as it will override the resources set by partitioner Bean
2 Use PathMatchingResourcePatternResolver to load files in partitioner Bean
Sample code
ClassLoader cl = this.getClass().getClassLoader();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
resources = resolver.getResources("file:" + properties.getPath() + "/*.csv");
3: you can also add #StepScope on partitioner bean (Not sure abot this)
Hope this helps :)
My 2p with Spring Boot:
#Bean
#StepScope
public Partitioner logsPartitioner(#Value("file:${my.resources.path}/${my.resources.input:*}.csv") Resource[] resources) {
MultiResourcePartitioner partitioner = new MultiResourcePartitioner();
partitioner.setResources(resources);
partitioner.partition(resources.length);
return partitioner;
}
I have the aspect(see below) which should log actions(create, update, delete) in db. Depends on action logging happens in a preProcess or postProcess method. I shouldn't log anything if some fail happens through these actions. I.e. if create didn't happened, then there is no need to logging it.
I tried to tested it. I throw RunTimeException in the join point and expect that there is no new log in db. Unfortunately, new log is saved in spite of exception in the join point.
Aspect:
#Component
#Aspect
public class LoggingAspect {
#Autowired
private ApplicationContext appContext;
#Autowired
private LoggingService loggingService;
#Around("#annotation(Loggable)")
#Transactional
public void saveActionMessage(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature ms = (MethodSignature) joinPoint.getSignature();
Loggable m = ms.getMethod().getAnnotation(Loggable.class);
LoggingStrategy strategy = appContext.getBean(m.strategy());
Object argument = joinPoint.getArgs()[0];
strategy.preProcess(argument);
joinPoint.proceed();
strategy.postProcess(argument);
}
}
TestApplicationConfig:
<context:spring-configured/>
<import resource="applicationConfig-common.xml"/>
<import resource="applicationConfig-security.xml"/>
<aop:aspectj-autoproxy/>
<util:map id="testValues">
<entry key="com.exadel.mbox.test.testSvnFile" value="${svnFolder.configPath}${svnRoot.file[0].fileName}"/>
<entry key="com.exadel.mbox.test.testCommonRepositoryPath" value="${svnRoot.commonRepositoryPath}"/>
<entry key="com.exadel.mbox.test.testMailFile" value="${mailingList.configPath}"/>
</util:map>
<context:component-scan base-package="com.exadel.report.common" />
<!-- Jpa Repositories -->
<jpa:repositories base-package="com.exadel.report.common.dao" />
<tx:annotation-driven proxy-target-class="true"
transaction-manager="txManager" mode="aspectj"/>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- Data Source -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:testdb" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<!-- Entity Manager -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect"/>
</bean>
</property>
<property name="persistenceUnitName" value="exviewer-test"/>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
[Update]
LoggingStrategy:
public interface LoggingStrategy {
public void preProcess(Object obj);
public void postProcess(Object obj);
}
BaseLoggingStrategy:
public class BaseLoggingStrategy implements LoggingStrategy {
#Override
public void preProcess(Object obj) {}
#Override
public void postProcess(Object obj) {}
}
UpdateProcessStrategy:
#Service
public class UpdateProcessStrategy extends BaseLoggingStrategy {
#Autowired
private LoggingService loggingService;
#Autowired
private UserService userService;
#Autowired
DeviceService deviceService;
private Device currentDevice;
#Override
#Transactional
public void preProcess(Object obj) {
currentDevice = (Device) obj;
Device previousDevice = deviceService.getById(currentDevice.getId());
String deviceDataBeforeUpdate = deviceService.getDeviceDetailsInJSON(previousDevice);
String deviceDataAfterUpdate = deviceService.getDeviceDetailsInJSON(currentDevice);
String login = userService.getCurrentUser().getLogin();
String actionMessage = LoggingMessages.DEVICE_UPDATE.name();
loggingService.save(
new Logging(
login,
actionMessage,
deviceDataBeforeUpdate,
deviceDataAfterUpdate,
new Date())
);
}
#Override
public void postProcess(Object obj) {}
}
Class intercepted by aspcet:
#Service
public class DeviceService {
#Loggable(value = LoggingMessages.DEVICE_CREATE, strategy = CreateProcessStrategy.class)
#Transactional
public void create(Device device) {
createOrUpdate(device);
}
#Loggable(value = LoggingMessages.DEVICE_UPDATE, strategy = UpdateProcessStrategy.class)
#Transactional
public void update(Device device) {
createOrUpdate(device);
}
private void createOrUpdate(Device device) {
deviceRepository.save(device);
}
#Loggable(value = LoggingMessages.DEVICE_REMOVE, strategy = RemoveProcessStrategy.class)
public void remove(Long deviceId) {
deviceRepository.delete(deviceId);
}
}
Loggable annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface Loggable {
LoggingMessages value();
Class<? extends LoggingStrategy> strategy();
}
Log for update action contains:
id, created_dtm, action(DEVICE_UPDATE), device_data_before_action_on_the_device(in json format), device_data_after_action_on_the_device(in json format), created_by.
Disclaimer: Actually I am not a Spring expert, maybe someone else can help you out here. My field of expertise it AspectJ, which is how I found your question.
Anyway, you have two issues here:
#Transactional annotation on your aspect's advice LoggingAspect.saveActionMessage(..). Actually I have no idea if this works at all (I found no example using #Transactional on an aspect method/advice on the web, but maybe I searched in the wrong way) because declarative transaction handling in Spring is implemented via proxy-based technology, just like Spring AOP. Read the chapter 12 about transaction management in the Spring manual for further details, especially chapter 12.5.1. I am pretty sure you will find a way to do what you want there.
Nested transactions, because e.g. UpdateProcessStrategy.preProcess(..) is called by the very advice which is meant to be transactional, but is declared #Transactional too. So you have a transaction within a transaction. How Spring handles this, I have no idea, but maybe this tutorial about Spring transaction propagation contains enlightening details.
The Spring manual lists several means to implement transactional behaviour: programmatically, declaratively via annotations, XML-based <tx:advice> stuff and so forth. I don't know which way is the best for you, I merely wanted to provide some general hints.
i'm working on a spring web application using spring data jpa lately
i have problems with the persistence configuration :
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = "com.servmed")
#PropertySource({ "/resources/hibernate.properties" })
#EnableJpaRepositories(basePackages = "com.servmed.repositories")
public class PersistenceConfig {
#Autowired
private Environment env;
Properties jpaProperties() {
return new Properties() {
{
setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); //allows Hibernate to generate SQL optimized for a particular relational database.
setProperty("hibernate.show_sql",env.getProperty("hibernate.show_sql"));
}
};
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
{
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setJpaProperties(jpaProperties());
factory.setPackagesToScan("com.servmed.models");
//factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}
#Bean
public PlatformTransactionManager transactionManager()
{
EntityManagerFactory factory = entityManagerFactory().getObject();
return new JpaTransactionManager(factory);
}
#Bean
public HibernateExceptionTranslator hibernateExceptionTranslator(){
return new HibernateExceptionTranslator();
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
}
i get this error and i can't seem to find what's wrong :
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/servmed/configuration/PersistenceConfig.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory]]
PS: i noticed that the hibernate entity manger i added to libraries is depecated , should i replace with something else ?
Not entirely sure what the problem is but I believe your entity manager definition might be busted somewhere.
I use this definition that is pretty close to your. Have a look.
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(this.dataSource());
emf.setPackagesToScan("com.servmed.models");
emf.setPersistenceUnitName("MyPU");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(va);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
jpaProperties.put("hibernate.hbm2ddl.auto", "create");
emf.setJpaProperties(jpaProperties);
emf.afterPropertiesSet();
return emf;
}
<?xml version="1.0" encoding="UTF-8"?>
<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: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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.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-3.0.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<context:annotation-config/>
<context:component-scan base-package="com.wish.anthem.hippa" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.wish.anthem.hippa.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${jpa.showSql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> -->
<bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- <tx:annotation-driven /> -->
<!-- <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" /> -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="ignoreAcceptHeader" value="true" />
<property name="mediaTypes">
<map>
<entry key="xml" value="application/xml"/>
<entry key="json" value="application/json"/>
</map>
</property>
</bean>
</beans>
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/anthem
jdbc.username=root
jdbc.password=
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app><?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>anthem</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcherservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcherservlet-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
<jsp:forward page="anthemlogin.htm" />
#SuppressWarnings("unchecked")
#Repository
public class CatalogDaoImpl implements CatalogDao
{
#Autowired
private SessionFactory sessionFactory;
#Autowired
private JdbcTemplate jdbcTemplate;
#Override
#Transactional
public List<Catalog> getAllCatalogs()
{
Session session = sessionFactory.openSession();
Query query = session.createQuery("select c from Catalog c");
List<Catalog> catalogs = query.list();
session.close();
return catalogs;
}
}
#Entity
#Table(name = "h_product")
public class Product implements Serializable
{
private static final long serialVersionUID = 353305417649482096L;
#Id
#GeneratedValue
#Column(name = "ProductID", nullable = false)
private Integer productID = 0;
#Column(name = "ProductItem", nullable = false, length = 50)
private String productItem = "";
#Column(name = "ProductName", nullable = false, length = 50)
private String productName = "";
#Column(name="Title", nullable=false, length=50)
private String title = "";
#Column(name = "CreateTime", nullable = false, length = 19)
private Date createTime = Utils.getCurrentDateTimeDate();
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public String getProductItem() {
return productItem;
}
public void setProductItem(String productItem) {
this.productItem = productItem;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((productID == null) ? 0 : productID.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;
Product other = (Product) obj;
if (productID == null)
{
if (other.productID != null)
return false;
}
else if (!productID.equals(other.productID))
return false;
return true;
}
}
#Component
public class HippaServiceImpl implements HippaService
{
#Autowired
private HippaDao catalogDao;
}
#Controller
public class HippaController
{
final static Logger logger = Logger.getLogger(HippaController.class);
#Autowired
private HippaService hippaService;
#RequestMapping(value="/anthemlogin", method = RequestMethod.GET)
public String showLoginPage(HttpServletRequest request,HttpSession session)
{
logger.info("Home Page!!!!!!!!");
return "home";
}
<?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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:property-placeholder location="classpath:datasource.properties" />
<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="minPoolSize" value="${jdbc.miniPoolSize}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
<property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
<property name="acquireIncrement" value="${jdbc.acquireIncrement}" />
<property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}" />
<property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}" />
<property name="testConnectionOnCheckin" value="${jdbc.testConnectionOnCheckin}" />
<property name="preferredTestQuery" value="${jdbc.preferredTestQuery}" />
<property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
</bean>
<!-- JPA EntityManagerFactory -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}" p:showSql="${jpa.showSql}" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.jdbc.fetch_size">${hibernate.jdbc.fetch_size}</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop>
<prop key="hibernate.default_batch_fetch_size">${hibernate.default_batch_fetch_size}</prop>
<prop key="hibernate.search.default.directory_provider">${hibernate.search.default.directory_provider}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<aop:aspectj-autoproxy proxy-target-class="true" />
<context:component-scan base-package="com.wish" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
jdbc.miniPoolSize=1
jdbc.maxPoolSize=10
jdbc.initialPoolSize=1
jdbc.maxIdleTime=21600
jdbc.acquireIncrement=1
jdbc.acquireRetryAttempts=30
jdbc.acquireRetryDelay=1000
jdbc.testConnectionOnCheckin=true
jdbc.preferredTestQuery=select 1
jdbc.idleConnectionTestPeriod=3600
hibernate.search.default.directory_provider=com.wish.common.resource.hibernate.search.WishFSDirectoryProvider
jpa.database=MYSQL
jpa.showSql=false
hibernate.hbm2ddl.auto=update
hibernate.jdbc.fetch_size=50
hibernate.jdbc.batch_size=30
hibernate.default_batch_fetch_size=8
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/bbcrafts?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=
#Service
public class OrderDao implements IOrderDao
{
#PersistenceContext
private EntityManager em;
#SuppressWarnings("unchecked")
#Override
public List<Order> getOrdersForTracking(String orderCode, String realName) throws RuntimeException
{
StringBuffer sql = new StringBuffer("select o from Order o");
sql.append(" where (o.orderCode = ?1) and (o.billingRealName like concat('%',?2,'%')");
sql.append(" or o.shippingRealName like concat('%',?3,'%'))");
sql.append(" order by o.dateTime desc");
Query query = em.createQuery(sql.toString());
query.setParameter(1, orderCode);
query.setParameter(2, realName);
query.setParameter(3, realName);
return query.getResultList();
}
TO find: Order temp = em.find(Order.class, orderID);
return temp != null ? temp : new Order();
Libs:
activation-1.1, antlr-2.7.6, antlr-runtime-3.0, aopappliance-1.0, apache-lucene, commons-collections-3.1, commons-io-2.0.1, commons-logging-1.0.4, dom4j, ejb3-persistence-1.0.2.GA, hibernate3, hibernate-annoatation-3.4.0.GA, hibernate-commons-annoatation-3.1.0.GA, hibernate-core-3.3.2.GA, hibernate-entitymanager-3.4.0.GA, hibernate-search-3.1.1.GA, hibernate-validator-3.1.0.GA, javax.transaction, jstl-1.2, log4j, log4j-1.2.13, logback, javaassist-3.4.GA, jackson-all-1.9.0, IKanalyzer-3.1.2.GA, mysql-connector-java-5.1.18-bin, org-apache-commons-logging, pinyin4j-2.5.0, slf4j-api-1.7.9, all spring jars
I have simple web service server which receive SOAP with MIME attachment, store it to the HashMap and send back message with this mime attachment:
Java 1.7.0_13-b20
Spring WS 2.1.3
MOXy implementation of JAXB (EclipseLink 2.4.1)
Glassfish 3.1.1
MIME attachment & SOAP
enabled SAAJ MimePull to save to the hard drive
based on Enabling large file transfers through SOAP with Spring WS, MTOM/XOP and JAXB2 and Spring WS "mtom" sample
tested by SoapUI
If I send Request with small attachment (<80MB) everything is OK but when I send Request with >80 MB attachment the DataHandler object is null. So it is not parsed from Request and not stored to the HashMap. Does not matter if I have enabled mimepull, if yes the large attachment is stored to the temporary folder on hard drive.
Enabled MimePull:
-Dsaaj.use.mimepull=true
-Djava.io.tmpdir=/path/to/tmpdir
Enlarged GlassFish Thread Pools:
"Max Thread Pool Size" from 5 to 32
"Min Thread Pool Size" from 2 to 16
ImageRequest.java
package sample.mtom.schema;
#XmlRootElement
#XmlType(propOrder = {"fileName", "data"})
public class ImageRequest {
protected String fileName;
protected DataHandler data;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
#XmlMimeType("*/*")
public DataHandler getData() {
return data;
}
public void setData(DataHandler data) {
this.data = data;
}
}
ImageResponse.java
package sample.mtom.schema;
#XmlRootElement
#XmlType(propOrder = {"fileName", "data"})
public class ImageResponse {
// the same as ImageRequest
}
package-info.java
#XmlSchema(namespace = "http://www.example.org/Image",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package sample.mtom.schema;
import javax.xml.bind.annotation.XmlSchema;
StubRepository.java
package sample.mtom.service;
public class StubRepository implements Repository {
private Map<String, DataHandler> files = new HashMap();
public DataHandler readFile(String name) throws IOException {
return files.get(name);
}
public void storeFile(String name, DataHandler file) throws IOException {
files.put(name, file);
}
}
ImageRepositoryEndpoint.java
package sample.mtom.ws;
#Endpoint
public class ImageRepositoryEndpoint {
private static Repository repository;
static {
repository = new StubRepository();
}
#PayloadRoot(localPart = "imageRequest", namespace = "http://www.example.org/Image")
#ResponsePayload
public ImageResponse handleRequest(#RequestPayload ImageRequest request) throws IOException {
repository.storeFile(request.getFileName(), request.getData());
ImageResponse response = new ImageResponse();
response.setFileName(request.getFileName());
response.setData(repository.readFile(request.getFileName()));
return response;
}
}
schema.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xmime="http://www.w3.org/2005/05/xmlmime"
targetNamespace="http://www.example.org/Image"
elementFormDefault="qualified">
<xsd:element name="imageRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="fileName" type="xsd:string"/>
<xsd:element name="data" type="xsd:base64Binary" xmime:expectedContentTypes="*/*"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="imageResponse">
<!-- the same as imageRequest -->
</xsd:element>
</xsd:schema>
web.xml
<?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_3_0.xsd"
version="3.0">
<display-name>MyCompany HR Holiday Service</display-name>
<servlet>
<servlet-name>spring-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-ws</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
spring-ws-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="sample.mtom.ws"/>
<bean id="defaultMethodEndpointAdapter"
class="org.springframework.ws.server.endpoint.adapter.DefaultMethodEndpointAdapter">
<property name="methodArgumentResolvers" ref="marshallingPayloadMethodProcessor"/>
<property name="methodReturnValueHandlers" ref="marshallingPayloadMethodProcessor"/>
</bean>
<bean id="marshallingPayloadMethodProcessor"
class="org.springframework.ws.server.endpoint.adapter.method.MarshallingPayloadMethodProcessor">
<constructor-arg ref="jaxb2Marshaller"/>
</bean>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan" value="sample.mtom.schema"/>
<property name="mtomEnabled" value="true"/>
</bean>
<sws:dynamic-wsdl id="image"
portTypeName="ImageResource"
locationUri="/">
<sws:xsd location="/WEB-INF/schema.xsd"/>
</sws:dynamic-wsdl>
</beans>
Been trying to setup a Struts2 + Sprint + Hibernate basic framework and was working on creating a sample application. Everything configured and the stack doesnt through any error/exception while starting tomcat. Even when I run the action it doesnt throw any Exception, but on the browser it throws the following stack
Unable to instantiate Action, signupFormAction, defined for 'signupForm' in namespace '/'signupFormAction
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:318)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
root cause
java.lang.ClassNotFoundException: signupFormAction
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491)
com.opensymphony.xwork2.util.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:157)
com.opensymphony.xwork2.ObjectFactory.getClassInstance(ObjectFactory.java:107)
com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:223)
com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:143)
com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150)
com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:120)
com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:299)
com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91)
My struts.xml
<struts>
<!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" />-->
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default" namespace="/">
<action name="login" class="loginAction">
<result name="success">welcome.jsp</result>
<result name="error">login.jsp</result>
</action>
<action name="signup" class="registerAction" method="add">
<result name="success">welcome.jsp</result>
<result name="error">login.jsp</result>
</action>
<action name="signupForm" class="signupFormAction">
<result name="input">registerForm.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
My SpringBeans.xml
<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-2.5.xsd">
<!-- Database Configuration -->
<import resource="config/spring/DataSource.xml" />
<import resource="config/spring/HibernateSessionFactory.xml" />
<!-- Beans Declaration -->
<import resource="com/srisris/khiraya/spring/register.xml" />
<import resource="com/srisris/khiraya/spring/login.xml" />
</beans>
My register.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<!-- <bean id="ownerService" class="com.srisris.khiraya.service.OwnerServiceImpl">-->
<!-- <property name="ownerDAO" ref="ownerDAO" />-->
<!-- </bean>-->
<bean id="signupForm" class="com.srisris.khiraya.action.RegisterAction"/>
<!-- <bean id="registerAction" class="com.srisris.khiraya.action.RegisterAction">-->
<!-- <property name="ownerService" ref="ownerService" /> -->
<!-- </bean>-->
<!-- <bean id="ownerDAO" class="com.srisris.khiraya.dao.OwnerDAOImpl" >-->
<!-- <property name="sessionFactory" ref="sessionFactory" />-->
<!-- </bean>-->
</beans>
My Action Class
package com.srisris.khiraya.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.srisris.khiraya.dao.hibernate.Owner;
import com.srisris.khiraya.service.OwnerService;
#SuppressWarnings("rawtypes")
public class RegisterAction extends ActionSupport implements ModelDriven{
private static final long serialVersionUID = 6521996078347478542L;
private String ownerFirstName;
private String ownerLastName;
private String username;
private String password;
private String ownerPhone;
private String ownerEmail;
private OwnerService ownerService;
Owner owner = new Owner();
public void setOwnerService(OwnerService ownerService) {
this.ownerService = ownerService;
}
public String add() {
owner.setOwnerFirstName(ownerFirstName);
owner.setOwnerLastName(ownerLastName);
owner.setOwnerPassword(password);
owner.setOwnerPhone(ownerPhone);
owner.setOwnerEmail(ownerEmail);
ownerService.save(owner);
return SUCCESS;
}
public String execute() {
return INPUT;
}
public String getOwnerFirstName() {
return ownerFirstName;
}
public void setOwnerFirstName(String ownerFirstName) {
this.ownerFirstName = ownerFirstName;
}
public String getOwnerLastName() {
return ownerLastName;
}
public void setOwnerLastName(String ownerLastName) {
this.ownerLastName = ownerLastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getOwnerPhone() {
return ownerPhone;
}
public void setOwnerPhone(String ownerPhone) {
this.ownerPhone = ownerPhone;
}
public String getOwnerEmail() {
return ownerEmail;
}
public void setOwnerEmail(String ownerEmail) {
this.ownerEmail = ownerEmail;
}
public Object getModel() {
return owner;
}
}
I made a trivial mistake which costed me hours of pain. Silly me the problem was that my class name in struts.xml and id in register.xml were not matching and hence the issue.