#Before Advice Annotation not Applied in the Spring Application - spring

I have been trying to develop a small application that demonstrates the #Before Annotation , but its not working
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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>aopdemo</groupId>
<artifactId>aopdemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.11</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>
AccoutDAO.java file is
package org.java.aop.dao;
import org.springframework.stereotype.Component;
#Component
public class AccoutDAO {
public void addAccount()
{
System.out.println("Adding account"+getClass());
}
}
The Aspect configuration file is
package org.java.aop.aspects;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
#Aspect
#Component
public class MyAspects {
#Before("execution(public void addAccount())")
public void display()
{
System.out.println("=====================>>CALLING Aspects");
}
}
The spring config file(spring-config.xml) is
<?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:mvc="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>
</beans>
And finally my main code is
package org.java.aop;
import org.java.aop.dao.AccoutDAO;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainDemo {
public static void main(String arg[])
{
try
{
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
AccoutDAO accoutDAO=context.getBean("accountDAO",AccoutDAO.class);
accoutDAO.addAccount();
context.close();
}
catch (Exception e)
{
System.out.print(e);
}
}
}
I am able to get the output as "INFO: Loading XML bean definitions from class path resource [spring-config.xml]
Adding accountclass org.java.aop.dao.AccoutDAO
Nov 22, 2018 2:06:14 AM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.support.ClassPathXmlApplicationContext#1ed6993a: startup date [Thu Nov 22 02:06:14 IST 2018]; root of context hierarchy"
But i could not able to get the output for #Before Annotation.Kindly tell me whats wrong in this code

The above problem is resolved by adding component scan in spring-config.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:mvc="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="accountDAO" class="org.java.aop.dao.AccoutDAO">
</bean>
<aop:aspectj-autoproxy/>
<context:component-scan base-package="org.java.aop"/>
</beans>

Related

Spring validation annotations (#Size, #NotEmpty, #Max...) not working in my MVC project

I'm trying to get my head around an MVC project. There is a form page that the user fills out and they end up in an object of the Employee class.
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
Here is what the class part looks like. It can be seen that I set parameter validation above some of the fields.
import jakarta.validation.constraints.*;
...
public class Employee {
#Size(min = 2, message = "Name must be min 2 symbols")
private String name;
#NotBlank(message = "surname is required field")
private String surname;
#Max(value = 100,message = "max is required field")
private int salary;
....
}
Here's what the html page looks like with the form filled out. It can be seen that the form "errors" is used to catch errors.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
...
<form:form action="show" modelAttribute="employee">
Name <form:input path="name"/>
<form:errors path="name" />
<br>
<br>
Surname <form:input path="surname"/>
<form:errors path="surname"/>
<br>
<br>
Salary <form:input path="salary"/>
<form:errors path="salary" />
...
Well, this is how the method looks like, which redirects to another page if all the fields in the form have been validated.
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask-page";
} else {
return "show-page";
}
The problem is that the annotations specified above the fields in the class do not work. Here is the output of the showDetails method, which shows that data is being entered that does not match the specified restrictions in the Size, Name annotations. You can also see that bindingResult indicates no errors.
...
surname length = 0
name length = 0
bindingResult.hasErrors() = false
Does anyone know why these annotations don't work?
In my view, validation should not pass and the user should be returned the original form with an error on incorrectly filled fields
UPD.
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pablinho.spring.mvc</groupId>
<artifactId>spring_mvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<name>spring_mvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>javax.servlet</groupId>-->
<!-- <artifactId>servlet-api</artifactId>-->
<!-- <version>2.5</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-validator</artifactId>-->
<!-- <version>6.1.0.Final</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>spring_mvc</finalName>
</build>
</project>
UPD. Add web.xml, applicationContext.xml and conroller MyController.java
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>spring-cource-mvc</display-name>
<absolute-ordering />
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.pablinho.spring.mvc" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
MyContoller.java
package com.pablinho.spring.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import jakarta.validation.Valid;
#Controller
#RequestMapping("/")
public class MyController {
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask=page";
} else {
return "show-page";
}
}
}

Query failed with error code 16550 and error message 'not authorized for query on myCollection

