http status 500 spring webservice hibernate - java

I'm getting an status http 500, it says the server encountered an internal error that prevented it from fulfilling this request. But the apache log shows no errors at all.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="org.postgresql.Driver"/>
<beans:property name="url" value="jdbc:postgresql://localhost:5432/tms"/>
<beans:property name="username" value="postgres"/>
<beans:property name="password" value="paswoord"/>
</beans:bean>
<beans:bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="configLocation">
<beans:value>classpath:hibernate.cfg.xml</beans:value>
</beans:property>
<beans:property name="configurationClass">
<beans:value>org.hibernate.cfg.AnnotationConfiguration</beans:value>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">${jdbc.dialect}</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven />
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
<context:component-scan base-package="be.pxl.publictms" />
</beans:beans>
testController the getUsers method works partly i can print the results but it won't return it as an populated list.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import be.pxl.publictms.model.Computer;
import be.pxl.publictms.pojo.Gebruiker;
import be.pxl.publictms.service.GebruikerService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
#Controller
#RequestMapping("test")
public class TestController {
#Autowired
private GebruikerService gebruikerService;
#RequestMapping(value = "pc",method = RequestMethod.GET)
public #ResponseBody Computer testMethod() {
return new Computer(0, "DELL");
}
#RequestMapping(value = "users",method = RequestMethod.GET)
public #ResponseBody List<Gebruiker> getUsers(){
List<Gebruiker> users = gebruikerService.getGebruikers();
System.out.println("***********************************************");
for(Gebruiker user: users){
System.out.println(user.toString());
}
System.out.println("***********************************************");
/*List<Gebruiker> users = new ArrayList<Gebruiker>();
users.add(new Gebruiker(1, "laurens", "test"));
users.add(new Gebruiker(2, "laurens", "test"));
users.add(new Gebruiker(3, "laurens", "test"));*/
return users;
}
}
GebruikerService:
import be.pxl.publictms.DAO.GebruikerDAO;
import be.pxl.publictms.pojo.Gebruiker;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
*
* #author 11302785
*/
#Service
public class GebruikerServiceImpl implements GebruikerService{
#Autowired
private GebruikerDAO gebruikerDao;
#Transactional
public void addGebruiker(Gebruiker gebruiker) {
gebruikerDao.addGebruiker(gebruiker);
}
#Transactional
public List<Gebruiker> getGebruikers() {
return gebruikerDao.getGebruikers();
}
#Transactional
public void deleteGebruiker(int id) {
gebruikerDao.deleteGebruiker(id);
}
#Transactional
public void updateGebruiker(Gebruiker gebruiker) {
gebruikerDao.updateGebruiker(gebruiker);
}
}
gebruikerDAO:
import be.pxl.publictms.pojo.Gebruiker;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
*
* #author 11302785
*/
#Repository
public class GebruikerDAOImpl implements GebruikerDAO{
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addGebruiker(Gebruiker gebruiker) {
sessionFactory.getCurrentSession().save(gebruiker);
}
#Override
public List<Gebruiker> getGebruikers() {
return sessionFactory.getCurrentSession().createQuery("from Gebruiker").list();
}
#Override
public void deleteGebruiker(int id) {
Gebruiker gebruiker = (Gebruiker)sessionFactory.getCurrentSession().load(Gebruiker.class, id);
if(null != gebruiker){
sessionFactory.getCurrentSession().delete(gebruiker);
}
}
#Override
public void updateGebruiker(Gebruiker gebruiker) {
sessionFactory.getCurrentSession().update(gebruiker);
}
}
pojo class gebruiker (it's dutch, it meaning is User... sorry for the dutch parts in it):
import java.util.HashSet;
import java.util.Set;
/**
* Gebruiker generated by hbm2java
*/
public class Gebruiker implements java.io.Serializable {
private int gebruikerid;
private Werknemer werknemer;
private String gebruikersnaam;
private String paswoord;
private Set<Bericht> berichtsForGebruikerid = new HashSet<Bericht>(0);
private Set<Bericht> berichtsForOntvangerid = new HashSet<Bericht>(0);
public Gebruiker() {
}
public Gebruiker(int gebruikerid, String gebruikersnaam, String paswoord) {
this.gebruikerid = gebruikerid;
this.gebruikersnaam = gebruikersnaam;
this.paswoord = paswoord;
}
public Gebruiker(int gebruikerid, Werknemer werknemer, String gebruikersnaam, String paswoord, Set<Bericht> berichtsForGebruikerid, Set<Bericht> berichtsForOntvangerid) {
this.gebruikerid = gebruikerid;
this.werknemer = werknemer;
this.gebruikersnaam = gebruikersnaam;
this.paswoord = paswoord;
this.berichtsForGebruikerid = berichtsForGebruikerid;
this.berichtsForOntvangerid = berichtsForOntvangerid;
}
public int getGebruikerid() {
return this.gebruikerid;
}
public void setGebruikerid(int gebruikerid) {
this.gebruikerid = gebruikerid;
}
public Werknemer getWerknemer() {
return this.werknemer;
}
public void setWerknemer(Werknemer werknemer) {
this.werknemer = werknemer;
}
public String getGebruikersnaam() {
return this.gebruikersnaam;
}
public void setGebruikersnaam(String gebruikersnaam) {
this.gebruikersnaam = gebruikersnaam;
}
public String getPaswoord() {
return this.paswoord;
}
public void setPaswoord(String paswoord) {
this.paswoord = paswoord;
}
public Set<Bericht> getBerichtsForGebruikerid() {
return this.berichtsForGebruikerid;
}
public void setBerichtsForGebruikerid(Set<Bericht> berichtsForGebruikerid) {
this.berichtsForGebruikerid = berichtsForGebruikerid;
}
public Set<Bericht> getBerichtsForOntvangerid() {
return this.berichtsForOntvangerid;
}
public void setBerichtsForOntvangerid(Set<Bericht> berichtsForOntvangerid) {
this.berichtsForOntvangerid = berichtsForOntvangerid;
}
#Override
public String toString(){
return this.gebruikersnaam + " " + this.paswoord;
}
}

Related

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' [duplicate]

This question already has answers here:
Why does Spring MVC respond with a 404 and report "No mapping found for HTTP request with URI [...] in DispatcherServlet"?
(13 answers)
Closed 6 years ago.
I am trying to Making a simple BBS but I'm encountering following this error,
WARN : org.springframework.web.servlet.PageNotFound - No mapping found
for HTTP request with URI [/board/] in DispatcherServlet with name
'appServlet'
I have tried to solve this error many times, but I have failed. How can I solve this error?
here is my web.xml, Controllerand and servlet-context.
my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>EUC-KR</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</context-param>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
my Controller
package com.onj.board;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.board.model.BoardDTO;
import com.board.model.CommentDTO;
import com.board.service.BoardService;
import com.board.util.EncodingHandler;
import com.board.util.PageHandler;
public class BoardMultiController extends MultiActionController {
private BoardService boardService;
private PageHandler pageHandler;
public void setBoardService(BoardService boardService) {
this.boardService = boardService;
}
public void setPageHandler(PageHandler pageHandler) {
this.pageHandler = pageHandler;
}
ModelAndView mav = null;
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {
mav = new ModelAndView();
HttpSession session = request.getSession();
if (session.isNew() == false) {
session.invalidate();
}
List<BoardDTO> list = null;
String boardListSelect = request.getParameter("boardListSelect");
String boardListSearchText = request
.getParameter("boardListSearchText");
Map<String, Object> searchMap = new HashMap<String, Object>();
if (boardListSearchText != null) {
searchMap.put("boardListSearchText",
EncodingHandler.toKor(boardListSearchText));
searchMap.put("boardListSelect", boardListSelect);
mav.addObject("boardListSearchText",
EncodingHandler.toKor(boardListSearchText));
mav.addObject("boardListSelect", boardListSelect);
}
String pageNumber = request.getParameter("pageNumber");
int pageNum = 1;
if (pageNumber != null) {
pageNum = Integer.parseInt(pageNumber);
}
int totalCount = pageHandler.boardAllNumber(searchMap);
int totalPageCount = pageHandler.boardPageCount(searchMap);
int startPage = pageHandler.boardStartPage(pageNum);
int endPage = pageHandler.boardEndPage(pageNum, searchMap);
List<Object> rowNumberList = new ArrayList<Object>();
rowNumberList = pageHandler.boardSetPageNumber(pageNum);
searchMap.put("startRow", rowNumberList.get(0));
searchMap.put("endRow", rowNumberList.get(1));
list = boardService.boardList(searchMap);
mav.addObject("pageNumber", pageNum);
mav.addObject("boardCount", totalCount);
mav.addObject("totalPageCount", totalPageCount);
mav.addObject("startPage", startPage);
mav.addObject("endPage", endPage);
mav.addObject("list", list);
mav.setViewName("list");
return mav;
}
public ModelAndView read(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String seq = request.getParameter("seq");
BoardDTO boardDTO = boardService.readContent(seq);
HttpSession session = request.getSession();
session.setAttribute("boardDTO", boardDTO);
mav.addObject("boardDto", boardDTO);
mav.addObject("comment", boardService.ListComment(seq));
mav.setViewName("read");
return mav;
}
public ModelAndView comment(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
BoardDTO boardDTO = (BoardDTO) session.getAttribute("boardDTO");
mav = new ModelAndView("redirect:/read.html?seq=" + boardDTO.getSeq());
CommentDTO commentDTO = new CommentDTO();
commentDTO.setComment_name(request.getParameter("comment_name"));
commentDTO.setComment_comm(request.getParameter("comment_comm"));
commentDTO.setSeq(boardDTO.getSeq());
boardService.insertComment(commentDTO);
return mav;
}
public ModelAndView write(HttpServletRequest request,
HttpServletResponse response) throws Exception {
mav = new ModelAndView("write");
return mav;
}
public ModelAndView writeOk(HttpServletRequest request,
HttpServletResponse response) throws Exception {
mav = new ModelAndView("redirect:/list.html");
MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
String name = request.getParameter("name");
String passwd = request.getParameter("passwd");
String title = request.getParameter("title");
String content = request.getParameter("content");
MultipartFile file = mpRequest.getFile("file");
String fileName = file.getOriginalFilename();
BoardDTO boardDTO = new BoardDTO();
String fileDir = "D:/upload/";
byte[] fileData;
FileOutputStream output = null;
if (!fileName.equals("")) {
// 파일 저장
try {
fileData = file.getBytes();
output = new FileOutputStream(fileDir + fileName);
output.write(fileData);
} catch (IOException e) {
e.printStackTrace();
} finally {
output.close();
}
} else {
fileName = " ";
}
boardDTO.setName(name);
boardDTO.setPasswd(passwd);
boardDTO.setTitle(title);
boardDTO.setContent(content);
boardDTO.setFilename(fileName);
boardService.insertBoard(boardDTO);
return mav;
}
public ModelAndView updatePageGo(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
BoardDTO boardDTO = (BoardDTO) session.getAttribute("boardDTO");
mav = new ModelAndView("update", "boardDto", boardDTO);
return mav;
}
public ModelAndView update(HttpServletRequest request,
HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
BoardDTO boardDTO = (BoardDTO) session.getAttribute("boardDTO");
String name = request.getParameter("name");
String title = request.getParameter("title");
String content = request.getParameter("content");
String seq = boardDTO.getSeq();
boardDTO.setName(name);
boardDTO.setTitle(title);
boardDTO.setContent(content);
boardDTO.setSeq(seq);
boardService.updateBoard(boardDTO);
mav = new ModelAndView("redirect:/read.html?seq=" + seq);
return mav;
}
public ModelAndView delete(HttpServletRequest request,
HttpServletResponse response) throws Exception {
mav = new ModelAndView();
HttpSession session = request.getSession();
BoardDTO boardDTO = (BoardDTO) session.getAttribute("boardDTO");
String boardPassword = boardDTO.getPasswd();
String passwd = request.getParameter("passwd");
String mas = "";
if (boardPassword.equals(passwd)) {
boardService.deleteBoard(boardDTO.getSeq());
mav.setViewName("redirect:/list.html");
} else {
mas = "비밀번호가 일치하지 않습니다.";
mav.addObject("mas", mas);
mav.setViewName("redirect:/read.html?seq=" + boardDTO.getSeq());
}
return mav;
}
}
my servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- <context:component-scan base-package="com.onj.board" /> -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<beans:property name="url"
value="jdbc:oracle:thin:#localhost:1521:ex" />
<beans:property name="username" value="study" />
<beans:property name="password" value="study" />
</beans:bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/jsp/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- 넘어오는 URL에 따라 컨트롤러에서 실행될 메소드 매핑 -->
<!-- PropertiesMethodNameResolver는 prop key로 넘어오는 url에 대해 실행할 컨트롤러의 메소드
정의 -->
<beans:bean id="userControllerMethodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<beans:property name="mappings">
<beans:props>
<beans:prop key="/list.html">list</beans:prop>
<beans:prop key="/read.html">read</beans:prop>
<beans:prop key="/comment.html">comment</beans:prop>
<beans:prop key="/write.html">write</beans:prop>
<beans:prop key="/writeOk.html">writeOk</beans:prop>
<beans:prop key="/updatePage.html">updatePageGo</beans:prop>
<beans:prop key="/update.html">update</beans:prop>
<beans:prop key="/delete.html">delete</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<!-- controller mapping -->
<beans:bean
name="/list.html /read.html /comment.html /write.html /writeOk.html /updatePage.html /update.html /delete.html"
class="com.onj.board.BoardMultiController">
<beans:property name="methodNameResolver" ref="userControllerMethodNameResolver" />
<beans:property name="boardService" ref="boardService" />
<beans:property name="pageHandler" ref="pageHandler" />
</beans:bean>
</beans:beans>
I need your advice.
Thanks
Try changing the <url-pattern> in your web.xml file to:
<url-pattern>/*</url-pattern>
How are you deploying this application? As board.war?
Also, just to let you know, this is a very ancient way of configuring a Spring MVC application. Spring has some guides available demonstrating the modern approach.
The following items seems to be missing from the code:
1. In servlet-context.xml, add
<context:component-scan base-package="com.onj" />
<mvc:annotation-driven />
Replace
<beans:beans .....> with
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
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.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
2. Add #Controller annotation and #RequestMappings for methods inside it as no controller configuration found in the servlet-context.xml.
#Controller
public class BoardMultiController extends MultiActionController {
Request mapping to list() method:
#RequestMapping(value="/board", method = RequestMethod.GET)
public ModelAndView list(HttpServletRequest request,
HttpServletResponse response) throws Exception {

org.springframework.beans.factory.BeanCreationException and org.springframework.beans.factory.NoUniqueBeanDefinitionException

I have developed server program using spring mvc and hibernate but I'm getting an error at runtime
This is servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
xmlns:tx="http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="kr.ac.jbnu.jinggumdari" />
<context:annotation-config />
<beans:bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/jinggumdari" />
<beans:property name="username" value="root" />
<beans:property name="password" value="mysql1234" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>kr.ac.jbnu.jinggumdari.model.Member</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="memberDAO" class="kr.ac.jbnu.jinggumdari.DAO.MemberDAOImpl">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="memberService"
class="kr.ac.jbnu.jinggumdari.serviceImplementation.MemberManageServiceImpl">
<beans:property name="memberDAO" ref="memberDAO"></beans:property>
</beans:bean>
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory"
ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
</beans:beans>
and It is error message
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jinggumdariController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private kr.ac.jbnu.jinggumdari.service.MemberManageService kr.ac.jbnu.jinggumdari.controller.JinggumdariController.MemberManager; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [kr.ac.jbnu.jinggumdari.service.MemberManageService] is defined: expected single matching bean but found 2: memberManageServiceImpl,memberService
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:158)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5262)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5550)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
and my code:
package kr.ac.jbnu.jinggumdari.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.jbnu.jinggumdari.model.Member;
import kr.ac.jbnu.jinggumdari.service.MemberManageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Handles requests for the application home page.
*/
#Controller
public class JinggumdariController {
private static final Logger logger = LoggerFactory.getLogger(JinggumdariController.class);
#Autowired
private MemberManageService MemberManager;
private boolean isSuccess;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
#RequestMapping(value = "/member/signIn", method = RequestMethod.GET)
public #ResponseBody boolean signIn(#RequestParam("email") String email,
#RequestParam("password") String password,
HttpServletRequest request, HttpServletResponse response) {
isSuccess = false;
Member member = new Member(email, password);
isSuccess = MemberManager.addMember(member);
return isSuccess;
}
#RequestMapping(value = "/member/getInfo", method = RequestMethod.GET)
public #ResponseBody Member getMember(#RequestParam("email") String email) {
Member member = MemberManager.getMember(email);
return member;
}
//출력 예시 코드
#RequestMapping(value = "/test", method = RequestMethod.POST)
public #ResponseBody String test2() {
return "이젠 이걸 쓸거임";
}
}
package kr.ac.jbnu.jinggumdari.service;
import kr.ac.jbnu.jinggumdari.model.Member;
public interface MemberManageService {
public boolean addMember(Member member);
public boolean modifyMember(Member member);
public boolean removeMember(String email);
public Member getMember(String email);
}
package kr.ac.jbnu.jinggumdari.serviceImplementation;
import kr.ac.jbnu.jinggumdari.DAO.MemberDAO;
import kr.ac.jbnu.jinggumdari.model.Member;
import kr.ac.jbnu.jinggumdari.service.MemberManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class MemberManageServiceImpl implements MemberManageService{
private MemberDAO memberDAO;
public void setMemberDAO(MemberDAO memberDAO) {
this.memberDAO = memberDAO;
}
#Override
#Transactional
public boolean addMember(Member member) {
return memberDAO.addMember(member);
}
#Override
#Transactional
public boolean modifyMember(Member member) {
return memberDAO.modifyMember(member);
}
#Override
#Transactional
public boolean removeMember(String email) {
return removeMember(email);
}
#Override
#Transactional
public Member getMember(String email) {
return memberDAO.getMember(email);
}
}
The exception is pretty clear, expected single matching bean but found 2: memberManageServiceImpl,memberService
You are creating bean in your xml (having id: memberService) and also using annotation #Service (having id: memberManageServiceImpl). You need to decide which one you want and remove other.

