Error executing JSON based Restful WCF Service - json

I am trying to write a json based restful WCF service. When i execute it using RestSharp i get a null response with the following Error in the ErrorException and the ErrorMessage.
Data at the root level is invalid. Line 1, position 1.
Status Code is BadRequest
The data object is created as
[DataContract]
public class User
{
[DataMember]
public string first_name { get; set; }
[DataMember]
public string last_name { get; set; }
[DataMember]
public string email_address { get; set; }
[DataMember]
public List<UserAddress> Address; //do not serialize this in the data contract
}
[DataContract]
public class UserAddress
{
[DataMember]
public string line_1_address { get; set; }
[DataMember]
public string state { get; set; }
[DataMember]
public string PostalArea { get; set; }
}
The service code is
[ServiceContract]
public interface IUserService
{
[OperationContract]
User AddUser(User user);
}
public class UserService : IUserService
{
[WebInvoke(Method = "PUT",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "User/")]
public User AddUser(User user)
{
return new User();
}
}
The service is hosted in a Web App.
I have a c# client based on RestSharp
static void Main(string[] args)
{
User u = new User();
u.first_name = "testFirst";
u.last_name = "testLast";
UserAddress ua = new UserAddress();
ua.line_1_address = "line 1";
ua.PostalArea = "08648";
ua.state = "NJ";
u.Address = new List<UserAddress>();
u.Address.Add(ua);
RestSharp.RestClient client = new RestSharp.RestClient("http://localhost/TestWCHHost/User.svc");
var request = new RestRequest(String.Format("User/"), Method.PUT);
request.RequestFormat = DataFormat.Json;
request.AddObject(u);
var response = client.Execute<User>(request);
}
The web config changes are as
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<!-- User Service -->
<service name="TestService.UserService" behaviorConfiguration="serviceBehavior">
<endpoint address="" binding="webHttpBinding" contract="TestService.IUserService" behaviorConfiguration="web">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
To browse web app root directory during debugging, set the value below to true.
Set to false before deployment to avoid disclosing web app folder information.
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
Unable to figure whats going on. Any clues.

Related

Hibernate & MySql empty data

