Spring MVC 3 + JSON - json

I'm trying to use Spring MVC with JSON. It works great when a return an object from the controller, but when I try to make an AJAX call passing a custom object as parameter I'm getting HTTP 415 error.
My spring-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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<tx:annotation-driven />
<context:annotation-config/>
<context:component-scan
base-package="com.sommer.controller" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan base-package="com.sommer.service" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<!-- ========= [ADDED FOR JSON SUPPORT] ========= -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="es"/>
</bean>
<bean id="handlerMapping"
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<ref bean="localeChangeInterceptor" />
</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/sommer"/>
<property name="username" value="root"/>
<property name="password" value="master"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="persistenceUnitName" value="sommerPersistenceUnit"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="MYSQL"
p:showSql="true"
p:generateDdl="true"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
My controller:
#RequestMapping(value="/editJSON2",headers={"content-type=application/json,application/xml,application/x-www-form-urlencoded"})
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit){
return new ActionResult(toEdit);
}
Classes:
public class ActionResult {
private Boolean success;
private String message;
private Object object;
public ActionResult(){
this.success = true;
this.object = null;
this.message = null;
}
public ActionResult(Boolean isSuccess,Object obj, String message){
this.success = isSuccess;
this.object = obj;
this.message = message;
}
public ActionResult(Object obj){
this.success = true;
this.object = obj;
this.message = "";
}
public ActionResult(String message){
this.success = false;
this.object = null;
this.message = message;
}
public void setError(String msg){
this.success = false;
this.message = msg;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
public class CustomerTO {
private Long id;
private String name;
private String email;
private TestObject[] items;
public TestObject[] getItems() {
return items;
}
public void setItems(TestObject[] items) {
this.items = items;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public DocumentType getDocumentType() {
return documentType;
}
public void setDocumentType(DocumentType documentType) {
this.documentType = documentType;
}
public String getDocumentNumber() {
return documentNumber;
}
public void setDocumentNumber(String documentNumber) {
this.documentNumber = documentNumber;
}
private String surname;
private String sex;
private DocumentType documentType;
private String documentNumber;
public CustomerTO() {
}
public CustomerTO(Customer customer) {
this.id = customer.getId();
this.documentNumber = customer.getDocumentNumber();
this.documentType = customer.getDocumentType();
this.name = customer.getName();
this.surname = customer.getSurname();
this.sex = Sex.MALE.equals(customer.getSex())?"M":"F";
this.email = customer.getEmail();
this.items = new TestObject[1];
TestObject tio = new TestObject();
tio.setText("ITEM !");
this.items[0] = tio;
}
My ajax call:
var currentCustomer = {
'id': $('#id').val()
,'name' :$('#name').val()
,'surname' :$('#surname').val()
,'documentType' :$('#documentType').val()
,'documentNumber' :$('#documentNumber').val()
,'sex' :$('#sex').val()
,'email' :$('#email').val()
};
// Send the request
$.post('editJSON2.html', {toEdit:currentCustomer}, function(response) {
alert('OK');
}, 'json');
The problem I think is here:
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit)
I think #ResquestBody is not working for me. I also have
#RequestMapping("/editJSON")
public #ResponseBody ActionResult editJSON(#RequestParam(required=false) Long customerId){
CustomerTO toEdit = customerId!=null ? new CustomerTO(customerService.getById(customerId)):new CustomerTO();
return new ActionResult(toEdit);
}
And when I call it I have no problem.
This is information I collected from firebug:
Parámetrosapplication/x-www-form-urlencoded
toEdit[documentNumber] 36466
toEdit[documentType] DNI
toEdit[email] jpruizmdq#hotmail.com
toEdit[id] 2
toEdit[name] John
toEdit[surname] Doe
Código fuente
toEdit%5Bid%5D=2&toEdit%5Bname%5D=John&toEdit%5Bsurname%5D=Doe&toEdit%5BdocumentType%5D=DNI&toEdit%5BdocumentNumber%5D=36466&toEdit%5Bemail%5D=jpruizmdq%40hotmail.com

It's no tot working because content type of your request is application/x-www-form-urlencoded
and it supposed to be application/json
try to send it with Jquery the following way:
$.ajax({
type: "POST",
url: "someurl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
}};

Thanks! Problem solved. Here is the code
#RequestMapping(value="/editJSON2")
public #ResponseBody ActionResult editJSON2(#RequestBody CustomerTO toEdit){
return new ActionResult(toEdit);
}
ajaxCall('editJSON2.html',JSON.stringify(currentCustomer),function(valor){
alert('OK');
});
function ajaxCall(url,data,callback,onError){
jQuery.ajax({
url:url
,dataType: 'json'
,data:data
,type: "POST"
,contentType: "application/json; charset=utf-8"
,success:function(actionResult){
-----------
}
,error:function(jqXHR, textStatus, errorThrown){
---
}
});
}
It was simple! I added contentType: "application/json; charset=utf-8" and i used JSON.stringify(currentCustomer). With that it worked

Related

Hibernate cannot create table when the entity annotation?

My web project ,spring spring-mvc and hibernate,when the tomcat start there is no tables created in mysql db. why? and no error info
the sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.woodcoder.bean</value>
</list>
</property>
</bean>
the properties
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false
and I tried hibernate.hbm2ddl.auto=create, it's the same.
Why hibernate doesn't create a table?
The Entity
#Entity
#Table(name="user_bean")
public class UserBean extends BaseBean {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
the baseEntity
#MappedSuperclass
public class BaseBean implements Serializable{
/**
* ID
*/
#Id
#Column(name="id",length = 32, nullable = true)
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid")
private String id;
#Column(updatable = false)
private Date createDate;
private Date modifyDate;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
yes,i got the problem.
in the hibernate config there are some space in the end of each line,although i cant see them.i delete these space,the table was created.
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=false

org.hibernate.AnnotationException: #OneToOne or #ManyToOne on ........ references unknown entity:

I am new to Spring-Hibernate technology facing issue while integrating Spring MVC with Hibernate for relationship of two classes. Below are the code:
The User class:
package com.MVCHibernate.Model;
import java.util.List;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "EMP_USERS")
public class UserModel {
#Id
#GeneratedValue
private int id;
private String username;
private String password;
private String role;
#OneToMany(mappedBy="emp_users")
private List<PermanentEmployeeModel> permanentEmployeeModel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<PermanentEmployeeModel> getPermanentEmployeeModel() {
return permanentEmployeeModel;
}
public void setPermanentEmployeeModel(List<PermanentEmployeeModel> permanentEmployeeModel) {
this.permanentEmployeeModel = permanentEmployeeModel;
}
}
The PermanentEmployeeModel class:
package com.MVCHibernate.Model;
import javax.persistence.*;
#Entity
#Table(name = "EMP_PERMANENT")
public class PermanentEmployeeModel{
#Id
#GeneratedValue
private int eid;
private int fname;
private int lname;
private int salary;
private String grade;
private int date;
// ManyToOne relationship
#ManyToOne
#JoinColumn(name = "id")
private UserModel emp_user;
public int getEid() {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public int getFname() {
return fname;
}
public void setFname(int fname) {
this.fname = fname;
}
public int getLname() {
return lname;
}
public void setLname(int lname) {
this.lname = lname;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public UserModel getEmp_user() {
return emp_user;
}
public void setEmp_user(UserModel emp_user) {
this.emp_user = emp_user;
}
}
employee-servlet.xml:
<context:component-scan base-package="com.MVCHibernate" />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/Files/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/EmployeeMVCHibernate" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.MVCHibernate.Model.UserModel</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<!-- PERMANENT EMPLOYEE -->
<bean id="sessionFactory1"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.MVCHibernate.Model.PermanentEmployeeModel</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- USER BEANS -->
<!-- <bean id="userDAOImpl" class="com.MVCHibernate.DAO.UserDAOImpl" /> -->
<bean id="userDAOImpl" class="com.MVCHibernate.DAO.UserDAOImpl">
<property name="sessionFactory" ref = "sessionFactory"></property>
</bean>
<bean id="userServiceImpl" class="com.MVCHibernate.Service.UserServiceImpl" />
<!-- EMPLOYEE BEANS -->
<!-- <bean id="pempDAOImpl" class="com.MVCHibernate.DAO.PermanentEmployeeDAOImpl" /> -->
<bean id="pempDAOImpl" class="com.MVCHibernate.DAO.PermanentEmployeeDAOImpl">
<property name="sessionFactory" ref = "sessionFactory1"></property>
</bean>
<bean id="pempServiceImpl" class="com.MVCHibernate.Service.PermanentEmployeeServiceImpl" />
While executing the code it shows the following error :
org.hibernate.AnnotationException: #OneToOne or #ManyToOne on ........
references unknown entity:......
No other solutions on stackoverflow worked for me so far.
Any idea whoat am i doing wrong?
This is working now.
Need to include the mapping resource into the employee-servlet.xml file
**<import resource="classpath*:hibernate.cfg.xml"/>**
hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="com.MVCHibernate.Model.UserModel"></mapping>
<mapping class="com.MVCHibernate.Model.PermanentEmployeeModel"></mapping>
</session-factory>
</hibernate-configuration>

Spring MVC with jdbc "table is not mapped"

So I´m trying to make an application with all http request get, put, post, delete.I'm making first a login with mysql and spring 3. So here I got this:
login.jsp:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="UsersLogin">
signup.jsp
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="Users">
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_2_0.xsd}"
version="2.0">
<persistence-unit name="punit">
</persistence-unit>
</persistence>
Here is my jpaContext.xml:
<context:annotation-config />
<jpa:repositories base-package="com.portuzona.repository" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="punit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
<entry key="hibernate.hbm2ddl.auto" value="validate" />
<entry key="hibernate.format_sql" value="true" />
</map>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<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/portuzona?autoReconnect=true&createDatabaseIfNotExist=true&" />
<property name="username" value="root" />
<property name="password" value="1234" />
</bean>
</beans>
com.portuzona.model
Users model:
#Entity
#Table(name="users")
public class Users {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
private String firstName;
#NotEmpty
private String lastName;
#NotEmpty
#Size(min=4, max=8)
private String password;
#NotEmpty
private String status;
#NotEmpty
#Email
private String emailAddress;
#NotNull
#Past
#DateTimeFormat(pattern="MM/dd/yyyy")
private Date dateOfBirth;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
USersLogin model:
public class UsersLogin {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
com.portuzona.service
public interface UsersService {
Users save(Users users);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
}
Implementation:
#Service("UsersService")
public class UsersServiceImpl implements UsersService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Users save(Users users) {
return usersRepository.save(users);
}
public boolean findByLogin(String userName, String password) {
Users stud = usersRepository.findByUserName(userName);
if(stud != null && stud.getPassword().equals(password)) {
return true;
}
return false;
}
public boolean findByUserName(String userName) {
Users use = usersRepository.findByUserName(userName);
if(use != null) {
return true;
}
return false;
}
}
com.portuzona.repository
#Repository("UsersRepository")
public interface UsersRepository extends JpaRepository<Users, Long> {
#Query("SELECT s FROM users s WHERE s.userName = :userName")
Users findByUserName(#Param("userName") String userName);
}
com.portuzona.controller
#Controller
#SessionAttributes("users")
public class UsersController {
#Autowired
private UsersService userService;
#RequestMapping(value="/signup", method=RequestMethod.GET)
public String signup(Model model) {
Users users = new Users();
model.addAttribute("users", users);
return "signup";
}
#RequestMapping(value="/signup", method=RequestMethod.POST)
public String signup(#Valid #ModelAttribute("users") Users users, BindingResult result, Model model) {
if(result.hasErrors()) {
return "signup";
} else if(userService.findByUserName(users.getUserName())) {
model.addAttribute("message", "User Name exists. Try another user name");
return "signup";
} else {
userService.save(users);
model.addAttribute("message", "Saved users details");
return "redirect:login.html";
}
}
#RequestMapping(value="/login", method=RequestMethod.GET)
public String login(Model model) {
UsersLogin usersLogin = new UsersLogin();
model.addAttribute("UsersLogin", usersLogin);
return "login";
}
#RequestMapping(value="/login", method=RequestMethod.POST)
public String login(#Valid #ModelAttribute("UsersLogin") UsersLogin usersLogin, BindingResult result) {
if (result.hasErrors()) {
return "login";
} else {
boolean found = userService.findByLogin(usersLogin.getUserName(), usersLogin.getPassword());
if (found) {
return "success";
} else {
return "failure";
}
}
}
}
I got this error when trying to access to /login or /signup where I have my .jsp with my forms:
sep 24, 2015 11:14:35 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Allocate exception for servlet usersHibernateServlet
org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [SELECT s FROM users s WHERE s.userName = :userName]
I have been with this for two days, looking for answers here but no kind of good results from my side... just gives me the same error, any idea?

Flex 4, Spring 3 BlazeDS4 mySQL dbcp query excecution

I've implemented the SpringFlex 1.5 with a connection to mySQL DB
and it works and retrieves data initially but when I enter an invalid
data that doesn't exist in my table the application seems to freeze
and not even entering valid data works after that and I need to
stop and start Tomcat again to get it working again
applicationContext.xml
<bean id="authToLeaveService" class="com.model.atl.AuthToLeaveServiceImpl">
<constructor-arg ref="dataSource" />
</bean>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://dxfcm:3306/wookie?autoReconnect=true&zeroDateTimeBehavior=convertToNull"/>
<property name="username" value="darth" />
<property name="password" value="vader" />
<property name="validationQuery" value="SELECT 1"/>
</bean>
MyView
<fx:Declarations>
<s:ChannelSet id="cs">
<s:AMFChannel url="http://localhost:8400/flexspring/messagebroker/amf"/>
</s:ChannelSet>
<s:RemoteObject id="atlRO" channelSet="{cs}" destination="authToLeaveService"/>
</fx:Declarations>
[Bindable]
private var job:AtlJob;
private function onEnter(event:FlexEvent):void
{
var token:AsyncToken = atlRO.findByBarcode(this.txtBarcode.text);
token.addResponder(new AsyncResponder(onResult, onFault));
}
private function onResult(event:ResultEvent, token:Object):void
{ job = event.result as AtlJob; }
private function onFault(event:FaultEvent, token:Object):void
{ }
<s:TextInput id="txtBarcode" x="23" y="60" width="218"
enter="onEnter(event)" maxChars="16"/>
AltJob.as
[Bindable]
[RemoteClass (alias="com.model.atl.AtlJob")]
public class AtlJob
{
public var barcode:String;
public var pieces:int;
public var customerName:String;
}
AtlJob.java
package com.model.atl;
public class AtlJob implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String barcode;
private String customerName;
private int pieces;
public AtlJob() { }
public AtlJob(String barcode, int pieces, String customerName) {
this.barcode = barcode;
this.customerName = customerName;
this.pieces= pieces;
}
Getters and Setters defined
#Service("authToLeaveService")
#RemotingDestination(channels = { "my-amf", "my-secure-amf" })
public class AuthToLeaveServiceImpl implements AuthToLeaveService {
private final DataSource dataSource;
public AuthToLeaveServiceImpl(DataSource dataSource) {
this.dataSource = dataSource; }
#RemotingInclude
public AtlJob findByBarcode(String barcode) {
AtlJob job = new AtlJob();
Connection con = null;
final String sql = "SELECT * FROM atl_job WHERE card_barcode = ?";
try {
con = this.dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, barcode);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
job.setBarcode(rs.getString("barcode"));
job.setPieces(rs.getInt("pieces"));
job.setCustomerName(rs.getString("customerName"));}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
if (con!=null) {try { con.close();
} catch (SQLException e) {
e.printStackTrace();
} }} return job; }
You are not throwing any exceptions if the record is not found like here
...
if (rs.next()) {
job.setBarcode(rs.getString("barcode"));
job.setPieces(rs.getInt("pieces"));
job.setCustomerName(rs.getString("customerName"));
}
// Put an else clause here and throw exception
else
{
throw new Exception("Record Not found");
}
Try showing caught exception in your faultMethod ..
private function onFault(event:FaultEvent, token:Object):void
{
//Handle Fault event here Put some Alert here
}

jQuery post can't get entity object as json

I need to get my 'Comment' (stored in DAO) object from my controller and display it in my JSP but every time I see the error message from the error block.
Why is this happenning and what should I do?
Logic of my code is the next:
After clicking on the 'Reply' button data from the form is sent to my controller.
Controller saves data in DB and returns 'Comment' entity.
I get this 'Comment' entity in my JSP page and use it for publishing on the page.
But I get the error msg from error block instead of msg from the success block.
Here is my form:
<form id="comment_${comment.getCommentId()}">
<textarea class="textarea" rows="10" name="text"></textarea>
<input type="hidden" name="bookId" value="${book.getBookId()}" />
<input type="hidden" name="parentId" />
<input type="hidden" name="commentId" value="${comment.getCommentId()}" /><br />
<input type="button" class="button" value="Reply" id="submit_${comment.getCommentId()}" onclick="ajaxsubmit(this.id)"/>
</form>
Here is my script:
<script type="text/javascript">
function ajaxsubmit(buttonId){
var formId = document.getElementById(buttonId).parentNode.id;
var dataString = $("#" + formId).serialize();
$.ajax( {
url: "ajaxcomment.htm",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
alert(data.getCommentAdded());
},
error: function() {
alert("error");
}
} );
}
Here is my controller
#RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
public #ResponseBody Comment ajaxcomment(
HttpServletRequest httpServletRequest,
#RequestParam(value = "bookId", required = false) Long bookId,
#RequestParam(value = "parentId", required = false) Long parentId,
#RequestParam(value = "commentId", required = false) Long commentId,
#RequestParam(value = "text", required = true) String text) {
String username = httpServletRequest.getRemoteUser();
User user = userDao.getUserByUsername(username);
Comment comment = new Comment();
// DAO logic
commentDao.addComment(comment);
return comment;
}
Here is my 'Comment' entity:
#Entity #Table(name = "COMMENT") public class Comment implements Serializable {
#Id
#GeneratedValue
#Column(name = "COMMENT_ID", nullable = false)
private Long commentId;
#Column(name = "COMMENT_TEXT", length = 512, nullable = true)
private String commentText;
#Column(name = "COMMENT_ADDED", length = 128, nullable = true)
#Temporal(TemporalType.TIMESTAMP)
private Date commentAdded;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#JoinColumn(name = "BOOK_ID")
private Book book;
#ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER)
#JoinColumn(name = "PARENT_ID")
private Comment parentComment;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "parentComment")
#OrderBy("commentAdded")
private Collection<Comment> subcomments;
public void setCommentText(String commentText) {
this.commentText = commentText;
}
public String getCommentText() {
return this.commentText;
}
// other getters and setters are public too
And 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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.demo"/>
<context:component-scan base-package="com.demo.service"/>
<context:annotation-config />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
<bean id="exceptionMessageAdapter"
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
<property name="messageConverters">
<list>
<!-- Support JSON -->
<ref bean="jacksonMessageConverter" />
</list>
</property>
</bean>
It might be that in your form you are setting values like value="${book.getBookId()}" instead of value="${book.bookId}".
In other words you have to use the expression language by referring to the name of the field in the bean (entity or whatever) rather than trying to use the getter for that field directly.
It works.
I've updated my controller method (handler):
#Autowired private DAOComment commentDao;
#RequestMapping(value = "ajaxcomment.htm", method = RequestMethod.POST)
public #ResponseBody String ajaxcomment(
HttpServletRequest httpServletRequest,
#RequestParam(value = "bookId", required = false) Long bookId,
#RequestParam(value = "parentId", required = false) Long parentId,
#RequestParam(value = "commentId", required = false) Long commentId,
#RequestParam(value = "text", required = true) String text) {
String username = httpServletRequest.getRemoteUser();
User user = userDao.getUserByUsername(username);
Comment comment = new Comment();
// DAO logic
commentDao.addComment(comment);
return "{\"id\":\"" + comment.getCommentId() + "\"," +
"\"username\":\"" + comment.getUser().getUsername() + "\"," +
"\"text\":\"" + comment.getCommentText() + "\"," +
"\"added\":\"" + comment.getFormattedDate() + "\"}";
}
I used \" instead of ' because JSON.parse() doesn't parse string like 'param':'value', "param":"value" only.
Updated script:
<script type="text/javascript">
function ajaxsubmit(buttonId, className){
var formId = document.getElementById(buttonId).parentNode.id;
var dataString = $("#" + formId).serialize();
$.ajax( {
url: "ajaxcomment.htm",
type: "post",
data: dataString,
dataType: "text",
success: function(data) {
var response = JSON.parse(data);
//This's it.
alert(response.id);
},
error: function() {
alert("Error has occured.");
}
} );
}
</script>