Spring security using http authentication based on xml

I am trying to implement a spring security in my project my requirements are
First user will login with url that will generate a secuirty code -
http://localhost:8181/SpringSecurity/login
After successfully loggedIn I hit secuired API call like -
http://localhost:8181/SpringSecurity/admin with secured key generated by login method
I am using crome postman to hit APIs
Although I am loggedIn with a user having ROLE_ADMIN but still it is not allow me to access secured APIs
my web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/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>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.ha.**"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">false</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
<bean id="savedRequestAwareAuthenticationSuccessHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<property name="targetUrlParameter" value="targetUrl" />
</bean>
<context:component-scan base-package="com.ha.**" />
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
</bean>
<import resource="../spring-security.xml"/>
spring-security.xml
<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"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<security:global-method-security secured-annotations="enabled"/>
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_ADMIN" />
<custom-filter ref="tokenProcessingFilter" after="FORM_LOGIN_FILTER" />
</http>
<beans:bean
class="com.ha.security.AuthenticationTokenAndSessionProcessingFilter"
id="tokenProcessingFilter">
<beans:constructor-arg name="principal" value="ANONYMOUS" />
<beans:constructor-arg name="authority" value="anonymousUser" />
<beans:constructor-arg name="tokenStore" ref="inMemoryTokenStore" />
</beans:bean>
<beans:bean class="com.ha.security.InMemoryTokenStore" id="inMemoryTokenStore" />
<authentication-manager>
<authentication-provider>
<user-service>
<user name="hr" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
Controller file is
package com.ha.security;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ha.model.UserEntity;
import com.ha.services.IUserService;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Autowired
private InMemoryTokenStore tokenStore;
#Autowired
IUserService userServices;
/* #RequestMapping(value = { "/" }, method = RequestMethod.GET)
public String welcomePage() {
return "index";
} */
#RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
#Secured("ROLE_ADMIN")
public #ResponseBody String defaultPage() {
List<UserEntity> userEntity = userServices.getUsersList();
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
return gson.toJson(userEntity);
}
#RequestMapping(value = "/admin", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto adminPage() {
return new ResponseDto("Can Access Admin");
}
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public ResponseDto login(#RequestBody UserLoginDto loginDto) {
String userName = loginDto.getUserName();
String password = loginDto.getPassword();
if (StringUtils.hasText(userName) && StringUtils.hasText(password)
&& userServices.validateAdminUser(loginDto)) {
ArrayList<GrantedAuthority> objAuthorities = new ArrayList<GrantedAuthority>();
SimpleGrantedAuthority objAuthority = new SimpleGrantedAuthority(
"ROLE_ADMIN");
objAuthorities.add(objAuthority);
User user = new User(userName, password, objAuthorities);
return new ResponseDto(this.tokenStore.generateAccessToken(user));
} else {
return new ResponseDto("Not Valid User");
}
}
}
AuthenticationTokenAndSessionProcessingFilter
package com.ha.security;
import java.io.IOException;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
public class AuthenticationTokenAndSessionProcessingFilter extends
GenericFilterBean {
private final InMemoryTokenStore tokenStore;
private final Object principal;
private final List<GrantedAuthority> authorities;
public AuthenticationTokenAndSessionProcessingFilter(
InMemoryTokenStore tokenStore, String authority, String principal) {
this.tokenStore = tokenStore;
this.principal = principal;
this.authorities = AuthorityUtils.createAuthorityList(authority);
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("Expecting a HTTP request");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
String authToken = null;
UserDetails objUserDetails = null;
if (StringUtils.hasText(httpRequest.getHeader("Authorization"))) {
authToken = httpRequest.getHeader("Authorization");
objUserDetails = this.tokenStore
.readAccessToken(authToken);
}
setAuthentication(objUserDetails, httpRequest);
chain.doFilter(request, response);
}
private void setAuthentication(UserDetails objUserDetails,
HttpServletRequest request) {
UsernamePasswordAuthenticationToken authentication = null;
if (null != objUserDetails) {
authentication = new UsernamePasswordAuthenticationToken(
objUserDetails, null, objUserDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource()
.buildDetails(request));
SecurityContextHolder.getContext()
.setAuthentication(authentication);
} else {
authentication = new UsernamePasswordAuthenticationToken(
this.principal, null, this.authorities);
SecurityContextHolder.getContext()
.setAuthentication(authentication);
}
}
}
I believe you need to use hasRole method
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
And also I noticed that you have only one user in your users list with role "ROLE_USER" hope you have added the admin user as well.
Thanks for your support, Problem get solved now and It was with importing style of security action. I was importing securty xml file multiple times
I had import securty in
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/spring-security.xml
</param-value>
</context-param>
as well as in spring-context.xml file
<import resource="../spring-security.xml"/>
due to that multiple instances creted of inMemoryTokenStore and while validating it checking user token with different one.
After removed entry from spring-context.xml and adding following qualifer in HomeController my code is working fine
#Qualifier("inMemoryTokenStore")
private InMemoryTokenStore tokenStore;
Thanks evertybuddy....:)