I'm trying to make an interface for my database created in MySQL Workbench, and i can't simply view the data from any table. I can add a client, and then it appears on Workbench, but not in .jsp file. What am i missing ?
pojo.Clienti
package pojo;
import java.util.HashSet;
import java.util.Set;
public class Clienti implements java.io.Serializable {
private Integer idclient;
private String nume_institutie_firma;
private String cod_unic;
private String adresa;
private Set angajats = new HashSet(0);
public Clienti() {
}
public Clienti(String nume_institutie_firma, String cod_unic, String adresa, Set angajats) {
this.nume_institutie_firma = nume_institutie_firma;
this.cod_unic = cod_unic;
this.adresa = adresa;
this.angajats = angajats;
}
public Integer getIdclient() {
return this.idclient;
}
public void setIdclient(Integer idclient) {
this.idclient = idclient;
}
public String getnume_institutie_firma() {
return this.nume_institutie_firma;
}
public void setnume_institutie_firma(String nume_institutie_firma) {
this.nume_institutie_firma = nume_institutie_firma;
}
public String getcod_unic() {
return this.cod_unic;
}
public void setcod_unic(String cod_unic) {
this.cod_unic = cod_unic;
}
public String getAdresa() {
return this.adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
public Set getAngajats() {
return this.angajats;
}
public void setAngajats(Set angajats) {
this.angajats = angajats;
}
}
pojo.Clienti.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pojo.Clienti" table="clienti" catalog="tema"
optimistic-lock="version">
<id name="idclient" type="java.lang.Integer">
<column name="idclient" />
<generator class="identity" />
</id>
<property name="nume_institutie_firma" type="string">
<column name="nume_institutie_firma" length="45" />
</property>
<property name="cod_unic" type="string">
<column name="cod_unic" length="45" />
</property>
<property name="adresa" type="string">
<column name="adresa" length="45" />
</property>
<set name="angajats" table="angajati" inverse="true"
lazy="true" fetch="select">
<key>
<column name="idclient" />
</key>
<one-to-many class="pojo.Angajati" />
</set>
</class>
</hibernate-mapping>
*hibernate.cfg.xml*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tema</property>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">pass</property>
<mapping resource="pojo/Angajati.hbm.xml"/>
<mapping resource="pojo/Clienti.hbm.xml"/>
<mapping resource="pojo/Proiecte.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernate.reveng.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
<schema-selection match-catalog="tema"/>
<table-filter match-name="proiecte"/>
<table-filter match-name="clienti"/>
<table-filter match-name="angajati"/>
</hibernate-reverse-engineering>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>ClientiController</servlet-name>
<servlet-class>Controller.ClientiController</servlet-class>
</servlet>
<servlet>
<servlet-name>ProiecteController</servlet-name>
<servlet-class>Controller.ProiecteController</servlet-class>
</servlet>
<servlet>
<servlet-name>AngajatiController</servlet-name>
<servlet-class>Controller.AngajatiController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientiController</servlet-name>
<url-pattern>/ClientiController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProiecteController</servlet-name>
<url-pattern>/ProiecteController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AngajatiController</servlet-name>
<url-pattern>/AngajatiController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
DAO.ClientiDao
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.util.List;
import pojo.Clienti;
/**
*
* #author vali
*/
public interface ClientiDao {
public void adaugaClienti (Clienti client);
public List<Clienti> afiseazaClienti();
public void modificaClienti (int idclient, String nume_institutie_firma, String cod_unic, String adresa);
public void stergeClient (Clienti client);
}
DAOImpl.ClientiDaoImpl
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAOImpl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Clienti;
import DAO.ClientiDao;
/**
*
* #author vali
*/
public class ClientiDaoImpl implements ClientiDao{
public void adaugaClienti(Clienti client) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.save(client);
transaction.commit();
session.close();
}
public List<Clienti> afiseazaClienti() {
List<Clienti> listaClienti = new ArrayList();
Session session = HibernateUtil.getSessionFactory().openSession();
org.hibernate.Query query = session.createQuery("From Clienti");
listaClienti = query.list();
return listaClienti;
}
public void modificaClienti(int idclient, String nume_institutie_firma, String cod_unic, String adresa) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
Clienti detaliiclienti = (Clienti) session.load(Clienti.class, idclient);
detaliiclienti.setnume_institutie_firma(nume_institutie_firma);
detaliiclienti.setcod_unic(cod_unic);
detaliiclienti.setAdresa(adresa);
session.update(detaliiclienti);
transaction.commit();
session.close();
}
public void stergeClient(Clienti client) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
session.delete(client);
transaction.commit();
session.close();
}
}
Controller.ClientiController
package Controller;
import DAO.ClientiDao;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import pojo.Clienti;
import DAOImpl.ClientiDaoImpl;
/**
*
* #author vali
*/
public class ClientiController extends HttpServlet {
Clienti client = new Clienti();
ClientiDaoImpl clientDaoImpl = new ClientiDaoImpl();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("adaugaClient") != null) {
String nume_institutie_firma = request.getParameter("nume_institutie_firma");
String cod_unic = request.getParameter("cod_unic");
String adresa = request.getParameter("adresa");
client.setnume_institutie_firma(nume_institutie_firma);
client.setcod_unic(cod_unic);
client.setAdresa(adresa);
clientDaoImpl.adaugaClienti(client);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getParameter("afiseazaClienti") != null) {
List<Clienti> listaClienti = new ArrayList();
listaClienti = clientDaoImpl.afiseazaClienti();
request.setAttribute("listaClienti", listaClienti);
RequestDispatcher rd = request.getRequestDispatcher("tabela_Clienti.jsp");
rd.forward(request, response);
}
if (request.getParameter("modificaClient") != null) {
int id1 = Integer.parseInt(request.getParameter("idclient"));
String nume_institutie_firma = request.getParameter("nume_institutie_firma");
String cod_unic = request.getParameter("cod_unic");
String adresa = request.getParameter("adresa");
clientDaoImpl.modificaClienti(id1, nume_institutie_firma, cod_unic, adresa);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
if (request.getParameter("stergeClient") != null) {
int id2 = Integer.parseInt(request.getParameter("idclient"));
client.setIdclient(id2);
clientDaoImpl.stergeClient(client);
RequestDispatcher rd = request.getRequestDispatcher("adauga_Client.jsp");
rd.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

HTTP Status 500 - Servlet.init() for servlet management threw exception

Emp.java
package com.management;
public class Emp {
private int id;
private String name;
private float salary;
private String designation;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
}
EmpController.java
package com.management;
import java.util.ArrayList;
import java.util.List;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.management.Emp;
import com.management.EmpDao;
#Controller
public class EmpController {
#Autowired
EmpDao dao;//will inject dao from xml file
/*It displays a form to input data, here "command" is a reserved request attribute
*which is used to display object data into form
*/
#RequestMapping("/empform")
public ModelAndView showform(){
return new ModelAndView("empform","command",new Emp());
}
/*It saves object into database. The #ModelAttribute puts request data
* into model object. You need to mention RequestMethod.POST method
* because default request is GET*/
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Emp emp){
dao.save(emp);
return new ModelAndView("redirect:/viewemp");//will redirect to viewemp request mapping
}
/* It provides list of employees in model object */
#RequestMapping("/viewemp")
public ModelAndView viewemp(){
List<Emp> list=dao.getEmployees();
return new ModelAndView("viewemp","list",list);
}
/* It displays object data into form for the given id.
* The #PathVariable puts URL data into variable.*/
#RequestMapping(value="/editemp/{id}")
public ModelAndView edit(#PathVariable int id){
Emp emp=dao.getEmpById(id);
return new ModelAndView("empeditform","command",emp);
}
/* It updates model object. */
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("emp") Emp emp){
dao.update(emp);
return new ModelAndView("redirect:/viewemp");
}
/* It deletes record for the given id in URL and redirects to /viewemp */
#RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable int id){
dao.delete(id);
return new ModelAndView("redirect:/viewemp");
}
}
EmpDao.java
package com.management;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.management.Emp;
public class EmpDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public int save(Emp p){
String sql="insert into Emp99(name,salary,designation) values('"+p.getName()+"',"+p.getSalary()+",'"+p.getDesignation()+"')";
return template.update(sql);
}
public int update(Emp p){
String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()+", designation='"+p.getDesignation()+"' where id="+p.getId()+"";
return template.update(sql);
}
public int delete(int id){
String sql="delete from Emp99 where id="+id+"";
return template.update(sql);
}
public Emp getEmpById(int id){
String sql="select * from Emp99 where id=?";
return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowMapper<Emp>(Emp.class));
}
public List<Emp> getEmployees(){
return template.query("select * from Emp99",new RowMapper<Emp>(){
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
}
});
}
}
servlet-management.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.spring" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://loclahost:3306/test1" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="dao" class="com.spring.EmpDao">
<property name="template" ref="jt"></property>
</bean>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>management</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>management</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
hi
my trying to insert the value to the database by using the spring-mvc.
and using the mysql database.
while execution process it shows the error like that-org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.spring.EmpDao] for bean with name 'dao' defined in ServletContext resource [/WEB-INF/management-servlet.xml]; nested exception is java.lang.ClassNotFoundException: com.spring.EmpDao .
please provide the soluation.
thank you.

