on submitting form to addUser controller exception occured
SEVERE: Servlet.service() for servlet dispatcherServlet threw exception
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'userBean' on field 'email': rejected value [hello]; codes [Email.userBean.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userBean.email,email]; arguments []; default message [email]]; default message [Not a vaild Email Address]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)
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.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Thread.java:744)
Controller for getting Form
#RequestMapping(method = RequestMethod.GET, value = "register")
public String addUser(Model model) {
if (!model.containsAttribute("wrongLink")) {
System.out.println("not wrong Link");
model.addAttribute(new UserBean());
} else {
System.out.println("wrong Link");
}
return "user/register";
}
Controller to post form
#RequestMapping(method = RequestMethod.POST, value = "register")
public String addUser(#Valid UserBean userBean, Model model,
RedirectAttributes redirectAttrs, BindingResult bindingResult) {
System.out.println("in addUser form");
if (bindingResult.hasErrors()) {
System.out.println("ERROR in user Form");
return "user/edit";
}
return "redirect:/users/" + user.getDisplayName();
}
UserBean class
import org.hibernate.validator.constraints.Email;
public class UserBean {
private Integer id;
#Email(message = "Not a vaild Email Address")
private String email;
//getter and setter
}
Form
<div id="container">
<sf:form method="POST" modelAttribute="userBean">
<div class="form">
<sf:input path="email" type="text" id="email"
placeholder="email address" />
<sf:errors path="email" cssClass="error" />
<input class="send submit" type="submit" name="submit_first"
id="submit_first" value="" />
</div>
</sf:form>
</div>
spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
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/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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<context:component-scan base-package="com.example" />
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="${smtp.host}" />
<property name="port" value="${smtp.port}" />
<property name="username" value="${smtp.username}" />
<property name="password" value="${smtp.password}" />
<property name="javaMailProperties">
<props>
<!-- Use SMTP transport protocol -->
<prop key="mail.transport.protocol">smtp</prop>
<!-- Use SMTP-AUTH to authenticate to SMTP server -->
<prop key="mail.smtp.auth">true</prop>
<!-- Use TLS to encrypt communication with SMTP server -->
<prop key="mail.smtp.starttls.enable">true</prop>
<prop key="mail.debug">true</prop>
</props>
</property>
</bean>
<bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="${alertMailMessage.from}" />
<property name="to" value="${alertMailMessage.to}" />
<property name="subject" value="${alertMailMessage.subject}" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1000000" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/**" location="/resources/" />
<mvc:annotation-driven />
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/properties/database.properties</value>
<value>/WEB-INF/properties/smtp.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.example.model" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
why this exception is coming on entering invalid email rather than validation has to be performed.
In your controller's addUser method, your BindingResult needs to be immediately after the bean:
public String addUser(#Valid UserBean userBean, BindingResult bindingResult,
Model model, RedirectAttributes redirectAttrs) {
...
}
Related
I have an issue when i run my application as a standalone web application using Tomcat.
I use spring , struts 2 and hibernate .
The weird part is when i run the application from the embedded tomcat in my STS IDE it is running fine.
In both scenarios the web application runs fine but certain hibernate models are not getting initialized causing certain screens to fail when the application is run in the stand alone mode.
Any help/direction would be greatly appreciated.
Below is the exact error:
Error in Pre-loading models or ppa_ids
org.springframework.orm.hibernate3.HibernateQueryException: RealTimeModel is not mapped [select distinct forecast_model from RealTimeModel]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: RealTimeModel is not mapped [select distinct forecast_model from RealTimeModel]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:656)
applicationContext.xml
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- MyBatis setup start -->
<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>
<context:property-placeholder location="classpath:jdbc.properties" />
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="permissionMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.PermissionMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="roleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.RoleMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="authorityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.guzmanenergy.dal.AuthorityMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="permissionService" class="com.guzmanenergy.service.impl.PermissionServiceImpl">
<property name="permissionMapper" ref="permissionMapper"></property>
</bean>
<bean id="authorityService" class="com.guzmanenergy.service.impl.AuthorityServiceImpl">
<property name="authorityMapper" ref="authorityMapper"></property>
</bean>
<bean id="userServiceTarget" class="com.guzmanenergy.service.impl.UserServiceImpl">
<property name="usermapper" ref="userMapper"></property>
</bean>
<bean id="userService" parent="txProxyTemplate">
<property name="target" ref="userServiceTarget"></property>
</bean>
<!-- MyBatis setup stop -->
<!-- email setup start -->
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.gmail.com" />
<property name="port" value="587" />
<!-- 25, 465, 587 -->
<property name="username" value="support#getrident.com" />
<property name="password" value="Aragon101!" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
<!-- <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> -->
<!-- <property name="host" value="smtp.gmail.com" /> -->
<!-- <property name="port" value="587" /> 25, 465, 587 -->
<!-- <property name="username" value="GPMreporting#gmail.com" /> -->
<!-- <property name="password" value="Guzman1234" /> -->
<!-- <property name="javaMailProperties"> -->
<!-- <props> -->
<!-- <prop key="mail.smtp.auth">true</prop> -->
<!-- <prop key="mail.smtp.starttls.enable">true</prop> -->
<!-- </props> -->
<!-- </property> -->
<!-- </bean> -->
<bean id="resetPasswordMailer" class="com.guzmanenergy.util.ResetPasswordMailer">
<property name="mailSender" ref="mailSender" />
</bean>
<bean id="sendEmail" class="com.guzmanenergy.util.SendMail">
<property name="mailSender" ref="mailSender" />
</bean>
<!-- email setup stop -->
<!-- Spring + Hibernate Configuration -->
<import resource="applicationContext-hibernate.xml"/>
<!-- Curve Action Beans -->
<bean id="curveDao" class="com.guzmanenergy.action.dao.Impl.CurveDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<bean id="curveService" class="com.guzmanenergy.action.service.Impl.CurveServiceImpl" scope="prototype">
<property name="curveDao">
<ref bean="curveDao"/>
</property>
</bean>
<bean id="curveAction" class="com.guzmanenergy.action.CurveAction_s2sh" scope="prototype">
<property name="curveService">
<ref bean="curveService"/>
</property>
</bean>
<!-- Curve Action Beans End -->
<!-- Beans for physical_longterm_main -->
<bean id="physicalLongtermMainDao" class="com.guzmanenergy.action.dao.Impl.PhysicalLongtermMainDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<!-- Beans for physical_longterm_main End-->
<!-- Real Time Model Beans -->
<bean id="realTimeModelDao" class="com.guzmanenergy.action.dao.Impl.RealTimeModelDaoImpl" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<bean id="realTimeModelService" class="com.guzmanenergy.action.service.Impl.RealTimeModelServiceImpl" scope="prototype">
<property name="realTimeModelDao">
<ref bean="realTimeModelDao"/>
</property>
<property name="physicalLongtermMainDao">
<ref bean="physicalLongtermMainDao"/>
</property>
</bean>
<bean id="RealTimeModelAction" class="com.guzmanenergy.action.RealTime_Model_Action" scope="prototype">
<property name="realTimeModelService">
<ref bean="realTimeModelService"/>
</property>
</bean>
<!-- Real Time Model Beans -->
<!-- forecast model download -->
<bean id="ForcastModelDownloadAction" class="com.guzmanenergy.action.ForcastModelDownloadAction" scope="prototype">
<property name="realTimeModelService">
<ref bean="realTimeModelService"/>
</property>
</bean>
<!-- forecast model download -->
<!-- Spring + Hibernate Configuration End -->
applicationContext-hibernate.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: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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="ETRM_database">
<property name="locations">
<value>classpath:jdbc.properties</value>
</property>
</bean>
<!--
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<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="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<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="Hibernate_sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/guzmanenergy/action/domain</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="generate_statistics">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory</prop>
</props>
</property>
<!--
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
-->
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" scope="prototype">
<property name="sessionFactory">
<ref bean="Hibernate_sessionFactory"/>
</property>
</bean>
<tx:advice id="ETRM_tx" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" read-only="false"/>
<tx:method name="update*" read-only="false"/>
<tx:method name="delete*" read-only="false"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut expression="execution(* com.guzmanenergy.action.service.Impl.*.*(..))" id="ETRM_perform"/>
<aop:advisor advice-ref="ETRM_tx" pointcut-ref="ETRM_perform"/>
</aop:config>
Found the answer , the hbm.xml files were in the main/java folder. but they ought to be in the main/resources folder.
I am trying to map same embeddable object to my entity class.
#Entity
public class Person {
#Embedded
public Address home;
#Embedded
public Address work;
}
#Embeddable
public class Address {
public String street;
public String poBox;
}
and below is my configuration file
<?xml version="1.0" encoding="UTF-8"?>
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/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<!-- access -->
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/portfolio" />
<property name="user" value="root" />
<property name="password" value="root" />
<!-- pool sizing -->
<property name="initialPoolSize" value="3" />
<property name="minPoolSize" value="6" />
<property name="maxPoolSize" value="25" />
<property name="acquireIncrement" value="3" />
<property name="maxStatements" value="0" />
<!-- retries -->
<property name="acquireRetryAttempts" value="30" />
<property name="acquireRetryDelay" value="1000" /> <!-- 1s -->
<property name="breakAfterAcquireFailure" value="false" />
<!-- refreshing connections -->
<property name="maxIdleTime" value="180" /> <!-- 3min -->
<property name="maxConnectionAge" value="10" /> <!-- 1h -->
<!-- timeouts and testing -->
<property name="checkoutTimeout" value="5000" /> <!-- 5s -->
<property name="idleConnectionTestPeriod" value="60" /> <!-- 60 -->
<property name="testConnectionOnCheckout" value="true" />
<property name="preferredTestQuery" value="SELECT 1" />
<property name="testConnectionOnCheckin" value="true" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan">
<list>
<value>com.app.db.entities</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory
</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.jdbc.batch_size">20</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.connection.isolation">2</prop>
***<prop key="hibernate.implicit_naming_strategy">org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl</prop>***
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
On startup its still giving me the below error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/hibernate-config.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Repeated column in mapping for entity: com.app.db.entities.Person column: street (should be mapped with insert="false" update="false")
As you can see I am using <prop key="hibernate.implicit_naming_strategy">org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl</prop> in the configuration . I thought this way you can have the embeddable object more than once in a class.
If i give a random string for the naming strategy its failing saying the class is not found. So I assume the configuration is read. Is there something I am missing here ? Any help is appreciated.
I am getting below error whenever I am using RedirectAttributes in my controller method if I am adding any other thing like ModelMap or Model then it is not giving any error. Why?
I checked on the net for the solution but I did not find anything.
java.lang.IllegalArgumentException: argument type mismatch
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.controller" />
<mvc:annotation-driven />
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#localhost:1521:xe" />
<property name="username" value="system" />
<property name="password" value="system" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="userDAO" class="userDAO.UserDAOImpl"/>
<bean id="userService" class="userService.UserServiceImpl"/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
</beans>
//Controller class
#RequestMapping("/Check")
public String Check(#ModelAttribute("adduser") User user,ModelMap model,RedirectAttributes rd)
//This is my function
{
System.out.println(user.getUsername());
System.out.println(user.getPassword());
rd.addFlashAttribute("ajay", "Cjal");
model.addAttribute("Username",user.getUsername());
User result=userService.getByUserName(user.getUsername());
System.out.println(result);
if(result == null)
{
userService.addUser(user);
return "redirect:SuccessfulRegistration.html";
}
else
{
return "redirect:RegistrationError.html";
}
}
What is the Spring version you are using? RedirectAttributes has been added since Spring 3.1 release. Please check example at http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/
I am having a main datasource, where I have read/write access and another datasource, where I just pull the data out and import it into my main datasource.
At the moment my whole application just uses the read/write database. Therefore, I configured it like that:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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:security="http://www.springframework.org/schema/security"
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/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:annotation-config />
<context:component-scan base-package="com.limitCalculator"
annotation-config="true" />
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
<bean id="mainGUI" class="com.limitCalculator.gui.scenarioSelection.MainWindow" />
<!-- 1 Data Source -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:hsql://localhost/testDB" />
<property name="username" value="sa" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="jpaData" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- 2 Data Source -->
<bean id="dataSource2" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url"
value="jdbc:oracle:thin:#test.com.vi:1234:TEST" />
<property name="username" value="test_db" />
<property name="password" value="abcde" />
<property name="maxActive" value="20" />
</bean>
</beans>
My DAO Call:
#Component
public class SettingsDaoImpl {
#Autowired
#PersistenceContext
public EntityManager em;
public SettingsDaoImpl() {
super();
}
#Transactional
public Long save(Settings sr)
{
em.persist(sr);
return sr.getId();
}
As you can see I added the second database in my application. However, I do not know how to properly call it inside my SettingsDaoImpl?
Any recommendations how to implement this in my current architecture.
You need to create different entity manager for each datasource and in the code you need to define unitName property of #PersistenceContext to inject particular entity manager.
I have this method that returns an object which is then serialized.
I'd like to set the content type of the response (e.g. as application/xml).
How can I do this?
I have found other posts but they are not very clear about how to do this for xml type
#RequestMapping(value = "/Disco/GetAreasAtLevel", method = RequestMethod.GET)
#ResponseBody
public GetAreasAtLevelResponseElement getAreasAtLevel(#RequestParam("AreaId") String areaId) {
GetAreasAtLevelResponseElement root = new GetAreasAtLevelResponseElement();
root.setArea("TEST");
return root;
}
This is my spring-ws-servlet.xml file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:sws="http://www.springframework.org/schema/web-services"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scan base-package="com.porism"/>
<sws:annotation-driven/>
<tx:annotation-driven />
<util:properties id="sqlProperties" location="classpath:sql.properties"/>
<bean id="OAuth" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
<property name="schema" ref="schema"/>
<property name="portTypeName" value="OAuth"/>
<property name="locationUri" value="/soap/OAuthService/"/>
</bean>
<bean id="schema" class="org.springframework.xml.xsd.SimpleXsdSchema">
<property name="xsd" value="WEB-INF/OAuthContract.xsd"/>
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://192.168.50.171:3306/testtoolDev" />
<property name="username" value="" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocations" value="classpath*:/hibernate.cfg.xml"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="testtoolDAO" class="com.porism.dao.testtoolDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean class="org.springframework.http.converter.AbstractHttpMessageConverter">
<property name="messageConverters">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="application/xml"/>
</bean>
</property>
</bean>
<bean id="oAuthDAO" class="com.porism.oauth.dao.OAuthDAOImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
A simple option is to set the produces attribute of the #RequestMapping annotation to MediaType.APPLICATION_XML_VALUE (or "application/xml"), e.g.
#RequestMapping(produces = MediaType.APPLICATION_XML_VALUE,
value = "/Disco/GetAreasAtLevel",
method = RequestMethod.GET)
#ResponseBody
public GetAreasAtLevelResponseElement getAreasAtLevel(
// ...
}
and at the same time specifying the #EnableWebMvc or <mvc:annotation-driven />.
These feature are available as of Spring 3.1.
#RequestMapping(value = "/Disco/GetAreasAtLevel", method = RequestMethod.GET)
#ResponseBody
public void getAreasAtLevel(#RequestParam("AreaId") String areaId, HttpServletResponse response) {
GetAreasAtLevelResponseElement root = new GetAreasAtLevelResponseElement();
root.setArea("TEST");
PrintWriter pr = response.getWriter();
response.setContentType("application/xml");
//parse your data to XML
String xml = parseXml(root);
pr.write(xml);
// rest of the code.
//
}