I have a simple Library project based on spring MVC framework. I am going to add a new author to my author table but I am getting NullPointerException.
I provided add classes related to this function below. can anybody say what is wrong?
#Controller
public class AuthorController {
#RequestMapping("/addAuthor")
protected ModelAndView addAuthor() throws Exception {
ModelAndView model = new ModelAndView("addAuthor");
return model;
}
#RequestMapping("/addAuthorExecution")
protected ModelAndView addAuthorExecution(
#RequestParam("authorName") String authorName) throws Exception {
ApplicationContext cnx = new ClassPathXmlApplicationContext("spring.xml");
AuthorService authorService = (AuthorService) cnx.getBean("authorService");
authorService.addAuthor(authorName);
ModelAndView model = new ModelAndView("adminFunctionsPage");
model.addObject("successMsg", "Your request has been processed Successfully.");
return model;
}
}
Service Class:
public class AuthorService {
#Autowired
Author author;
#Autowired
AuthorDAO authorDAO;
public void addAuthor(String authorName) throws ClassNotFoundException,
SQLException {
AuthorDAO authorDAO = new AuthorDAO();
authorDAO.addAuthor(authorName);
}
}
DAO class:
public class AuthorDAO extends JdbcDaoSupport {
public void addAuthor(String authorName) {
String sql = "insert into tbl_author (authorName) values (?)";
this.getJdbcTemplate().update(sql, new Object[] { authorName });
}
private static final class AuthorMapper implements RowMapper<Author> {
#Autowired
Author author;
#Override
public Author mapRow(ResultSet rs, int rowNum) throws SQLException {
author.setAuthorId(rs.getInt("authorId"));
author.setAuthorName(rs.getString("authorName"));
return author;
}
}
}
Model Class:
public class Author {
int authorId;
String authorName;
public int getAuthorId() {
return authorId;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.hojat.LibSpringMVCProject.DAO" />
<context:component-scan base-package="com.hojat.LibSpringMVCProject.Service" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/library"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<bean id="author" class="com.hojat.LibSpringMVCProject.model.Author"/>
<bean id="authorDAO" class="com.hojat.LibSpringMVCProject.DAO.AuthorDAO" >
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="authorService" class="com.hojat.LibSpringMVCProject.service.AuthorService"/>
Error:
'INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Feb 24, 2015 1:16:11 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring-dispatcher] in context with path [/LibrarySpringMVCProject] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.hojat.LibSpringMVCProject.DAO.AuthorDAO.addAuthor(AuthorDAO.java:32)
at com.hojat.LibSpringMVCProject.service.AuthorService.addAuthor(AuthorService.java:40)
at com.hojat.LibSpringMVCProject.controller.AuthorController.addAuthorExecution(AuthorController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:146)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:277)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)'
Hello could you try
<property name="url" value="jdbc:mysql://localhost:3306/library"/>
instead of
<property name="url" value="jdbc:mysql://localhost/library"/>
It will be problem.
Several mistakes
You are autowiring the POJO entity class Auther. This is wrong.
Hope you have #Service annotation on the AuthorService
You are creating an object of the the AuthorDAO inside the addAuthor method. You should note the AutherDAO should not be manually constructed as there are autowired object available inside that class AutherDAO.AuthorMapper. By manually constructing them these auto wiring will not get wired to objects.
If I completely rewrite your service class, it would be something like this.
#Service
public class AuthorService {
#Autowired
AuthorDAO authorDAO;
public void addAuthor(String authorName) throws Exception {
authorDAO.addAuthor(authorName);
}
}
Related
AdminService.java
package service;
import java.awt.Window.Type;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import dao.IMemberDAO;
import model.Member;
#Service
public class MemberService
{
#Autowired
private IMemberDAO memberDao;
// 로그인
public HashMap<String, Object> login(String id,String pw)
{
HashMap<String, Object> result = memberDao.selectOne(id);
if(result != null) // 존재하는 값이 있으면
{
String opwd = (String) result.get("pw"); // opwd = 존재하는값의 pw값을 가져온 값
if(opwd.equals(pw))
{
return result; // true면 존재하는값을 반환
}
else
{
return null;
//return null; // 아니면 값을 반환하지 않음.
}
}
else // 존재하는 값이 없다면
{
return null;
}
}
// 아이디 체크
public boolean idCheck(String loginPerson)
{
HashMap<String, Object> user = memberDao.selectOne(loginPerson);
if(user != null)
{
return false;
}
else
{
return true;
}
}
// 멤버 추가
public boolean insertMember(Member member)
{
if(idCheck(member.getId()))
{
memberDao.insertMember(member);
return true;
}
else
{
return false;
}
}
public HashMap<String, Object> getMemberInfo(String id)
{
return memberDao.selectOne(id);
}
// 회원 수정
public void memberUpdate(HashMap<String, Object> params)
{
System.out.println("params is : " + params);
memberDao.updateMember(params);
}
// 회원삭제
public boolean memberDelete(String id,String pw)
{
HashMap<String, Object> user = memberDao.selectOne(id);
String pw2 = (String) user.get("pw");
System.out.println("id and pw is : " + id + "/" + pw);
System.out.println("pw2 is : " + pw2);
if(pw2.equals(pw))
{
memberDao.deleteMember(id);
System.out.println("return true");
return true;
}
else
{
System.out.println("return false");
return false;
}
}
}
AdminController.java
package controller;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import service.AdminService;
import service.MemberService;
#Controller
public class AdminController
{
#Autowired
public AdminService aService;
// 관리자 로그인 폼 페이지
#RequestMapping("admin.do")
public String adminLoginPage()
{
return "adminLoginPage";
}
// 관리자 로그인했을 시 요청
#RequestMapping("adminLoginOK.do")
#ResponseBody
public String adminMainPage(#RequestParam(required=false) String id, #RequestParam(required=false)String pw,HttpSession session,HttpServletRequest req,HttpServletResponse resp)
{
HashMap<String, Object> adminLoginIdentify = aService.adminLogin(id, pw);
//if(session.getAttribute("id") == null){System.out.println("zzz kkk");}
//String admin_id = (String) session.getAttribute("id");
if(adminLoginIdentify != null)
{
return "1";
}
else
{
return "0";
}
}
#RequestMapping("adminPage.do")
public String adminPage(
#RequestParam(required = false) String keyword,
#RequestParam(defaultValue="0") int type,
HttpSession session,HttpServletRequest resquest,HttpServletResponse response) throws IOException
{
ModelAndView mav = new ModelAndView();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("type", type);
params.put("keyword", keyword);
System.out.println(params);
return "adminMainPage";
}
}
adminDaoMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.IAdminDAO">
<select id="selectOne" parameterType="Strig" resultType="java.util.HashMap">
select * from member where id = #{id}
</select>
<select id="selectMemberAll" resultType="java.util.HashMap">
select * from member
</select>
</mapper>
AdminDao.java
package dao;
import java.util.HashMap;
public interface IAdminDAO
{
public HashMap<String, Object> selectOne(String id);
}
The code before modifying the applicationContext file is shown below.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath*:dao/mapper/*.xml"></property>
</bean>
<bean id="memberDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
<property name="mapperInterface" value="dao.IMemberDAO"></property>
</bean>
</beans>
This is the appliCation code after the modification.
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<context:component-scan base-package="service" />
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property value="com.mysql.jdbc.Driver" name="driverClassName"></property>
<property value="jdbc:mysql://localhost/rachelvf" name="url"></property>
<property value="root" name="username"/>
<property value="mysql" name="password"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:dao/mapper/*.xml"></property>
<property name="typeAliasesPackage" value="model"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>
The project worked well before the applicationContext file was modified,
but after the code has been modified, an error occurs.
error code is that.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private dao.IAdminDAO service.AdminService.adminDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [dao.IAdminDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
I thought about the cause of the error,
but I think it is because I did not insert the service annotation.
However, there is no typos in any way, and everything is written correctly and errors occur. Is there something I don't know?
Can you tell me what caused this error?
And what about the solution?
Please help me..
Try to change this code of yours:
#Autowired
public AdminService aService;
to this:
#Autowired
public AdminService adminService;
because when you Autowire, he can't see aService on your context that's why he can't create instance of adminService as a default name of your Service bean.
EDIT:
Another thing is you have to implement your interfaces to a concrete class in order to instantiate beans, you can't instantiate interfaces remember, so you need concrete beans to implement what is on your interfaces. Like this:
#Repository
public class IAdminDAOImpl implements IAdminDAO {
//Implementation here
}
#Service
public class AdminServiceImpl implements AdminService {
//Implementation here
}
I am getting a NullPointerException when I try to execute the checkCredentials function in my LoginController. I think the problem is not with my Service Implementation but with DAO Implementation. But I am not able to find what causes the issue. I am not sure if the problem is with the
#Autowired
private LoginDAO loginDAO;
or the
#Repository("loginDAO")
When I submit the login credentials I get the following
DEBUG - Returning handler method [public java.lang.String com.accademics.web.controllers.LoginController.checkCredentials(com.accademics.web.models.LoginModel,org.springframework.validation.BindingResult)]
DEBUG - Returning cached instance of singleton bean 'loginController'
inside controller checkCredentials
LoginModel [username=admin, password=password]
service checking login of admin and password
DEBUG - Resolving exception from handler [public java.lang.String com.accademics.web.controllers.LoginController.checkCredentials(com.accademics.web.models.LoginModel,org.springframework.validation.BindingResult)]: java.lang.NullPointerException
DEBUG - Resolving exception from handler [public java.lang.String com.accademics.web.controllers.LoginController.checkCredentials(com.accademics.web.models.LoginModel,org.springframework.validation.BindingResult)]: java.lang.NullPointerException
DEBUG - Resolving exception from handler [public java.lang.String com.accademics.web.controllers.LoginController.checkCredentials(com.accademics.web.models.LoginModel,org.springframework.validation.BindingResult)]: java.lang.NullPointerException
DEBUG - Could not complete request
java.lang.NullPointerException
at com.accademics.data.services.LoginServiceImpl.checkCredentials(LoginServiceImpl.java:18)
at com.accademics.web.controllers.LoginController.checkCredentials(LoginController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
So here is the root, applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="loginService" class="com.accademics.data.services.LoginServiceImpl"/>
</beans>
The dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.accademics.web.controllers"></context:component-scan>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"></property>
</bean>
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>
student_login.jsp actual content part
<form action='<spring:url value="/student/login"></spring:url>' method="post" autocomplete="on">
<h1>Log in</h1>
<p>
<label for></label>
</p>
<p>
<label for="username" class="uname" > Username </label>
<input id="username" name="username" required="required" type="text" placeholder="Username"/>
</p>
<p>
<label for="password" class="passwd"> Password </label>
<input id="password" name="password" required="required" type="password" placeholder="Password" />
</p>
<p class="keeplogin">
<input type="checkbox" name="saveLogin" id="saveLogin" value="saveLogin" />
<label for="saveLogin">Keep me logged in</label>
</p>
<p class="login button">
<input type="submit" value="Login" />
</p>
</form>
LoginController.java
package com.accademics.web.controllers;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.accademics.data.services.LoginService;
import com.accademics.web.models.LoginModel;
#Controller
#RequestMapping("/student")
public class LoginController {
#Autowired
public LoginService loginService;
#Autowired
MessageSource messagesource;
#RequestMapping(value="/login", method=RequestMethod.GET)
public String displayLogin(Model model){
return "student_login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String checkCredentials(#Valid #ModelAttribute LoginModel loginModel, BindingResult result){
System.out.println("inside controller checkCredentials");
if(result.hasErrors()){
return "student_login";
}
System.out.println(loginModel);
boolean userExists = loginService.checkCredentials(loginModel.getUsername(), loginModel.getPassword());
if(userExists){
System.out.println("valid");
return "dashboard";
}else{
System.out.println("invalid");
result.rejectValue("userName", "NotNull.login.invalidUser");
return "student_login";
}
}
}
LoginServiceImpl.java
package com.accademics.data.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.accademics.web.DAO.LoginDAO;
#Service("loginService")
public class LoginServiceImpl implements LoginService {
#Autowired
private LoginDAO loginDAO;
#Override
public boolean checkCredentials(String username, String password) {
// TODO Auto-generated method stub
System.out.println("service checking login of "+username+" and "+password);
return loginDAO.checkCredentials(username, password);
}
}
LoginDAO.java
package com.accademics.web.DAO;
public interface LoginDAO {
public boolean checkCredentials(String username, String password);
}
LoginDAOImpl.java
package com.accademics.web.DAO;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
#Repository("loginDAO")
public class LoginDAOImpl implements LoginDAO {
#Autowired
private SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
#Override
public boolean checkCredentials(String username, String password) {
System.out.println("Checking login");
//HQL
String hquery = "from student_credentials where student_credentials.username=? and student_credentials.password=?";
boolean userFound = false;
Session session = getSession();
Query query = session.createSQLQuery(hquery);
query.setParameter(0, username);
query.setParameter(1, password);
List list = query.list();
if(!list.isEmpty()){
userFound = true;
}
session.close();
return userFound;
}
}
and relevant entry in messages.properties
NotNull.login.invalidUser = Invalid Username/Password
Please help me to resolve this issue.
I have made the following changes to my dispatcher-servlet and removed the bean tag from applicationContext.xml,
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.accademics.web" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"></property>
</bean>
<mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
which created this new exception.
ERROR - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'loginService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginService': Unsatisfied dependency expressed through field 'loginDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.accademics.web.configuration.HibernateConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:668)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:682)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:553)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:494)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:138)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1183)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099)
at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:779)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:133)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1410)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginService': Unsatisfied dependency expressed through field 'loginDAO'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.accademics.web.configuration.HibernateConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 39 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginDAO': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.accademics.web.configuration.HibernateConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 52 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in com.accademics.web.configuration.HibernateConfiguration: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
... 65 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
at org.hibernate.cfg.Configuration.createReflectionManager(Configuration.java:2547)
at org.hibernate.cfg.Configuration.createReflectionManager(Configuration.java:2543)
at org.hibernate.cfg.Configuration.reset(Configuration.java:298)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:289)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:293)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.<init>(LocalSessionFactoryBuilder.java:140)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:343)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
... 75 more
I really dont understand what is wrong with my code.
I now have the solution, which is decribed in the below answer. The second problem was actually related to dependencies.
I found the solution to the second issue (first which was solved Thanks to #JBNizet)
It was actually regarding the dependencies added in the pom.xml, which I havnt included here. What I did is I actually upgraded my hibernate version to 5.1.0 and then added hibernate-commons-annotations 5.0.1.Final. So my dependencies are now like below.
The specific, Hibernate core will have hibernate-common-annotation and this has the missing class
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.annotations.common.reflection.java.JavaReflectionManager
Am getting an error saying :
exception
javax.servlet.ServletException: Servlet.init() for servlet spring threw exception
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.labs.dao.LoginDao com.labs.controllers.LoginController.loginDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginDao' defined in file [C:\Program Files\Apache Software Foundation\Tomcat 7.0\wtpwebapps\Annotated\WEB-INF\classes\com\labs\dao\LoginDao.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.labs.dao.LoginDao]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Property 'dataSource' is required
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
And here is my controller
#Controller
public class LoginController {
#Autowired
private LoginDao loginDao;
#RequestMapping(value="/login", method=RequestMethod.POST)
public ModelAndView login(#ModelAttribute User user){
if(loginDao.login(user))
return new ModelAndView("success", "user", user);
return new ModelAndView("failure");
}
public void setLoginDao(LoginDao loginDao) {
this.loginDao = loginDao;
}
public LoginDao getLoginDao() {
return loginDao;
}
}
And MyDao
#Repository
public class LoginDao {
#Autowired
private DataSource dataSource;
private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
public boolean login(User user){
String name = jdbcTemplate.queryForObject("select name from users where name=? and password=?",new Object[]{user.getUserName(),user.getPassword()},String.class);
if(!name.isEmpty())
return true;
return false;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getDataSource() {
return dataSource;
}
}
spring configuration is
<context:annotation-config/>
<context:component-scan base-package="com.labs"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" autowire="byName">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
<property name="username" value="postgres"/>
<property name="password" value="Raju"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="viewClass" value=""></property> -->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"></property>
</bean>
This line is the problem
private JdbcTemplate jdbcTemplate = new JdbcTemplate(getDataSource());
Instance variables are initialized before the constructor is called and before Spring has time to autowire any fields. In other words, dataSource is null and getDataSource() therefore returns null. JdbcTemplate throws an Exception if the DataSource argument is null.
Instead change your code to
private DataSource dataSource;
private JdbcTemplate jdbcTemplate;
#Autowired
public LoginDao(DataSource dataSource) {
this.dataSource = dataSource;
this.jdbcTemplate = new JdbcTemplate(this.dataSource);
}
I coded an interceptor as follows:
package org.mybatis.jpetstore.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mybatis.jpetstore.annotation.CsrfTokenCheck;
import org.mybatis.jpetstore.tool.CsrfTokenTool;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
public class CsrfTokenAnnotationInterceptor extends HandlerInterceptorAdapter {
#Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
}
#Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object ojbect) throws Exception {
System.out.println("======================");
//if(ojbect instanceof HandlerMethod){
CsrfTokenCheck csrfTokenCheck = ((HandlerMethod) ojbect).getMethodAnnotation(CsrfTokenCheck.class);
System.out.println("++++++++++++++++++++++");
if(csrfTokenCheck != null && !new CsrfTokenTool().verify((HttpServletRequest) request)){
response.sendRedirect("http://www.google.com");
return false;
}
//}
return true;
}
}
but it seems not work at all.(the codes depend on spring3.2)
annotation in controller:
#CsrfTokenCheck
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("category/category");
return mav;
}
interface:
package org.mybatis.jpetstore.annotation;
public #interface CsrfTokenCheck{
}
I also configued something as follows in my spring-config.xml:
<bean id="requestMappingHandlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="interceptors">
<list>
<ref bean="csrfTokenAnnotationInterceptor" />
</list>
</property>
</bean>
<bean id="csrfTokenAnnotationInterceptor" class="org.mybatis.jpetstore.interceptor.CsrfTokenAnnotationInterceptor" />
Start by fixing your annotation. It should contain at least a #Retention meta-annotation and make it available at runtime, currently it isn't and as such will also fail.
#Target({ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
public #interface CsrfTokenCheck{}
Next to that make sure you don't have an <mvc:annotation-driven /> in your configuration as that will render your explicitly configured RequestMappingHandlerMapping useless. If you are using <mvc:annotation-driven /> you should use the <mvc:interceptors /> tag to register interceptors.
Check these files:
resources/spring/spring.xml
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
...
<property name="configLocation" value="classpath:/mybatis/mybatis-config.xml"/>
</bean>
resources/mybatis/mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
...
<plugins>
<!-- Interceptor configuration -->
<plugin interceptor="com.w.pay.api.test.mvn.res.db.MybatisLogPrinter" />
</plugins>
</configuration>
Please search for interceptors in all XML files in your workspace.
I solved this by realizing that the servlet-context file already exists where the annotation driven and other interceptors are defined. After placing my interceptor definition in that file it worked like a charm.
I spent quite 1.5 day scratching my head, it turns out that spring does not like multiple locations for interceptors.
When i tried to connect my Cloud SQL via JPA the following error is generated :
2012-10-25 10:07:38.439
Error for /jpatest
java.lang.NoClassDefFoundError: Could not initialize class com.my.jpa.EMF
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:14)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
2012-10-25 10:07:38.440
Uncaught exception from servlet
java.lang.NoClassDefFoundError: Could not initialize class com.my.jpa.EMF
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:14)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
My EMF Class is
public final class EMF {
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("JPATest");
private EMF() {
}
public static EntityManagerFactory get() {
return emfInstance;
}
}
EMF initialising portion is
public class ContactService {
private static Logger logger = Logger.getLogger(ContactService.class
.getName());
public void createContact(Contact c) {
logger.info("Entering createContact: [" + c.getFirstName() + ","
+ c.getLastName() + "]");
EntityManager mgr = EMF.get().createEntityManager();
try {
mgr.getTransaction().begin();
mgr.persist(c);
mgr.getTransaction().commit();
} finally {
mgr.close();
}
logger.info("Exiting createContact");
}
}
My Servlet is :
public class JPATestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ContactService service = new ContactService();
service.createContact(new Contact("Manu", "Mohan", "686019", "TVM"));
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
web.xml is
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>JPATest</servlet-name>
<servlet-class>com.my.jpa.JPATestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JPATest</servlet-name>
<url-pattern>/jpatest</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPATest">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.my.jpa.Contact</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.google.cloud.sql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://instance-name/stock" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
<!-- EclipseLink should create the database schema automatically -->
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode"
value="database" />
</properties>
</persistence-unit>
</persistence
Do you need to use final for EntityManagerFactory in EMF. Try to use Singleton Design Pattern for EMF. EntityManagerFactory class is thread-safe.
EMF.java
public final class EMF {
private EntityManagerFactory emfInstance;
private static EMF emf;
private EMF() {
}
public EntityManagerFactory get() {
if(emfInstance == null) {
emfInstance = Persistence.createEntityManagerFactory("JPATest");
}
return emfInstance;
}
public static EMF getInstance() {
if(emf == null) {
emf = new EMF();
}
return emf;
}
}
// usages
EntityManagerFactory emf = Emf.getInstance().get();
Here better way to use EntityManagerFactory in web applicaiton.