Spring with REST

I am learning Spring framework. I have created a sample project with SpringMVC with REST + JSON. I can able to compile successfully but when i hit the rest url, the system says below message
org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Below is the springmvc-servlet.xml
<context:component-scan base-package="com.springmvc.beans" />
<context:annotation-config />
<mvc:annotation-driven />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter" />
</list>
</property>
</bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>
And the Web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
And the EmployeeController.java
package com.springmvc.beans;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class EmployeeController {
public static final String GET_EMPLOYEE = "/rest/employee/{empId}";
public static final String CREATE_EMPLOYEE = "/rest/employee/create/";
public static final String DELETE_EMPLOYEE = "/rest/employee/delete/{empId}";
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
private Map<String, Employee> employeeData = new HashMap<String, Employee>();
private Integer count = 1;
#RequestMapping(method=RequestMethod.GET, value=GET_EMPLOYEE)
public #ResponseBody Employee getEmployee(#PathVariable ("empId") String empId){
return employeeData.get(empId);
}
#RequestMapping(method=RequestMethod.PUT, value=CREATE_EMPLOYEE)
public #ResponseBody void createEmployee(){
employeeData.put(String.valueOf(count++), new Employee(String.valueOf(count++), "Batman"+Math.random(), "23"+Math.random(), "Andartica"+Math.random(), "dash2#gmail.com"+Math.random()));
}
#RequestMapping(method=RequestMethod.PUT, value=DELETE_EMPLOYEE)
public #ResponseBody void deleteEmployee(#PathVariable ("empId") String empId){
employeeData.remove(empId);
}
#RequestMapping(method=RequestMethod.GET, value=GET_ALL_EMPLOYEES)
public #ResponseBody Map<String, Employee> getAllEmployees(){
return employeeData;
}
{
employeeData.put(String.valueOf(count), new Employee("1", "Mani", "31", "America", "Dash#gmail.com"));
}
}
Finally the Employee.java pojo
package com.springmvc.beans;
/**
* #author Mani
*
*/
public class Employee {
private String empId;
private String name;
private String age;
private String address;
private String email;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Employee(String empId, String name, String age, String address, String email) {
super();
this.empId = empId;
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
}
Note : My Spring version is 4.1 and I have added below jars in my classpath to convert output to JSON message
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
Kindly help to solve this.
Thanks in Advance
Manivannan
looking at the code the endpoint is mapped to
public static final String GET_ALL_EMPLOYEES = "/rest/employee/";
where as the url being accessed is
/SpringMVC/rest/employee
org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/SpringMVC/rest/employee] in DispatcherServlet with name 'springmvc'.
Try making as below:
GET_ALL_EMPLOYEES = "/rest/employee";

