I've been fighting with the Spring framework for few weeks now, and I got
a normal MVC page to show up, and I got JDBC to print onto the console.
But I can't seem to get these to work together...
I've been through countless tutorials at this point and every one of them
seem to have some type of error or problem.
I think I've finally managed to get together a pretty decent and working build, but nope, still getting only 404's.
I think the problem might be in the spring-servlet.xml file:
<context:component-scan base-package="src" />
And I'm not sure if you can even load project like that, but it's the only thing I can think of here.
I include all the other files too, though.
Console Errors
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:spring-mvc' did not find a matching property.
and
SEVERE: Servlet [spring] in web application [/spring-mvc] threw load() exception
java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1275)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1109)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1050)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:989)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4903)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5213)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
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)
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-mvc</groupId>
<artifactId>spring-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<java.version>1.8</java.version>
<spring.version>3.1.0.RELEASE</spring.version>
<cglib.version>2.2.2</cglib.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.gatein.common</groupId>
<artifactId>common-logging</artifactId>
<version>2.2.2.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.8.1</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
</dependencies>
</project>
spring-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: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">
<!-- Telling container to take care of annotations stuff -->
<context:annotation-config />
<!-- Declaring base package -->
<context:component-scan base-package="controller" />
<!-- Adding view resolver to show jsp's on browser -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Declare beans -->
<bean id="userDao" class="dao.UserDaoImpl" />
<bean id="userService" class="services.UserServiceImpl" />
<!-- Declare datasource 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/userdb" />
<property name="username" value="root" />
<property name="password" value="38613861" />
</bean>
</beans>
web.xml
<?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"
id="WebApp_ID" version="2.5">
<display-name>SpringJDBCTemplate</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
homePageController
package controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import domain.*;
import services.*;
#Controller
public class HomePageController {
#Autowired
UserService userService;
#RequestMapping("/register")
public ModelAndView registerUser(#ModelAttribute User user) {
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, List> map = new HashMap<String, List>();
map.put("genderList", genderList);
map.put("cityList", cityList);
return new ModelAndView("register", "map", map);
}
#RequestMapping("/insert")
public String inserData(#ModelAttribute User user) {
if (user != null)
userService.insertData(user);
return "redirect:/getList";
}
#RequestMapping("/getList")
public ModelAndView getUserLIst() {
List<User> userList = userService.getUserList();
return new ModelAndView("userList", "userList", userList);
}
#RequestMapping("/edit")
public ModelAndView editUser(#RequestParam String id,
#ModelAttribute User user) {
user = userService.getUser(id);
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
List<String> cityList = new ArrayList<String>();
cityList.add("delhi");
cityList.add("gurgaon");
cityList.add("meerut");
cityList.add("noida");
Map<String, Object> map = new HashMap<String, Object>();
map.put("genderList", genderList);
map.put("cityList", cityList);
map.put("user", user);
return new ModelAndView("edit", "map", map);
}
#RequestMapping("/update")
public String updateUser(#ModelAttribute User user) {
userService.updateData(user);
return "redirect:/getList";
}
#RequestMapping("/delete")
public String deleteUser(#RequestParam String id) {
System.out.println("id = " + id);
userService.deleteData(id);
return "redirect:/getList";
}
}
Project tree
Project tree from Eclipse Neon2
Not my answer but the one which solved the case, posting as answers since it's buried deep in comments.
Sorry for the delay.... It still not right. I know that because
Eclipse should not show the package as main.java.controller.... Maven
ignores that folder and start right under the java folder as it was
the src folder itself. Something must be wrong on your project. Try
cleaning everything, remove the project from eclipse, delete
(physically) the folder .settings and the file .classpath and the file
.project. Go on your folder project on the console and run mvn clean
eclipse:clean then open all folders of if (like the image I showed to
you) and paste it here so I can see what it is wrong
– Jorge Campos
Related
This my files which I think I configured correctly. My Tomcat 9 application is up and running correctly. I just don't know what it is the problem. Tomcat deploy the application but i'm not sure if the problem relays on Tomcat o Spring MVC
rcontroller.java:
package com.mycompany.myspring;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
#RequestMapping("/")
public class rcontroller {
#ResponseBody
public String getFoosBySimplePath() {
return "Get some Foos";
}
}
dispatch-servlet.xml:
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://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 />
<context:component-scan base-package="com.mycompany.myspring" />
<!-- 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/" />
<beans:property name="suffix" value=".html" />
</beans:bean>
</beans:beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>spring-mvc-example</display-name>
<!-- Add Spring MVC DispatcherServlet as front controller -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/dispatch-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
pom.xml:
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.myspring</groupId>
<artifactId>SpringMVC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringMVC</name>
<description>Spring MVC Hello World Example</description>
<!-- Add Spring Web and MVC dependencies -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName> <!-- added to remove Version from WAR file -->
</build>
</project>
Project structure:
in your folder structure, index.html file is located under the webapp folder. but in the dispatch-servlet.xml file, you set the path as a WEB-INF folder.
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/" />
<beans:property name="suffix" value=".html" />
</beans:bean>
hence, move index.html file into WEB-INF folder
then, config the welcome file in the web.xml file as given below,
<display-name>spring-mvc-example</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
Your question is not very clear. What is the exact problem ?
Anyway there are some problems on your dispatch-servlet.xml
1- the rows
<beans:bean>
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
should be
<beans:bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
I.E. you should not close the tag bean before the class declaration and should assign it an id
2- I believe you may have some issues with the namespace beans: . If true the best think you could do is remove the beans: namespace prefix. Follow this answer
The prefix "beans" for element "beans:beans" is not bound
3- contextConfigLocation should be /WEB-INF/dispatch-servlet.xml
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatch-servlet.xml</param-value>
4- In your controller you should map the method you want ot expose with #GetMapping or òRequestMapping(method=RequestMethod.GET)
#GetMapping
#ResponseBody
public String getFoosBySimplePath() {
I suggest also not to map your controller to / but to some subpath
Following a spring mvc tutorial and I am getting the error
HTTP Status [404] – [Not Found]
The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Can anyone identify whats missing or can point me in the right direction?
Using spring tools suit 3.9.o and pivotal tc server and maven
HomeController.java
package com.infiniteskills.mvc;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
private static final Logger logger =
LoggerFactory.getLogger(HomeController.class);
/**
* 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";
}
}
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.infiniteskills</groupId>
<artifactId>mvc</artifactId>
<name>hello-world</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
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-content.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 -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
root-context.xml
<!-- 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="com.infiniteskills.mvc" />
</beans:beans>
<?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.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
</beans>
you need to use #RequestMapping("/homeController") after #Controller for mapping of Controller. and use #RequestMapping(value = "/hello", method = RequestMethod.GET) before method.
and url will b : http://localhost:8080/project-name/homeController/hello and use GET method.
I want to write a simple Web Store in NetBeans in Spring MVC framework. But when I deploy my program on Glassfish, this Error occurred:
Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.karans.webstore.models.Daoimp.UserDAOimp] 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)}. Please see server.log for more details`.
My pom.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.karans</groupId>
<artifactId>webstore</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>webstore</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- spring-context which provides core functionality -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- The spring-aop module provides an AOP Alliance-compliant aspect-oriented
programming implementation allowing you to define -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- The spring-webmvc module (also known as the Web-Servlet module) contains
Spring’s model-view-controller (MVC) and REST Web Services implementation
for web applications -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- The spring-web module provides basic web-oriented integration features
such as multipart file upload functionality and the initialization of the
IoC container using Servlet listeners and a web-oriented application context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
My web.xml is:
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring Web MVC Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring-Datasource.xml</param-value> <!-- This setup "A" works -->
<!-- <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/spring/appServlet/hibernate-context.xml</param-value> --> <!-- Once the commented sections are shifted, this setup "B" fails -->
</context-param>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
mvc-dispatcher-servlet:
<?xml version="1.0" encoding="UTF-8"?>
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.karans.webstore.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
Spring-Datasource.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/webstore" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="ProductDAOimpl" class="com.karans.webstore.models.Daoimp.ProductDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="UserDAOimpl" class="com.karans.webstore.models.Daoimp.UserDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="CartDAOimpl" class="com.karans.webstore.models.Daoimp.CartDAOimp">
<property name="template" ref="jt"></property>
</bean>
<bean id="usercontroller" class="com.karans.webstore.controllers.userController">
<property name="userdaoimp" ref="UserDAOimp"></property>
</bean>
<bean id="productcontroller" class="com.karans.webstore.controllers.productController">
<property name="ProductDaoimp" ref="ProductDAOimp"></property>
</bean>
UserDAOimp:
package com.karans.webstore.models.Daoimp;
import com.karans.webstore.models.Dao.UserDAO;
import com.karans.webstore.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
public class UserDAOimp implements UserDAO{
#Autowired
JdbcTemplate template;
#Override
public User GetUsertByUsername(String username, String password) {
User user=null;
String sql = "select * from user where username=? AND password=?";
user=(User) template.queryForObject(sql, new Object[]{username ,password},new BeanPropertyRowMapper(User.class));
return user;
}
}
And other classes is like this.
UserDAO:
package com.karans.webstore.models.Dao;
import com.karans.webstore.models.User;
public interface UserDAO {
public User GetUsertByUsername(String username,String password);
}
User:
package com.karans.webstore.models;
public class User {
private int iduser;;
private String username;
private String password;
public void setIduser(int iduser) {
this.iduser = iduser;
}
public int getIduser() {
return iduser;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
userController:
package com.karans.webstore.controllers;
import com.karans.webstore.models.Daoimp.UserDAOimp;
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;
#Controller
public class userController {
#Autowired
UserDAOimp userdaoimp;
#RequestMapping(value="/login", method = RequestMethod.GET )
public String login(){
return "login";
}
#RequestMapping( value="/loginfailed", method = RequestMethod.GET)
public String loginError(Model model){
model.addAttribute("error", "true");
return "login";
}
#RequestMapping( value = "/logout", method = RequestMethod.GET)
public String logout(Model model){
return "login";
}
}
And so on.
How can fix the problem?
Add the context-listener to web.xml in order to spring load the contextConfigLocation:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Also you can try changing the web.xml file and remove the context-param section of web.xml and set the Spring-Datasource.xml as init-param to dispatcher servlet like this:
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/Spring-Datasource.xml</param-value>
</init-param>
</servlet>
I'm doing a GWTP project and use Spring Data JPA for a connection with an oracle database. I've read several tutorials in which a repository interface is used directly without the use of implementation. It was #Autowired where needed and it worked fine. I've tried to use the same strategy but it seems the #Autowired annotation is not working at all.
Here is my Repository :
#Repository
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
I try to inject it with #Autowired in my service implementation (I use RESTful services) :
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/bugs")
#Component
public class BugServiceImpl{
#Autowired
private BugRepository bugRepository;
#GET
#Path("/findAll")
public List<Bug> findAll() {
return bugRepository.findAll();
}
}
Here is my Entity :
#Entity
#Table(name = "BUGS")
#SequenceGenerator(name = "BUG_SEQUENCE", sequenceName = "BUG_SEQUENCE")
public class Bug implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BUG_SEQUENCE")
#Column(name="BUG_ID")
private Long bugId;
#Column(name="BUG_NAME")
private String bugName;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="CREATED_BY")
private User createdBy;
#OneToOne
#PrimaryKeyJoinColumn
#Column(name="ASSIGNED_TO")
private User assignedTo;
#Column(name="CREATION_DATE")
private Date creationDate;
#Column(name="LAST_UPDATE_DATE")
private Date lastUpdateDate;
#Column(name="BUG_COMMENT")
private String bugComment;
#OneToOne(cascade = CascadeType.ALL, optional = false, fetch = FetchType.EAGER, orphanRemoval = true)
#PrimaryKeyJoinColumn
#Column(name="PRIORITY_ID")
private Priority priority;
#OneToOne
#PrimaryKeyJoinColumn
private Status status;
public Bug() {
}
}
I also have applicationContext.xml and persistence.xml in main/resources/META-INF. Here is my 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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.0.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<context:component-scan base-package="com.edu" />
<jpa:repositories base-package="com.edu.server.repositories" />
<context:annotation-config />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="***"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</bean>
<!-- EntityManagerFactory -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:packagesToScan="com.edu.shared.entity"
p:dataSource-ref="dataSource"
>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My persistence.xml :
<persistence 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"
version="2.0">
<!-- oracle -->
<persistence-unit name="oracle">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.edu.server.service.BugServiceImpl</class>
<class>com.edu.server.repositories.BugRepository</class>
<class>com.edu.shared.entity.Bug</class>
<properties>
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.connection.driver_class" value="oracle.jdbc.OracleDriver" />
<property name="hibernate.connection.url" value="***" />
<property name="hibernate.connection.username" value="***" />
<property name="hibernate.connection.password" value="***" />
<property name="hibernate.flushMode" value="FLUSH_AUTO" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
And finally the exception I get is :
java.lang.NullPointerException
com.edu.server.service.BugServiceImpl.findAll(BugServiceImpl.java:39)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
...
When I debug the code and put a breakpoint to the autowired repository it appears to be null so I suppose it's not injected properly and that's why invoking the method findAll fires the NullPointerException. So, why do you think the #Autowired annotation is not working?
I think you're mixing two ways of Spring/JPA configuration. Last time when i configured Spring/JPA project with XML I use only DataSource bean without persistence.xml configuration for connection to the database. I can suggest you to read the official documentation of Spring Data. The community has one of the best documentation.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/orm.html
First problem that i see is you have annotated your interface with #Repository
You shouldn't do that, but as follows:
//no annotation here
public interface BugRepository extends JpaRepository<Bug, Long> {
List<Bug> findAll();
.....
}
Secondly, make sure your BugRepository interface is in the package below, or else it wont work:
<jpa:repositories base-package="com.edu.server.repositories" />
Third thing i noticed is in your persistance.xml, you have noted NOT only #Entity beans, but #Service and a #Repository. You are supposed to only have #Entity beans (which are to be managed)
Lastly, you seem to be mixing Spring and Jersey, so make sure you have your Spring container (application/web context) properly set up, so it can manage (inject) your beans/repos/services.
I want to thank all for the help. I solved my problem. There were problems in my configuration files.
First of all, I really didn't need any persistence.xml because I've created a dataSource bean in my applicationContext.xml which contains all of the needed information regarding the connection with my database. You shouldn't mix the both things, I suppose.
Secondly, you should properly configure the link between Spring and Jersey. I had to add some new dependencies in my pom.xml which were needed for linking Spring and Jersey (there is a jersey-spring3 dependency which I didn't know existed). So, now all of the dependencies I use, concerning Spring and Jersey are these:
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.rs.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.fusesource.restygwt</groupId>
<artifactId>restygwt</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>1.1.2.RELEASE</version>
<type>pom</type>
<!--<scope>import</scope>-->
<scope>compile</scope>
</dependency>
<!-- DataSource (HikariCP) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.2.5</version>
</dependency>
<!-- JPA Provider (Hibernate) -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.2.RELEASE</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>12.1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.8.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
</exclusions>
</dependency>
In addition, I had to configure my web.xml so that Jersey could read the applicationContext.xml. Without configuring my web.xml the applicationContext.xml was useless and that's why the annotations and the connection with the database didn't work. Here is my web.xml :
<?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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:META-INF/applicationContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
As far as I understood the ContextLoadListener makes sure the web configuration "listens" for other configuration xml files and that's how the applicationContext.xml is now read and used. And with these settings
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.edu</param-value>
I make sure that my packages would be scanned for #Provider and #Path annotations and without these piece of my code my services would not be active.
More about this Provider Packages setting can be read here :
https://jersey.java.net/apidocs/2.23.2/jersey/org/glassfish/jersey/server/ServerProperties.html#PROVIDER_PACKAGES
I hope my issue and this answer are useful for all with similar configuration problems.
The Problem is very weird.My IDE is IDEA. Spring version is 4.3.1.RELEASE.The Blow is my project structure
The Blow is web.xml(Simple)
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml,
/WEB-INF/infrastructure.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/home/profile</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
The apllicationContext.xml just one line
<context:component-scan base-package="net.codespace.entity, net.codespace.DAO, net.codespace.service" />
The Blow is SpringMVC-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="net.codespace" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/home/" />
<property name="suffix" value=""/>
</bean>
</beans>
The PersonDAO is interface.The Code is Blow
import net.codespace.entity.Person;
public interface PersonDAO {
public void save(Person p);
public void findAll();
}
PersonDAOImpl is implementation.
import net.codespace.entity.Person;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository("personDAO")
public class PersonDAOImpl implements PersonDAO{
#Autowired
private SessionFactory sessionFactory;
public void save(Person p){
}
public void findAll(){
}
}
Same,The PersonService is interface,
package net.codespace.service;
/**
* Created by mark on 2016/7/26.
*/
import net.codespace.entity.Person;
public interface PersonService {
public void savePerson(Person p);
public void getAllPerson(Person p);
}
PersonServiceImpl is blow
import net.codespace.entity.Person;
import net.codespace.DAO.PersonDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service("personService")
#Transactional
public class PersonServiceImpl implements PersonService{
#Autowired
private PersonDAO personDAO;
public void savePerson(Person p){
}
public void getAllPerson(Person p){
System.out.println("punk your pieese");
}
}
The pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.markliang</groupId>
<artifactId>lsc-toy</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<jackson.version>2.6.3</jackson.version>
<hibernate.version>4.3.5.Final</hibernate.version>
<spring.version>4.3.1.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>servlet-api</artifactId>
<version>5.5.23</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.3.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
</dependencies>
</project>
When I deploy this Project, I got these Error(Show Important)
严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personService' defined in file
[C:\Users\mark\IdeaProjects\SMS01\out\artifacts\SMS01_war_exploded\WEB-INF\classes\net\codespace\service\PersonServiceImpl.class]: Post-processing failed of bean type [class net.codespace.service.PersonServiceImpl] failed; nested exception is java.lang.IllegalStateException: Failed to introspect bean class [net.codespace.service.PersonServiceImpl] for persistence metadata: could not find class that it depends on
Caused by: java.lang.IllegalStateException: Failed to introspect bean class [net.codespace.service.PersonServiceImpl] for
persistence metadata: could not find class that it depends on
/* some info */
Caused by: java.lang.NoClassDefFoundError: Lnet/codespace/DAO/PersonDAO;
/* some info */
Caused by: java.lang.ClassNotFoundException: net.codespace.DAO.PersonDAO
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1891)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1734)
/*some info */
Could someone help me? If you need more detail info, I can Send u a mail.Thanks
You need to know the difference between an applicationContext and a servlet-context (have a look at this answer.
Your servlet context shouldn't be scanning the persistence layer, because the persistence layer should have an application scope , which means to be available for all the servlets.
In your SpringMvc, scan only controllers:
<context:component-scan base-package="net.codespace.contrller" />
In your application Context you should scan repositories and services so you can bean wiring them.
The java.lang.ClassNotFoundException: net.codespace.DAO.PersonDAO and java.lang.NoClassDefFoundError: Lnet/codespace/DAO/PersonDAO should be the main concern.
You need to check why PersonDAO is not available on the classpath. Try the following:
Does the package declaration in your PersonDAO.java file match the folder structure? (it's either omitted in your post or missing from the file) i.e. package net.codespace.DAO;
Run mvn clean install and (making sure that it compiles and finishes ok) check that target/classes/net/codespace/DAO/PersonDAO.class exists.
If the above is ok then you will need to examine the classpath to see why it cannot find this class - this will depend on how you are running the application (in the IDE or Maven etc).
NB This shouldn't matter but Java naming convention for packages is lower case so ideally your package name should be net.codespace.dao