I m setting up my java web application on the server but the rest controller is giving 404 error.
All is working fine on my local system.
This is my 1st project in java hibernate spring.
Below is my code:
UserLoginController.java
package org.jasyatra.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.jasyatra.model.User;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.service.UserLoginService;
import org.jasyatra.service.LoginAuthTokenService;
#RestController
public class UserLoginController {
#Autowired
UserLoginService userLoginService;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#RequestMapping(value = "/user/login", method = RequestMethod.POST, headers = "Accept=application/json")
public Map login(#RequestBody User parameters) {
List<User> loginResponse = userLoginService.login(parameters);
Map<String, String> response = new HashMap<>();
if (loginResponse.size() > 0) {
response.put("result", "true");
response.put("id", Integer.toString(loginResponse.get(0).getId()));
response.put("type", loginResponse.get(0).getType());
response.put("firstName", loginResponse.get(0).getFirstName());
response.put("lastName", loginResponse.get(0).getLastName());
response.put("permissions", loginResponse.get(0).getPermissions());
List<LoginAuthToken> responseToken = loginAuthTokenService.getLatestToken(loginResponse.get(0).getId(),loginResponse.get(0).getType());
response.put("token", responseToken.get(0).getToken());
} else {
response.put("result", "false");
response.put("message", "Invalid mobile no or password!");
}
return response;
}
}
UserLoginDAO.java
package org.jasyatra.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.jasyatra.service.HashService;
#Repository
public class UserLoginDAO {
#Autowired
private SessionFactory sessionFactory;
public List<User> login(User parameters) {
Session session = this.sessionFactory.getCurrentSession();
Query query = session.createQuery("from User where mobileNo=:mobileNo and password=:password and status=:status");
query.setParameter("mobileNo", parameters.getMobileNo());
query.setParameter("password", HashService.getHash(parameters.getPassword(), "SHA1"));
query.setParameter("status", "active");
List<User> response = query.list();
return response;
}
}
UserLoginService.java
package org.jasyatra.service;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.jasyatra.dao.UserLoginDAO;
import org.jasyatra.dao.LoginAuthTokenDAO;
import org.jasyatra.model.LoginAuthToken;
import org.jasyatra.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class UserLoginService {
#Autowired
UserLoginDAO userLoginDao;
#Autowired
LoginAuthTokenDAO loginAuthTokenDAO;
#Autowired
LoginAuthTokenService loginAuthTokenService;
#Transactional
public List<User> login(User parameters) {
List<User> login = userLoginDao.login(parameters);
LoginAuthToken loginAuthToken = new LoginAuthToken();
if (login.size() > 0 && login.get(0).getId() > 0) {
try {
loginAuthToken.setLoginId(login.get(0).getId());
loginAuthToken.setLoginType(login.get(0).getType());
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
String token = HashService.getHash(generatedString, "SHA1");
loginAuthToken.setDateCreated(new Date());
loginAuthToken.setToken(token);
loginAuthTokenService.save(loginAuthToken);
} catch (Exception e) {
e.printStackTrace();
}
}
return login;
}
}
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/"/>
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/jasyatra" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.jasyatra.model.User</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="268435456"/>
</beans:bean>
<context:component-scan base-package="org.jasyatra" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</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="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_3_0.xsd"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<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>
The main issue i have is, it is able to run index.jsp but not the controller. What can be the issue?
Please guide me in right direction.
Thanks
you can not open that url in browser because it is POST service, you can only open GET url in browser. you need to add a body while hitting that url to test
your service you can use postman.
no need to send "Accept" header this way, you can use however following attribute instead if you expect a json body with the post request :
#RequestMapping(value = "/user/login", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE);
if you want to get "Accept" header value of your request you can get it like :
public Map login(#RequestBody User parameters,#RequestHeader(value="Accept") String accept){
....
Related
I am getting this error and I can't figure out why. I believe its the path. Tried to change it several times but no success.
***************************
APPLICATION FAILED TO START
***************************
Description:
Field loginDelegate in com.codeEvaluator.controller.LoginController required a bean of type 'com.codeEvaluator.delegate.LoginDelegate' that could not be found.
Action:
Consider defining a bean of type 'com.codeEvaluator.delegate.LoginDelegate' in your configuration.
Process finished with exit code 1
This is my sprinBeanConfiguration.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<bean id="loginDelegate" class="com.codeEvaluator.delegate.LoginDelegate">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="com.codeEvaluator.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="userDao" class="com.codeEvaluator.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</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/codeevaluator" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
My springWeb.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.jcg" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
<import resource="springBeanConfiguration.xml"/>
Controller class
package com.codeEvaluator.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.codeEvaluator.delegate.LoginDelegate;
import com.codeEvaluator.viewBean.LoginBean;
#Controller
public class LoginController
{
#Autowired
private LoginDelegate loginDelegate;
#RequestMapping(value="/login",method=RequestMethod.GET)
public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response, LoginBean loginBean)
{
ModelAndView model = new ModelAndView("login");
//LoginBean loginBean = new LoginBean();
model.addObject("loginBean", loginBean);
return model;
}
#RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response, #ModelAttribute("loginBean")LoginBean loginBean)
{
ModelAndView model= null;
try
{
boolean isValidUser = loginDelegate.isValidUser(loginBean.getUsername(), loginBean.getPassword());
if(isValidUser)
{
System.out.println("User Login Successful");
request.setAttribute("loggedInUser", loginBean.getUsername());
model = new ModelAndView("welcome");
}
else
{
model = new ModelAndView("login");
request.setAttribute("message", "Invalid credentials!!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
return model;
}
}
This is a project view.
The login.jsp is inside de jsp package.
change to
<context:component-scan base-package="com.jcg, com.codeEvaluator" />
and your import should be something like this
<import resource="classpath:springBeanConfiguration.xml"/>
or
<import resource="classpath*:springBeanConfiguration.xml"/>
In your "sprinBeanConfiguration.xml" file add those annotations <context:component-scan base-package="com.codeEvaluator" /> and<context:annotation-config> to enable annotation "#Autowired"
I am getting error :
java.lang.ClassNotFoundException:
org.springframework.web.servlet.handler.SimpleMappingExceptionResolver
I am hitting URL : http://localhost:8080/SpringMvcExceptionHandling/student on my local machine
Full Strack Trace is :
I have already checked most of the question/answer but not getting any help to resolve my issue,Please help.
Here is what I have done :
I am working on Spring Exception Handling with Jars(Spring-3.1.2). I am not using maven.
web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="2.5">
<servlet>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMvcExceptionHandling</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
SpringMvcExceptionHandling-servlet.xml 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:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:component-scan base-package="com.exceptionhandling.mvc.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean
class="org.springframework.web.servlet.handler.
SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="com.exceptionhandling.mvc.controller.SpringException">
ExceptionPage
</prop>
<prop key="java.lang.Exception">error</prop>
</props>
</property>
<property name="defaultErrorView" value="/error" />
</bean>
</beans>
StudentController.java
package com.exceptionhandling.mvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.exceptionhandling.mvc.model.Student;
#Controller
public class StudentController {
#RequestMapping(value = "/student")
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
#RequestMapping(value = "/addStudent", method = RequestMethod.POST)
#ExceptionHandler({SpringException.class})
public String addStudent(#ModelAttribute("SpringMvcExceptionHandling") Student student,
ModelMap model) {
if (student.getName().length() < 5) {
throw new SpringException("Given name is too short");
} else {
model.addAttribute("name", student.getName());
}
if (student.getAge() < 10) {
throw new SpringException("Given age is too low");
} else {
model.addAttribute("age", student.getAge());
}
model.addAttribute("id", student.getId());
return "result";
}
}
SpringException.java
package com.exceptionhandling.mvc.controller;
public class SpringException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String exceptionMsg;
public SpringException(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
public String getExceptionMsg() {
return exceptionMsg;
}
public void setExceptionMsg(String exceptionMsg) {
this.exceptionMsg = exceptionMsg;
}
}
My Project Structure Looks Like
Jars
Added Two External Jars :
In your SpringMvcExceptionHandling-servlet.xml file, your bean class name must be fully qualified (with no spaces in between).
So your solution must be:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
I tried to load data via AJAX in Spring 3.0, but the AJAX URL can't find the controller in Spring, and I don't know how to fix this.
I know while server start it looks up the URL and gets data but here I can't crate annotation properly in spring and I have searched the web a lot but have not succeeded.
My Java class:
package springactiontest;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import Dao.dao;
#Controller
//#RequestMapping("/employee")
public class mainclass {
#RequestMapping(value="/AddUser",method=RequestMethod.GET)
public #ResponseBody static String data(ModelMap model, HttpSession session) {
System.err.println("err ocured");
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
setvalueclass studentJDBCTemplate =(setvalueclass)context.getBean("actionclass");
System.out.println("------list district--------" );
JSONArray newtest=new JSONArray();
List<dao> students = studentJDBCTemplate.listStudents();
for (dao record : students)
{
JSONObject ob=new JSONObject();
System.out.print("ID test: " + record.getDistrict());
ob.put("distrct", record.getDistrict());
newtest.add(ob);
}
System.err.println("error");
String res=newtest.toString();
System.err.println("error"+res);
return res;
}
}
Jsp:
$("document").ready(function () {
alert("distrcict");
dist_pop();
});
function dist_pop() {
var urlService="http://tamilnilam:8080/SpringTest";
$.ajax({
url: urlService +'/AddUser',
type: 'GET',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("sucess")
},
error: function (jqXHR, exception) {
alert("Error Occured in dist pop");
}
});
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="springactiontest.setvalueclass"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://10.163.2.165:5434/land_rural"/>
<property name="username" value="postgres"/>
<property name="password" value="postgres"/>
</bean>
<bean id="actionclass" class="springactiontest.setvalueclass">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
Looks like component-scan is missing, it helps Spring to detect and instantiate Spring beans which are annotated with #Component, #Service,#Repository, #Controller, #Endpoint etc
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.your.controller.package" />
// Rest of the bean defiantions
</beans>
For reference : Spring MVC tutorial
I've been currently working on a Maven + Spring + Hibernate project. Actually, this is just a test project just to get familiar on how Spring works with Hibernate (+Maven). I've already setup and prepare the necessary dependencies. i.e. the appcontext.xml for Spring, the persistence.xml for Hibernate, the entity and DAO objects for JPA/Persistence/Hibernate.
During debug, persist method throws Transactionrequiredexception, no transaction in progress. I don't know what's causing this
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" version="2.5">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext-datasource.xml
/WEB-INF/applicationContext.xml
</param-value>
</context-param>
<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/applicationContext-servlet.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>
application-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.names.home" />
<!-- Default locale set -->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en"/>
</bean>
<!-- Tell Spring to not try to map things in these directories to controllers -->
<!-- Order must be set to supercede the handler configured by the mvc:annotation-driven annotation -->
<mvc:resources order="-10" location="/img/" mapping="/img/**" />
<mvc:resources order="-10" location="/css/" mapping="/css/**" />
<mvc:resources order="-10" location="/js/" mapping="/js/**" />
<mvc:resources order="-10" location="/fonts/" mapping="/fonts/**" />
<mvc:resources order="-10" location="favicon.ico" mapping="favicon.ico" />
<mvc:resources order="-10" location="robots.txt" mapping="robots.txt" />
</beans>
applicationContext-datasource.xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- The "webDS" data source is the main data source for names. It is referenced and
should be configured via JNDI in your particular environment. -->
<jee:jndi-lookup id="datasource" jndi-name="jdbc/web"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
<property name="persistenceUnitName" value="wzpu"/>
<property name="dataSource" ref="datasource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
</beans>
admincontroller.java
package com.names.home;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class AdminController {
#Resource(name="profiledao")
protected ProfileDao profiledao;
#RequestMapping(value="/admin/insert")
#Transactional
public String insert(){
Profile pr = new Profile();
pr.setId(1);
profiledao.save(pr);
return "home";
}
}
ProfileDao.java
package com.names.home;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
#Repository
public class ProfileDao {
#PersistenceContext(unitName = "wzpu")
protected EntityManager em;
public Profile find(){
return this.em.find(Profile.class, 2);
}
public void save(Profile profile){
this.em.persist(profile);
em.flush();
}
}
Profile.java
package com.names.home;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "profile")
public class Profile implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "PROFILE_ID",nullable=false,unique=true)
protected int id;
public Profile() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Profile other = (Profile) obj;
if (id != other.id)
return false;
return true;
}
}
Please help me resolving this
The root of your issue is that the bean you've annotated with the #Transactional annotation is not being picked up by the context that contains the tx:annotation-driven post processor. You have a couple options. Move the #Transactional to a bean that is loaded by the context that contains the tx:annotation-driven post processor or move the tx:annotation-driven post processor into the same context that the #Transactional bean is being loaded.
The answer here is a similar situation.
I am new to spring, in my application I need to connect to Mysql, all my database's configuration are in a bean, when I try to get it,the server gives me this error:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'dataSource' is defined
this is my servlet-context where I define my bean:
<?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 />
<!-- 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.metmi.mmasgis" />
<beans:bean id="dataSource" name="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
autowire-candidate="true">
<beans:property name="driverClassName"
value="com.mysql.jdbc.Driver">
</beans:property>
<beans:property name="username" value="root"></beans:property>
<beans:property name="password" value="password"></beans:property>
<beans:property name="url"
value="jdbc:mysql://localhost:3306/springschema">
</beans:property>
</beans:bean>
</beans:beans>
this is my controller:
package com.metmi.mmasgis;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ContextLoader;
import com.metmi.mmasgis.dao.DbImpl;
import com.metmi.mmasgis.model.Db;
/**
* Handles requests for the application home page.
*/
#Controller
public class HomeController {
#Inject
DbImpl dbs;
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";
}
/**
* get the database list in Mysql
*/
#RequestMapping(value = "/db", method = RequestMethod.GET)
public String dbs(Locale locale, Model model) {
ApplicationContext ctx = ContextLoader
.getCurrentWebApplicationContext();
DataSource ds = (DataSource) ctx.getBean("dataSource");
dbs = new DbImpl();
dbs.setDataSource(ds);
ArrayList<Db> dbList = dbs.getDatabases();
model.addAttribute("dbList", dbList);
return "dbs";
}
/**
* Simply shows ciao.
*/
#RequestMapping(value = "/ciao", method = RequestMethod.GET)
public String ciao(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 "ciao";
}
}
Move your bean declaration to your main application context, not the one where you have DispatcherServlet.