MVC not returning json... request not available

Hi all I want to return a userName with a rest http request in Spring + Mysql.
Controller:
#Controller
#SessionAttributes("user")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUserName(#PathVariable String userName) {
return userName;
}
}
Model:
#Entity
#Table(name="users")
public class User {
#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;
}
}
I just want to retrieve my services put,delete,post and get with requestmappings connecting with my model to my mysql DB. I´m trying to make the request in this way:
http://localhost:8080/portuzona/userss?userName=Arnoldo
But I get this:
HTTP Status 404 - /portuzona/userss
type Status report
message /portuzona/userss
description The requested resource is not available.
portuzona and userss is correctly handled (html views) but I cannot make a get in my controllers.
Log says correctly the Table has been found by the bean:
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: portuzona.users
sep 25, 2015 2:07:22 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [dateofbirth, password, firstname, emailaddress, id, username, lastname, status]
As a User requested here is more info that could be help .. or not:
/WEB-INF/servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>usersHibernateServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/servletConfig.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>usersHibernateServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/jpaContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Archetype Created Web Application</display-name>
</web-app>
/WEB-INF/config/servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.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-3.2.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.portuzona" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
</beans>
Looks like you're mixing up mapping and path variables. Two options:
1:
#RequestMapping(method=RequestMethod.GET, value="/userss/{userName}")
public #ResponseBody String getUname(#PathVariable String userName) {
return userName;
}
http://localhost:8080/portuzona/userss/Arnoldo
2:
#RequestMapping(method=RequestMethod.GET, value="/userss/yourmapping")
public #ResponseBody String getUserName(#RequestParam String username) {
return username;
}
http://localhost:8080/portuzona/userss/yourmapping?username=Arnoldo
Try the following with http://localhost:8080/portuzona/userss?userName=Arnoldo
#RequestMapping(method=RequestMethod.GET, value="/userss")
public #ResponseBody String getUserName(#RequestParam String userName) {
return userName;
}

How can I send a DataContract object as parameter for a WCF RESTFUL webservice?

