Flex 4, Spring 3 BlazeDS4 mySQL dbcp query excecution - mysql

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
}

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

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?

calling rest api in spring

I am having rest method in spring controller like below:
#RequestMapping(value="/register/{userName}" ,method=RequestMethod.GET)
#ResponseBody
public String getUserName(HttpServletRequest request,#PathVariable String userName ){
System.out.println("User Name : "+userName);
return "available";
}
In jquery I have writeen ajax call like:
$(document).ready(function(){
$('#userName').blur(function(){
var methodURL = "http://localhost:8085/ums/register/"+$('#userName').val();
$.ajax({
type : "get",
URL : methodURL,
data : $('#userName').val(),
success : function(data){
alert(data);
$('#available').show();
}
})
});
});
In web.xml I have:
<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>
In spring-servlet.xml I have the view resolver like below:
<context:component-scan base-package="com.users.controller" />
<context:annotation-config />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="text/xml" />
<entry key="htm" value="text/html" />
</map>
</property>
<property name="ignoreAcceptHeader" value="true" />
<!-- <property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />-->
<property name="defaultContentType" value="text/html" />
</bean>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
When I am running this in server, it is not going to controller.
Please let me know the problem with this code.
Please can any one help on this.
Regards,
Shruti
Since you have the #RequestMapping(value="register/{userName}" on your method definition, your jquery call must follow the same syntax.
var methodURL = "http://localhost:8085/users/register/"+$('#userName').val()+".html";
But you have also a problem in your RequestMapping value, it should start with /
#RequestMapping(value="/register/{userName}"
Also I doubt that you need the ".html" at the end
Add this line to your spring-servlet.xml. It will enable the Web MVC specific annotations like #Controller and #RequestMapping
<mvc:annotation-driven />
Example of an annotated controller
Assuming the url with context is http://localhost:8080/webapp and you want an api call like url /users/register/johnDoe. (johnDoe being the username)
You controller class would look something like the following.
#Controller
#RequestMapping(value="/users")
class UserController {
#ResponseBody
#RequestMapping(value="/register/{username}", method=RequestMethod.GET)
public String registerUser(#PathVariable String username) {
return username;
}
}
Please find my solution for calling REST web-services in Spring Framework.
/**
* REST API Implementation Using REST Controller
* */
#RestController
public class RestReqCntrl {
#Autowired
private UserService userService;
#Autowired
private PayrollService payrollService;
//-------------------Create a User--------------------------------------------------------
#RequestMapping(value = "/registerUser", method = RequestMethod.POST)
public ResponseEntity<User> registerUser(#RequestBody User user, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.registerUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerUser").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.CREATED);
}
//-------------------Authenticating the User--------------------------------------------------------
#RequestMapping(value = "/authuser", method = RequestMethod.POST)
public ResponseEntity<User> authuser(#RequestBody User user,UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating User " + user.getFirstName());
boolean flag = userService.authUser(user);
if (flag)
{
user.setStatusCode(1);
user.setStatusDesc("PASS");
}else{
user.setStatusCode(0);
user.setStatusDesc("FAIL");
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/authuser").buildAndExpand(user.getFirstName()).toUri());
return new ResponseEntity<User>(user,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Company--------------------------------------------------------
#RequestMapping(value = "/registerCompany", method = RequestMethod.POST)
public ResponseEntity<String> registerCompany(#RequestBody ComypanyDTO comypanyDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating comypanyDTO " + comypanyDTO.getCmpName());
String result ="";
boolean flag = payrollService.registerCompany(comypanyDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Create a Employee--------------------------------------------------------
#RequestMapping(value = "/registerEmployee", method = RequestMethod.POST)
public ResponseEntity<String> registerEmployee(#RequestBody EmployeeDTO employeeDTO, UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("Creating registerCompany " + employeeDTO.getEmpCode());
String result ="";
boolean flag = payrollService.registerEmpbyComp(employeeDTO);
if (flag)
{
result="Pass";
}else{
result="Fail";
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand(result).toUri());
return new ResponseEntity<String>(result,headers, HttpStatus.ACCEPTED);
}
//-------------------Get Company Deatils--------------------------------------------------------
#RequestMapping(value = "/getCompanies", method = RequestMethod.GET)
public ResponseEntity<List<ComypanyDTO> > getCompanies(UriComponentsBuilder ucBuilder) throws Exception {
System.out.println("getCompanies getCompanies ");
List<ComypanyDTO> comypanyDTOs =null;
comypanyDTOs = payrollService.getCompanies();
//Setting the Respective Employees
for(ComypanyDTO dto :comypanyDTOs){
dto.setEmployeeDTOs(payrollService.getEmployes(dto.getCompanyId()));
}
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/registerCompany").buildAndExpand("LISt").toUri());
return new ResponseEntity<List<ComypanyDTO>>(comypanyDTOs,headers, HttpStatus.ACCEPTED);
}
}
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="USER_TABLE")
public class User implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String lastName;
private String email;
private String userId;
private String password;
private String userType;
private String address;
#Transient
private int statusCode;
#Transient
private String statusDesc;
public User(){
}
public User(String firstName, String lastName, String email, String userId, String password, String userType,
String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.userId = userId;
this.password = password;
this.userType = userType;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* #return the userType
*/
public String getUserType() {
return userType;
}
/**
* #param userType the userType to set
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* #return the address
*/
public String getAddress() {
return address;
}
/**
* #param address the address to set
*/
public void setAddress(String address) {
this.address = address;
}
/**
* #return the statusCode
*/
public int getStatusCode() {
return statusCode;
}
/**
* #param statusCode the statusCode to set
*/
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
/**
* #return the statusDesc
*/
public String getStatusDesc() {
return statusDesc;
}
/**
* #param statusDesc the statusDesc to set
*/
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}

Jackson JSON Views ignored

I am trying to use Jackson2.0.0 with Spring3.1 so that I can use the jackson-Module-Hibernate. I have followed the steps as described here http://blog.pastelstudios.com/2012/03/12/spring-3-1-hibernate-4-jackson-module-hibernate/. All this seems to work fine, but when I try using JSON Views so that the JSON contains only the fields in the view it does not work.
The active view is always null. How do make the view active? I have tried for a day now with no luck...any help at all will be greatly appreciated. Thanks in advance.
Below is the relavant code.
Here is the Mapper
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module;
public class HibernateAwareObjectMapper extends ObjectMapper {
public HibernateAwareObjectMapper() {
Hibernate4Module hm = new Hibernate4Module();
registerModule(hm);
hm.configure(Hibernate4Module.Feature.FORCE_LAZY_LOADING, true);
}
}
Here is the view class
public class DiffViews {
public static class Public { }
}
Here is the POJO where I use the view
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#id")
#JsonIgnoreProperties(ignoreUnknown=true)
#Entity
public class Premium implements java.io.Serializable {
#JsonView(DiffViews.Public.class)
private String sequence;
#JsonView(DiffViews.Public.class)
#Column(name = "SEQUENCE", nullable = false, length = 4)
public String getSequence() {
return this.sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
)
In my spring controller
#RequestMapping("/cartonPremium")
public void listAll(
#RequestParam("page") int page, #RequestParam("rows") int maxResults,
#RequestParam("sidx") String sortKey, #RequestParam("sord") String sortOrder, HttpServletResponse response) {
HibernateAwareObjectMapper mapper = new HibernateAwareObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.enable(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS);
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION );
JqgridResponse<Premium> gridResponse = new JqgridResponse<Premium>();
gridResponse.setRows(premiumList);
gridResponse.setRecords(""+premiumList.size());
gridResponse.setTotal(""+premiumList.size());
gridResponse.setPage(""+page);
try {
ObjectWriter objWriter= mapper.writerWithView(DiffViews.Public.class);
Class<?> xxx = mapper.getSerializationConfig().getActiveView();
objWriter.writeValue(response.getOutputStream(), gridResponse);
//mapper.writerWithView(DiffViews.Public.class).writeValue(response.getOutputStream(), gridResponse);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
My spring config
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="com.creata.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="com.creata.json.HibernateAwareObjectMapper" />
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
I have finally found my error... I was returning my domain POJO in a wrapper called JqgridResponse and I had not added the #JsonView annotation on the fields in this wrapper class. So all is good the json view is not getting ignored.

Spring MVC 3 + 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