managed bean field is null when invoke bean method primefaces jsf

I am developing a primefaces - spring framework application but i have a big problem with my beans
i'm using spring annotations in java code to discover my beans, services, or component
but the problem is when i start jboss 7.1 AS and the beans are created i can see that my bean ListUsersBean
is created succesfully and the autowired setters are set successfully, but after when i try to invoke a test() method
from jsf page the autowired attributes are null.
I dont know what is happening
thanks a lot if anyone may help me
i'm using
spring-framework 3.2.2
JBOSS AS 7.1
primefaces 3.5
this is my bean
package edu.unbosque.beans;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.bean.ManagedProperty;
import edu.unbosque.model.User;
import edu.unbosque.services.IUserService;
import edu.unbosque.services.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
#Component
#ManagedBean
#SessionScoped
public class ListUsersBean implements Serializable{
/**
* Acceso A Datos De Usuario
*/
private IUserService userService;
private TestService testService;
/**
* Listado De Usuarios
*/
private List<User> usersList;
/**
* Usuario Seleccionado
*/
private User selectedUser;
/**
* Carga Los Usuarios
*/
private void populateUsers(){
this.usersList = this.userService.getUsers();
}
public IUserService getUserService() {
return userService;
}
#Autowired(required = true)
#Qualifier("userServiceImpl")
public void setUserService(IUserService userService) {
this.userService = userService;
}
public List<User> getUsersList() {
return usersList;
}
public void setUsersList(List<User> usersList) {
this.usersList = usersList;
}
public User getSelectedUser() {
return selectedUser;
}
public void setSelectedUser(User selectedUser) {
this.selectedUser = selectedUser;
}
public TestService getTestService() {
return testService;
}
#Autowired
public void setTestService(TestService testService) {
this.testService = testService;
}
public void test(){
this.testService = this.getTestService();
int i = 1;
i = i + 2;
}
}
this is my service
package edu.unbosque.services;
import java.util.List;
import javax.faces.bean.ManagedProperty;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import edu.unbosque.*;
import edu.unbosque.dao.UserDao;
import edu.unbosque.model.User;
import javax.inject.Named;
#Named("userServiceImpl")
public class UserServiceImpl implements IUserService{
#Autowired
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return (UserDetails) userDao.getUserByUserName(username);
}
#Override
public List<User> getUsers() {
return getUserDao().getUsers();
}
}
config files
faces-config.xml
*
<faces-config 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-facesconfig_2_0.xsd"
version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
<lifecycle>
<phase-listener>edu.unbosque.listeners.LoginPhaseListener</phase-listener>
</lifecycle>
</faces-config>
*
spring-database.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
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.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="edu.unbosque.model" />
<context:component-scan base-package="edu.unbosque.dao" />
<context:component-scan base-package="edu.unbosque.services" />
<context:component-scan base-package="edu.unbosque.beans" />
<context:property-placeholder location="classpath:jdbc.properties" />
<tx:annotation-driven transaction-manager="hibernateTransactionManager" />
<bean id="hibernateTransactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>edu.unbosque.model.User</value>
<value>edu.unbosque.model.Authority</value>
</list>
</property>
<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">update</prop>
</props>
</property>
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
</beans>
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">
<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/spring-security.xml,
/WEB-INF/spring-database.xml
</param-value>
</context-param>
<display-name>Semilleros Universidad El Bosque</display-name>
<!-- Change to "Production" when you are ready to deploy -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- Welcome page -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- JSF mapping -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map these files with JSF -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bootstrap</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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
The problem is you are mixing up jsf, CDI and spring annotations. Use #Component in your class UserServiceImpl. Because if you use #Named, the created bean's life cycle will be managed by CDI, because its a CDi annotation. So as you are using #Autowired annotation to inject the bean, which is unknown to Spring, will get null. So as you are using #Autowired while injecting the bean, the injecting bean must be in spring managed context and to do that you should have use #Component. For further reading you can see this nice tutorial.