I am developing a WCF resful service which will be basically consumed from some mobile applications.
Over the POST I am trying to send a DataContract object [actually I have to send a List of object] and another single id as string. My question is if it is possibly to define my function to accept DataContract object and the single string ?
Following is my code :
Interface declaration:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetDataUsingDataContract/{id}")]
CompositeType GetDataUsingDataContract(string id, CompositeType composite );
}
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
Actual definition of the function:
public CompositeType GetDataUsingDataContract(string id, CompositeType composite )
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite .BoolValue)
{
composite .StringValue += "- Suffix and the id is"+id;
}
return report;
}
and the json object I am trying to send from Fiddler is
{"BoolValue":true,"StringValue":"sdfsdfsf"}
Above are the snaps from the fiddler I am testing the service from.
After couple of googling I have got the following link where the client actually uses webservice reference to get the DataContract type and serializes to json before sending as request body. But why then my test from Fiddler doesn't succeed ?!
https://geeksarray.com/blog/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract
Can anybody please suggest anything ?
The web.config is as bellow:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="JSONWebService.Service1" behaviorConfiguration="JSONWebService.Service1Behavior">
<endpoint address="../Service1.svc"
binding="webHttpBinding"
contract="JSONWebService.IService1"
behaviorConfiguration="webBehaviour" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="JSONWebService.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
There's a couple of things you need to do to get this scenario to work.
First, in the service contract, you need to mark the method that has multiple parameters with the BodyStyle parameter of the WebInvoke attribute set to Wrapped as shown in this example (adapted from the sample you linked to at http://dotnetmentors.com/wcf/wcf-rest-service-to-get-or-post-json-data-and-retrieve-json-data-with-datacontract.aspx):
[OperationContract]
[WebInvoke(UriTemplate = "/PlaceOrder",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped)]
bool PlaceOrder(string id, OrderContract order);
With this attribute parameter in place you have to wrap the multiple web method parameters into a single string in your client. The following example shows a way of doing this in C#:
var requestdata = new
{
id = order.OrderID,
order = order
};
string data2 = JsonConvert.SerializeObject(requestdata);
Note that the field names in the anonymous method match the parameter names in your web method.
For reference, the JSON that this produces looks like this where you can see the id and order objects in the JSON string:
{"id":"10560","order":{"OrderID":"10560","OrderDate":"06/09/2013 12:29:04","ShippedDate":"16/09/2013 12:29:04","ShipCountry":"Uganda","OrderTotal":"781"}}
You should be able to test out JSON in this format in Fiddler with your example.
Extending the answer to deal with other datatypes
Using a DataContract that includes a bool and a DateTime property:
[DataContract]
public class OrderContract
{
[DataMember]
public string OrderID { get; set; }
[DataMember]
public string OrderDate { get; set; }
[DataMember]
public string ShippedDate { get; set; }
[DataMember]
public string ShipCountry { get; set; }
[DataMember]
public string OrderTotal { get; set; }
[DataMember]
public bool Shipped { get; set; }
[DataMember]
public DateTime DeliveredDate { get; set; }
}
The issue here is dealing with the DateTime and making sure that the JSON is in a format that the WCF RESTful service can deserialize. To get this to work I used this code on the client:
OrderContract order = new OrderContract
{
OrderID = "10560",
OrderDate = DateTime.Now.ToString(),
ShippedDate = DateTime.Now.AddDays(10).ToString(),
ShipCountry = "India",
OrderTotal = "781",
Shipped = true,
DeliveredDate = DateTime.Now
};
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(OrderContract));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, order);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
var requestdata = new
{
id = order.OrderID,
order = order
};
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
};
string data2 = JsonConvert.SerializeObject(requestdata, microsoftDateFormatSettings);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString("http://localhost:61966/OrderService.svc/PlaceOrder", "POST", data2);
Note the JSON Serializer settings - this produces the following JSON:
{"id":"10560","order":{"OrderID":"10560","OrderDate":"10/09/2013 16:15:30","ShippedDate":"20/09/2013 16:15:30","ShipCountry":"India","OrderTotal":"781","Shipped":true,"DeliveredDate":"\/Date(1378826130655+0100)\/"}}