I have the MySQL 5.5 cartridge with the following post_start_mysql (.openshift\action_hooks\post_start_mysql):
echo "********MySQL_config post_start_mysql it's running."/usr/bin/mysql -h "127.8.237.2" -u "adminc5aiLd5" \
--password="bcHxwMCKLpJ4" -P 3306 \
-e 'SET NAMES "utf8"; SET CHARACTER SET utf8; SET GLOBAL character_set_client=utf8, character_set_database=utf8, character_set_results=utf8, character_set_connection=utf8, character_set_server=utf8, collation_server=utf8_general_ci; SET character_set_client=utf8, character_set_results=utf8, character_set_connection=utf8, character_set_server=utf8, collation_server=utf8_general_ci, collation_database=utf8_general_ci;'
In my context.xml (\webapp\META-INF\context.xml) I have:
<Resource name="jdbc/currencyexchange"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://x.x.x.x:3306/xxx?autoReconnect=true"
connectionProperties="useEncoding=true&characterEncoding=UTF-8;"
username="xxx"
password="xxx"
maxActive="100" maxIdle="30" maxWait="10000"
/>
as the result:
mysql> show variables like '%character%';
+--------------------------+------------------------------------------------+
| Variable_name | Value |
+--------------------------+------------------------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | /opt/rh/mysql55/root/usr/share/mysql/charsets/ |
+--------------------------+------------------------------------------------+
I have the JBossEWS 2.0 cartridge with the following pre_start_jbossews (.openshift\action_hooks\pre_start_jbossews):
echo "*******jboss_Config pre_start_jboss it's running."
export JAVA_OPTS="$JAVA_OPTS -Dfile.encoding=UTF-8 -Dorg.apache.catalina.connector.URIEncoding=UTF-8 -Dorg.apache.catalina.connector.useBodyEncodingForURI=true"
In my server.xml (.openshift\config\server.xml) I have:
<Connector address="${OPENSHIFT_JBOSSEWS_IP}"
port="${OPENSHIFT_JBOSSEWS_HTTP_PORT}"
URIEncoding="UTF-8"
useBodyEncodingForURI="true"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
my web.xml (webapp\WEB-INF\web.xml):
<filter>
<filter-name>CharsetFilter</filter-name>
<filter-class>xx.xxx.xxx.filter.CharsetFilter</filter-class>
<init-param>
<param-name>requestEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharsetFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
CharsetFilter.java:
public class CharsetFilter implements Filter
{
private String encoding;
public void init(FilterConfig config) throws ServletException
{
encoding = config.getInitParameter("requestEncoding");
if( encoding==null ) encoding="UTF-8";
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain next)
throws IOException, ServletException
{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
next.doFilter(request, response);
}
public void destroy(){}
}
my hibernate prop:
<util:properties id="hibernateProperties">
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.connection.CharSet">utf8</prop>
<prop key="hibernate.connection.characterEncoding">utf8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.show_sql">false</prop>
</util:properties>
As the result:
enter image description here
enter image description here
the problem is in request to mysql:
.UpdateClient("update clients set name='???????'....")
I would really appreciate if some of you could help me solve this issue.
<Resource name="jdbc/currencyexchange"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://${OPENSHIFT_MYSQL_DB_HOST}:${OPENSHIFT_MYSQL_DB_PORT}/${OPENSHIFT_APP_NAME}?autoReconnect=true&useEncoding=true&characterEncoding=UTF-8
username="xxx"
password="xxx"
maxActive="100" maxIdle="30" maxWait="10000"
/>
Related
I want to check username and password in authenticationProvider but dont know why i cann't get call to authenticate method. I am implementing REST login service through spring security. my web.xml is
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml
WEB-INF/spring-security.xml</param-value>
</context-param>
<!-- Spring Security Filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>
com.sun.jersey.config.property.packages
</param-name>
<param-value>com.zymr.ojo.action</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>jsp/login.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
and spring-security.xml is as below...
<context:component-scan base-package="com.zymr.ojo" />
<security:global-method-security pre-post-annotations="enabled" secured- annotations="enabled" />
<!-- Security configuration for REST services. -->
<security:http use-expressions="true" entry-point-ref="restEntryPoint" create- session="always">
<!-- <security:http-basic/> -->
<security:intercept-url pattern="/rest/question/**" access="isAuthenticated()"/>
<!-- <security:intercept-url pattern="/rest/login/userLogin" access="permitAll"/> -->
<security:form-login login-processing-url="/rest/login/userLogin" username-parameter="admin" password-parameter="password"/>
</security:http>
<!-- Authentication manager. -->
<security:authentication-manager >
<security:authentication-provider user-service-ref="authProvider" >
</security:authentication-provider>
</security:authentication-manager>
<!-- Entry point for REST service. -->
<bean id="restEntryPoint" class="com.zymr.ojo.security.RestAuthenticationEntryPoint" />
<!-- A handler for successful REST service authentication. -->
<bean id="authSuccessHandler" class="com.zymr.ojo.security.RestAuthenticationSuccessHandler"></bean>
<bean id="authProvider" class="com.zymr.ojo.security.RestAuthenticationProvider" ></bean>
and RESTAuthenticationProvider class is
#Component public class
RestAuthenticationProvider implements AuthenticationProvider,
UserDetailsService{
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
System.out.println("in authProvider");
String username = authentication.getName();
String password = (String) authentication.getCredentials();
if(username != null && password != null){
System.out.println(username+ " "+ password);
}
return null;
}
public boolean supports(Class<?> authentication) {
// TODO Auto-generated method stub
return false;
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
System.out.println(username);
return null;
}
}
The problem is with the supports(..) method that always returns false. Your entry point should provide the user a way to populate an instance of Authentication and this will be given to the authenticate method if the supports method returns true.
Please refer to the following link. This link specified adding UsernamePasswordAuthenticationFilter. I tried this but it is not calling the login.html form.
http://www.networkedassets.com/configuring-spring-security-for-a-restful-web-services/
I am creating a website using Spring and want all pages under the folder "/admin" to be secure. However don't really know where to start and only have one complicated example to go on.
At work, we store the details in a database but I was hoping it could be more simple than that, maybe stored in context.xml or something? I am confronted with this page:
web.xml:
<security-constraint>
<display-name>admin pages</display-name>
<web-resource-collection>
<web-resource-name>Administration Pages</web-resource-name>
<description/>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<description/>
<role-name>userAdmin</role-name>
</auth-constraint>
<!-- <user-data-constraint>
<description/>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>-->
</security-constraint>
and in tomcat-users.xml I have the following password information:
<user password="password" roles="tomcat,role1,manager-script,manager-gui,admin,manager" username="user"/>
But when I try and access the page /admin/adminindex.htm, I get a forbidden error:
Access to the specified resource (Access to the requested resource has been denied) has been forbidden.
Ideally I would like to store user details in the database but can't progress with either at the moment.
I would look into Spring Security, which offers a plethora of options for securing websites (including DB-backed or JNDI-backed security). The tutorial may prove a good starting point.
This is how I secure applications using Spring Security, here is the web.xml
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-servlet.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/myapp/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
spring-security.xml
<security:http auto-config="true" use-expressions="true" access-denied-page="/" create-session="never" disable-url-rewriting="true">
<security:intercept-url pattern="/myapp/auth/login" access="permitAll" />
<security:intercept-url pattern="/myapp/main/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/" authentication-failure-url="/myapp/auth/login?error=true" default-target-url="/myapp/main/default"/>
<security:logout invalidate-session="true" logout-success-url="/myapp/auth/login" logout-url="/myapp/auth/logout" />
</security:http>
In order to authenticate using a Database you can use an Authentication Manager like this in spring-security.xml
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="passwordEncoder" />
</security:authentication-provider>
</security:authentication-manager>
Where "userService" is a service you define that has access to the Database, your service must implement org.springframework.security.core.userdetails.UserDetailsService and write the method
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException, DataAccessException {
UserDetails user = null;
try {
// Replace loadUserFromDB with your Data access method to pull the user and encrypted password from the database
Users u = loadUserFromDB(userName);
if(u != null)
user = new User(u.getEmail(), u.getPassword().toLowerCase(), true, true, true, true, getAuthorities(0));
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
Spring security will use this method to secure your pages. Make sure to include this method:
public Collection<GrantedAuthority> getAuthorities(Integer access) {
// Create a list of grants for this user
List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(1);
authList.add(new GrantedAuthorityImpl("ROLE_USER"));
authList.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS"));
return authList;
}
I would start with this: http://docs.spring.io/autorepo/docs/spring-security/3.0.x/reference/springsecurity.html You can also check out this project that already has the basic code to start using Spring Security
https://github.com/pgardunoc/spring-security
I am having troubles implementing Spring Security along with Spring MVC and Hibernate.
When I give the credentials and validate the form, it goes to the following URL:
http: //localhost:8080/test/login_error.htm;jsessionid=9BE14BCXXXXXXXXXXXXXXXX
So it redirects me to the login_error.htm page that I have configured in my spring-security.xml. It looks like a session has been created so the problems occurs after that.
I did try to debug to find out more and here is the deal:
Since UserDetailsService is configured as my authenticationProvider in my spring-security.xml, it goes into the findByUserName method in the UserDetailsServiceImpl class:
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
UserEntity userEntity = dao.findByName(username);
if (userEntity == null)
throw new UsernameNotFoundException("user not found");
return (UserDetails)assembler.buildUserFromUserEntity(userEntity);
}
When it goes to the return, the user is properly loaded, so the connection to the DB has been made and the user has been found, no issue on that side. I can't figure out where the problem is.
Here is the UserEntityDAOImpl class that I am using:
#Repository("userEntityDao")
public class UserEntityDAOImpl implements UserEntityDAO {
private SessionFactory sessionFactory;
#Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void addUser(UserEntity user) {
sessionFactory.getCurrentSession().save(user);
}
public UserEntity findByName(String username) {
Session session = sessionFactory.getCurrentSession();
UserEntity user = (UserEntity)session.createQuery("select u from UserEntity u where u.username = '" + username + "'").uniqueResult();
return user;
}
...others methods like activate, listUsers, etc...
Edit:
#Service("assembler")
public class Assembler {
#Transactional(readOnly = true)
User buildUserFromUserEntity(UserEntity userEntity) {
String username = userEntity.getUsername();
String password = userEntity.getPassword();
boolean enabled = userEntity.getActive();
boolean accountNonExpired = userEntity.getActive();
boolean credentialsNonExpired = userEntity.getActive();
boolean accountNonLocked = userEntity.getActive();
Collection<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
for (SecurityRoleEntity role : userEntity.getSecurityRoleCollection()) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
}
User user = new User(username, password, enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return user;
}
}
It is retrieving the roles properly from the DB (ROLE_Admin in my case).
Here is my spring-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"
xmlns:context="http://www.springframework.org/schema/context"
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/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/resources/**" security="none"/>
<http auto-config='true' use-expressions='true'>
<intercept-url pattern="/login*" access="isAnonymous()" />
<intercept-url pattern="/secure/**" access="hasRole('ROLE_Admin')" />
<logout logout-success-url="/home.htm" />
<form-login login-page="/login.htm" login-processing-url="/j_spring_security_check"
authentication-failure-url="/login_error.htm" default-target-url="/home.htm"
always-use-default-target="true" />
</http>
<beans:bean id="com.daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<beans:property name="userDetailsService" ref="userDetailsService" />
</beans:bean>
<beans:bean id="authenticationManager"
class="org.springframework.security.authentication.ProviderManager">
<beans:property name="providers">
<beans:list>
<beans:ref local="com.daoAuthenticationProvider" />
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
</beans:beans>
Here is the web.xml:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</servlet> -->
<!-- This listener creates the root application Context -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I suspect your user doesn't have the required permissions (i.e. Authorities) set. Enable Spring Security debug logging. What does
assembler.buildUserFromUserEntity(userEntity);
do? What do you see if in the loadUserByUsername method before returning you print UserDetails-getAuthorities() to the console?
I am using multiple http elements [with different patterns] in my spring security configuration. Each points to a separate authentication manager. I am able to login successfully for all http elements. However , after successful login, the Principal object returned is null. Please help me.
The contents of spring security are as follows
<http pattern="teacher/login*" authentication-manager-
ref="teacherAuthenticationManager">
<intercept-url pattern="teacher/login*" access="ROLE_TEACHER" />
<http-basic`enter code here` />
</http>
<http pattern="student/login*" authentication-manager-
ref="studentAuthenticationManager">
<intercept-url pattern="student/login*" access="ROLE_STUDENT" />
<http-basic />
</http>
<authentication-manager alias="teacherAuthenticationManager">
<authentication-provider>
<!-- <password-encoder hash="md5"/>-->
<jdbc-user-service data-source-ref="dataSources"
users-by-username-query="
select username,password,true
from Teacher where username=?"
authorities-by-username-query="
select username,'ROLE_TEACHER' from Teacher where username=?" />
</authentication-provider>
</authentication-manager>
<authentication-manager alias="studentAuthenticationManager">
<authentication-provider>
<!-- <password-encoder hash="md5"/>-->
<jdbc-user-service data-source-ref="dataSources"
users-by-username-query="
select username,password,true
from Student where username=?"
authorities-by-username-query="
select username,'ROLE_STUDENT' from Student where username=?" />
</authentication-provider>
</authentication-manager>
Web.xml is as follows
<display-name>Spring Web MVC Application</display-name>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
Controller code
#RequestMapping(value = "/teacher/login", method = RequestMethod.GET)
public #ResponseBody MethodResponse teacherlogin( Principal principal) {
System.out.println("Welcome Teacher");
MethodResponse methodResponse = new MethodResponse();
try {
//org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("Is Principal Null:"+Boolean.valueOf(principal==null));
final String name = principal.getName();
String sql="Select * from Teacher where UserName=?";
Teacher teacher = jdbcTemplate.queryForObject(sql,
ParameterizedBeanPropertyRowMapper
.newInstance(Teacher.class),name);
methodResponse.setData(teacher);
//String sql = " Select * from Teacher where TeacherId=?";
/*
List<Teacher> list = jdbcTemplate.query(sql,
ParameterizedBeanPropertyRowMapper
.newInstance(Teacher.class), teacherId);
Teacher[] teachers = list.toArray(new Teacher[] {});
methodResponse.setDataArray(teachers);*/
methodResponse
.setResponseCode(GlobalConstants.SERVICE_STATUS_CODE_SUCCESS);
methodResponse
.setResponseMessage(GlobalConstants.SERVICE_STATUS_MSG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
methodResponse
.setResponseCode(GlobalConstants.SERVICE_STATUS_CODE_DATABASE_ERROR);
methodResponse.setResponseMessage(e.getMessage());
}
return methodResponse;
}
The servlet is mapped to /rest/* and those URLs are not protected by your filters (so I would expect the principal to be null). Does that explain the behaviour you see?
I am getting the following error while trying to pass in values from a properties file to Spring, so that I don't have to supply them directly in hibernate.cfg.xml. Is there a better (and correct) approach? I know that the properties file is being referenced because if I put in in invalid password, it fails on that. I'd be grateful for any help.
WARNING: No connection properties specified - the user must supply JDBC connections
Exception in thread "main" org.hibernate.HibernateException: Hibernate Dialect must be explicitly set
at org.hibernate.dialect.DialectFactory.determineDialect(DialectFactory.java:57)
at org.hibernate.dialect.DialectFactory.buildDialect(DialectFactory.java:39)
at org.hibernate.cfg.SettingsFactory.determineDialect(SettingsFactory.java:426)
This is applicationContext.xml:
<context:component-scan base-package="cmsutil"/>
<context:property-placeholder location="jdbc.properties"/>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configurationClass="org.hibernate.cfg.AnnotationConfiguration"
p:packagesToScan="cmsutil.*">
<property name="exposeTransactionAwareSessionFactory" value="false" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
</props>
</property>
</bean>
<bean id="txnManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
This is my hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="cmsutil.entity/contentcomponent.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Per Ramesh's request - web.xml
<web-app version="3.0" 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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
For Ramesh, this is my jdbc.properties, located in the root directory (/src/java/jdbc.properties)
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://xx:3306/x
jdbc.username=y
jdbc.password=z
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=false
hibernate.generate_statistics=false
add this bean in your applicationContext.xml
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>classpath:jdbc.properties</value></property>
</bean>
update this in web.xml instead of listener
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
I had the same issue but it was the result of an error in my java code. It required calling configure() on the Configuration before calling buildSessionFactory().
The javadoc for configure() method:
Use the mappings and properties specified in an application resource
named hibernate.cfg.xml.
Broken Code:
public static void main(String[] args) {
Configuration cfg = new Configuration();
factory = cfg.buildSessionFactory(); // missing the configure() call
Session s = factory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Solution:
public static void main(String[] args) {
Configuration cfg = new Configuration();
factory = cfg.configure().buildSessionFactory();
Session s = factory.openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
Note: I was not using a Spring config.