Database connection spring framework unresolved

i had earlier created the spring framework, then replaced with the database connection, but there is problem in creating the beans.
also receiving the below error during the deployment.
DEFAULT=C:\Users\gopc\Documents\NetBeansProjects\HelloSpringJDBC\build\web&name=HelloSpringJDBC&contextroot=/HelloSpringJDBC&force=true
failed on GlassFish Server 3.1.2 Error occurred during deployment:
Exception while loading the app : java.lang.IllegalStateException:
ContainerBase.addChild: start: org.apache.catalina.LifecycleException:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'productManager' defined in ServletContext
resource [/WEB-INF/applicationContext.xml]: Error setting property
values; nested exception is
org.springframework.beans.NotWritablePropertyException: Invalid
property 'productDao' of bean class [SimpleProductManager]: Bean
property 'productDao' is not writable or has an invalid setter method.
Does the parameter type of the setter match the return type of the
getter?. Please see server.log for more details.
C:\Users\gopc\Documents\NetBeansProjects\HelloSpringJDBC\nbproject\build-impl.xml:1029:
The module has not been deployed. See the server log for details.
Source
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="externalDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" scope="singleton" destroy-method="close">
<property name="driverClassName" value="sun.jdbc.odbc.JdbcOdbcDriver"/>
<property name="url" value="jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=C://Users//gopc//Documents//odbc_sql.accdb"/>
<property name="username" value=""/>
<property name="password" value=""/>
</bean>
<bean id="productManager" class="SimpleProductManager">
<property name="productDao" ref="productDao"/>
</bean>
<bean id="productDao" class="JdbcProductDao">
<property name="dataSource" ref="externalDataSource"/>
</bean>
</beans>
spirngapp-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<bean name="/hello.htm" class="HelloController">
<property name="productManager" ref="productManager"/>
</bean>
<!-- we can prefix="/"
http://localhost:8080/HelloSpring/hello.htm
specify the path in modelview from the controller
OR
Decouple the view from the controller
prefix="/WEB-INF/jsp/"
-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
<property name="defaultLocale" value="en_US"/>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
</beans>
JdbcProductDao.java
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
public class JdbcProductDao extends SimpleJdbcDaoSupport implements ProductDao {
protected final Log logger = LogFactory.getLog(getClass());
public List<Product> getProductList() {
logger.info("Getting products!");
List<Product> products = getSimpleJdbcTemplate().query(
"select id, description, price from products",
new ProductMapper());
return products;
}
public void saveProduct(Product prod) {
logger.info("Saving product: " + prod.getDescription());
int count = getSimpleJdbcTemplate().update(
"update products set description = :description, price = :price where id = :id",
new MapSqlParameterSource().addValue("description", prod.getDescription())
.addValue("price", prod.getPrice())
.addValue("id", prod.getId()));
logger.info("Rows affected: " + count);
}
private static class ProductMapper implements ParameterizedRowMapper<Product> {
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product prod = new Product();
prod.setId(rs.getInt("id"));
prod.setDescription(rs.getString("description"));
prod.setPrice(new Double(rs.getDouble("price")));
return prod;
}
}
}
SimpleProductManager.java
import java.util.List;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SimpleProductManager implements ProductManager {
protected final Log logger = LogFactory.getLog(getClass());
private ProductDao productDao;
public List<Product> getProductDao() {
//throw new UnsupportedOperationException();
return productDao.getProductList();
}
public void increasePrice(int percentage) {
//throw new UnsupportedOperationException();
List <Product> products = productDao.getProductList();
for (Product product : products) {
double newPrice = product.getPrice() * (100 + percentage)/100;
product.setPrice(newPrice);
productDao.saveProduct(product);
}
}
public void setProductDao(ProductDao productDao) {
//throw new UnsupportedOperationException();
logger.info("inside the setProducts in SimpleProductManager");
this.productDao = productDao;
}
}
HelloController.java
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
public class HelloController implements Controller {
private ProductManager productManager;
protected final Log logger = LogFactory.getLog(getClass());
/*
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.info("Returning hello view");
String now = ( new Date().toString());
logger.info("time now:"+ now);
//return new ModelAndView("hello");
//return new ModelAndView("WEB-INF/jsp/hello","now",now);
//decouple the view from the controller
return new ModelAndView("hello","now",now);
}
*/
//Writing some business logic in the controller
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProductDao());
return new ModelAndView("hello", "model", myModel);
}
public void setProductManager(ProductManager productManager)
{
this.productManager = productManager;
}
}
hey the problem got resovled, after i had modified, the following..
1) applicationContext with mapping for the bean "productManager" with ref productDao.
2) ProductManager interface with new method call getProducts(), then implemenent in the SimpleProductManager and which call the ProductDao.getProducts(), where the sql query is being defined.

Categories

Resources