I have a spring boot rest application that interacts with MongoDB but when I invoke the controller method, I give the following exception :
com.mongodb.MongoQueryException: Query failed with error code 16550 and error message 'not authorized for query on 'tenant' on server 172.16.233.128:27017
at com.mongodb.connection.ProtocolHelper.getQueryFailureException(ProtocolHelper.java:131) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:295) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.QueryProtocol.execute(QueryProtocol.java:54) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.connection.DefaultServerConnection.query(DefaultServerConnection.java:212) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:525) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:510) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:81) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo.execute(Mongo.java:836) ~[mongo-java-driver-3.4.2.jar:na]
at com.mongodb.Mongo$2.execute(Mongo.java:823) ~[mongo-java-driver-3.4.2.jar:na] .....
these are classes and configuration
pom.xml is
<?xml version="1.0" encoding="UTF-8"?>
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.concretepage</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-mongodb</name>
<description>Spring Boot Demo Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
xml configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:annotation-config />
<context:property-placeholder location="classpath*:properties/application.properties"/>
<context:component-scan base-package="com.faracloud.mongodbop.controller" />
<mvc:annotation-driven />
<mongo:mongo id="mongo" host="${catalog.mongodb.host}" port="${catalog.mongodb.port}" />
<mongo:db-factory id="mongoDbFactory" dbname="${catalog.mongodb.database}" mongo-ref="mongo"
username="${catalog.mongodb.user}"
password="${catalog.mongodb.password}"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.faracloud.mongodbop.repository"
mongo-template-ref="mongoTemplate" />
MongoApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;
#SpringBootApplication
#ImportResource("classpath:spring/mongodbop-context.xml")
public class MongoApp {
public static void main(String[] args) {
ApplicationContext ctx =SpringApplication.run(MongoApp.class,
args);
}
}
TenantRepository.java
import com.faracloud.mongodbop.model.Tenant;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface TenantRepository extends MongoRepository<Tenant,
String> {
}
and Rest Controller
import com.faracloud.mongodbop.model.Tenant;
import com.faracloud.mongodbop.repository.TenantRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class StatisticController {
#Autowired
TenantRepository repo;
#RequestMapping("/greeting")
public List<Tenant> greeting() {
return repo.findAll() ;
}
}
please give me some advice how to handle this error
My problem was solved using these dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
instead of using mongoTemplate and mongoDbFactory for host,dbnameand credentials, I used following configurations in application.properties
spring.data.mongodb.host=x.x.x.x
spring.data.mongodb.port=27017
spring.data.mongodb.database=xxx
spring.data.mongodb.username=***
spring.data.mongodb.password=***
Thank you reviewers.

AspectJ + Perf4J + Spring and #Profiled annotation?

I can't get AspectJ to work at all, and I have ran out of ideas after following 10 different tutorials.
Here is what I am trying to do...
I have a Spring application. It uses Spring, Perf4J, and Now Aspect(if it ever works!) and I want to use #Profiled("some tag here") at the tog of my public method. That is it, nothing too fancy.
Here is the code I am trying to run :
#Override
#Profiled(tag = "MainClass" + ".runMethod", logFailuresSeparately = true)
public Collection<Throwable> runMethod() throws Exception {
System.out.println("Running a simple method that I want timings for.");
}
Here are my POM dependencies used in maven to get everything to set up.
<dependencies>
<!-- Spring (includes spring-aop)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- AspectJ (required spring-aop dependency) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.5</version>
</dependency>
<!-- LOG -->
<dependency>
<groupId>org.perf4j</groupId>
<artifactId>perf4j</artifactId>
<version>${perf4j.version}</version>
</dependency>
</dependencies>
Here is the aspect beans file :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="true">
<aop:include name="timingAspect"/>
</aop:aspectj-autoproxy>
<!--<context:load-time-weaver/> -->
<!-- The perf4j aspect -->
<bean id="timingAspect" class="org.perf4j.log4j.aop.TimingAspect"/>
Here is how I bring that XML beans file in (within the spring application context file) :
<import resource="aspectBeans.xml" />
Now, the application compiles, it runs, and it prints my System.out.println line, but I am seeing absolutely nothing related to timing.

No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]

when autowired the datasource ,the project will appear error,when i remove the datasource ,the project works normal. i have add the datasource beans in the spring,i do not know where is wrong
i put my project on git address is:
git#github.com:liwei-green/springMVC.git
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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>springMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springMVC</finalName>
</build>
</project>
the spring
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context- 4.1.xsd">
<!-- 加载配置文件 -->
<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="com.springdemo" />
<context:property-placeholder location="jdbc.properties" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<beans>
the DemoController.java
package com.springdemo.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
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.servlet.ModelAndView;
import com.springdemo.entity.User;
import com.springdemo.service.UserService;
#Controller
public class DemoController {
#Autowired
private UserService userService;
/*加上
#Autowired
private DataSource dataSource
编译报错,没有这句编译正常*/
#Autowired
private DataSource dataSource;
#RequestMapping("login.do")
public ModelAndView index(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
System.out.println(userService);
System.out.println(dataSource);
String userName=request.getParameter("userName");
String userAge=request.getParameter("userAge");
User user= userService.findById(3);
if(userName.equals(user.getName())){
return new ModelAndView("sys/success","user",user);
}else{
return new ModelAndView("sys/faild","user",user);
}
}
}
jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url=mysql://localhost:3306/maven?useUnicode=true&characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
enter image description here
The context config listener is missing in web.xml, so the beans in spring.xml are not init, you can add these to your web.xml,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
BTW: spring.xml path is not correct in the web.xml, you can change to this.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>

java.lang.NullPointerException exception in my controller file (using Spring Hibernate Maven)

The problem happens when I run this part (#RequestMapping("/SearchStaff")) in my controller file. I can display my search form successfullt (the request mapping below SearchStaff).
The problem doesn't seemed to have anything to do with Hibernate. As I've commented the Hibernate stuff but I'm still getting it.
If I comment out this line
message = staffDAO.searchForStaff(search);
in my controller file, it goes through ok. But I don't see anything wrong with searchForStaff function. It's a very simple function that just returns the string "test" and run system.out.println("test").
Can you please help? thanks
But this is the error that I'm getting:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
org.flinders.staffdirectory.controllers.SearchController.showSearchResults(SearchController.java:25)
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:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
My 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:context="http://www.springframework.org/schema/context"
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.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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.flinders.staffdirectory.controllers" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven />
<bean
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring.properties" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean
id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="org.flinders.staffdirectory"/>
<bean
id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"
p:viewClass="org.springframework.web.servlet.view.tiles2.TilesView" />
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
p:definitions="/WEB-INF/tiles.xml" />
<bean
id="staffDAO"
class="org.flinders.staffdirectory.dao.StaffDAO"
p:sessionFactory-ref="sessionFactory" />
<!-- <bean
id="staffService"
class="org.flinders.staffdirectory.services.StaffServiceImpl"
p:staffDAO-ref="staffDAO" />-->
</beans>
This is my controller file
package org.flinders.staffdirectory.controllers;
import java.util.List;
//import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
import org.flinders.staffdirectory.dao.StaffDAO;
//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.servlet.ModelAndView;
#Controller
public class SearchController {
//#Autowired
private StaffDAO staffDAO;
private String message;
#RequestMapping("/SearchStaff")
public ModelAndView showSearchResults(#ModelAttribute Search search) {
//List<SearchResult> searchResults =
message = staffDAO.searchForStaff(search);
//System.out.println(search.getSurname());
return new ModelAndView("search/SearchForm", "Search", new Search());
//return new ModelAndView("search/SearchResults", "searchResults", searchResults);
}
#RequestMapping("/SearchForm")
public ModelAndView showSearchForm() {
return new ModelAndView("search/SearchForm", "search", new Search());
}
}
my dao class
package org.flinders.staffdirectory.dao;
import java.util.List;
import org.hibernate.SessionFactory;
//import org.springframework.beans.factory.annotation.Autowired;
import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
public class StaffDAO {
//#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public String searchForStaff(Search search) {
/*String SQL = "select distinct telsumm_id as id, telsumm_parent_id as parentId, telsumm_name_title as title, (case when substr(telsumm_surname, length(telsumm_surname) - 1, 1) = ',' then substr(telsumm_surname, 1, length(telsumm_surname) - 1) else telsumm_surname end) as surname, telsumm_preferred_name as firstname, nvl(telsumm_tele_number, '-') as telephoneNumber, nvl(telsumm_role, '-') as role, telsumm_display_department as department, lower(telsumm_entity_type) as entityType from teldirt.teld_summary where (telsumm_search_surname is not null) and not (nvl(telsumm_tele_directory,'xxx') IN ('N','S','D')) and not (telsumm_tele_number IS NULL AND telsumm_alias IS NULL) and (telsumm_alias_list = 'Y' OR (telsumm_tele_directory IN ('A','B'))) and ((nvl(telsumm_system_id_end,sysdate+1) > SYSDATE and telsumm_entity_type = 'P') or (telsumm_entity_type = 'N')) and (telsumm_search_department NOT like 'SPONSOR%')";
if (search.getSurname().length() > 0) {
SQL += " and (telsumm_search_surname like '" + search.getSurname().toUpperCase() + "%')";
}
if (search.getSurnameLike().length() > 0) {
SQL += " and (telsumm_search_soundex like soundex(('%" + search.getSurnameLike().toUpperCase() + "%'))";
}
if (search.getFirstname().length() > 0) {
SQL += " and (telsumm_search_preferred_name like '" + search.getFirstname().toUpperCase() + "%' or telsumm_search_first_name like '" + search.getFirstname() + "%')";
}
if (search.getTelephoneNumber().length() > 0) {
SQL += " and (telsumm_tele_number like '" + search.getTelephoneNumber() + "%')";
}
if (search.getDepartment().length() > 0) {
SQL += " and (telsumm_search_department like '" + search.getDepartment().toUpperCase() + "%')";
}
if (search.getRole().length() > 0) {
SQL += " and (telsumm_search_role like '" + search.getRole().toUpperCase() + "%')";
}
SQL += " order by surname, firstname";
List<Object[]> list = (List<Object[]>) sessionFactory.getCurrentSession().createQuery(SQL).list();
for(int j=0;j<list.size();j++){
Object [] obj= (Object[])list.get(j);
for(int i=0;i<obj.length;i++)
System.out.println(obj[i]);
}*/
System.out.println("test");
return "test";
}
}
my 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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.flinders.staffdirectory</groupId>
<artifactId>directory-maven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>directory-maven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>3.1.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>directory-maven</finalName>
</build>
</project>
StaffDAO is null . Any reason why you commented out its autowiring.
Also I see private SessionFactory sessionFactory; Autowired is also commented. Please try removing those comments.
//#Autowired

Resources