Order of object fields in spring boot rest api response changes - java

I have following model class:
package com.restAPIExmaple;
public class ApiModel {
private String City;
private String TeamName;
private String QBName;
public ApiModel() {
}
public ApiModel(String city, String teamName, String qBName) {
City = city;
TeamName = teamName;
QBName = qBName;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getTeamName() {
return TeamName;
}
public void setTeamName(String teamName) {
TeamName = teamName;
}
public String getQBName() {
return QBName;
}
public void setQBName(String qBName) {
QBName = qBName;
}
}
Here is the service class:
package com.restAPIExmaple;
import java.util.List;
import org.springframework.stereotype.Service;
import java.util.Arrays;
#Service
public class ApiService {
private List <ApiModel> score = Arrays.asList(
new ApiModel("Jacksonville","Jaguars","Gardner Minshew"),
new ApiModel("Tempa Bay", "Buccaneer", "Tom Brady"),
new ApiModel("San Fran", "49rs", "Jimmy Garoppolo"),
);
public List<ApiModel> getScores()
{
return score;
}
public ApiModel getTeam(String team){
return score.stream().filter(t -> t.getTeamName().equalsIgnoreCase(team)).findFirst().get();
}
}
The Controller is as below:
package com.restAPIExmaple;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
#RestController
#RequestMapping("/football")
public class ApiController {
#Autowired
private ApiService apiService;
#GetMapping(value = "/scores", produces = {MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE})
public List<ApiModel> getScores(){
return apiService.getScores();
}
#GetMapping(value="/{team}", produces = {MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE})
public ApiModel getTeam(#PathVariable String team){
return apiService.getTeam(team);
}
}
Here is the response in xml:
<List>
<item>
<teamName>Jaguars</teamName>
<city>Jacksonville</city>
<qbname>Gardner Minshew</qbname>
</item>
<item>
<teamName>Buccaneer</teamName>
<city>Tempa Bay</city>
<qbname>Tom Brady</qbname>
</item>
<item>
<teamName>49rs</teamName>
<city>San Fran</city>
<qbname>Jimmy Garoppolo</qbname>
</item>
</List>
Problem: The order of the object properties has been changed in the out put. I cant get City, Team name , QBname in that order order in the response. When I generate getter and setter using Eclipse, the order of the fields there is different from the model class as well. Any idea? Thank you.

start variable name with simple letters. that's the case

Related

Update and Delete error in Spring-boot and mongo db CRUD application

I am trying to create a CRUD application using Spring-boot and Mongo DB.
I am getting error the in the update and delete operations
During Delete, there is a timestamp error showing and on update a new object is getting created instead of updating the existing object. I have attached the controller and service layer codes.
Can anyone please find a solution for this.
Controller Layer
package com.springrest.springrest.controller;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.springrest.springrest.entities.Course;
import com.springrest.springrest.services.CourseService;
#CrossOrigin
#RestController
#RequestMapping("/api")
public class MyController {
#Autowired
private CourseService courseService;
#GetMapping("/courses")
public ResponseEntity<?> getCourses(){
return ResponseEntity.ok(this.courseService.GetCourses());
}
#PostMapping("/courses")
public ResponseEntity<?> addCourse(#RequestBody Course course)
{
Course save=this.courseService.addCourse(course);
return ResponseEntity.ok(save);
}
#GetMapping("/courses/{courseId}")
public ResponseEntity<?> getCourse(#PathVariable String courseId ){
Optional<Course> save=this.courseService.getCourse(Integer.parseInt(courseId));
return ResponseEntity.ok(save);
}
#PutMapping("/courses/{courseId}")
public ResponseEntity<?> updateCourse(#PathVariable String courseId,
#RequestBody Course course)
{
Optional<Course> save=Optional.ofNullable(this.courseService.updateCourse(Integer.parseInt
(courseId),course));
return ResponseEntity.ok(save);
}
#DeleteMapping("/courses/{courseId}")
public void deleteCourse(#PathVariable String courseId)
{
this.courseService.deleteCourse(Integer.parseInt(courseId));
//return ResponseEntity.ok(this.courseService.deleteCourse(Integer.parseInt(courseId)));
}
}
Service Layer
package com.springrest.springrest.services;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springrest.springrest.entities.Course;
import com.springrest.springrest.repository.CourseRepository;
#Service
public class CourseServiceimpl implements CourseService
{
#Autowired
private CourseRepository userlist;
public List<Course> GetCourses() {
return this.userlist.findAll();
}
public Course addCourse(Course course) {
return this.userlist.save(course);
}
public Optional<Course> getCourse(int courseId)
{
Optional<Course> c=this.userlist.findById(courseId);
return c;
}
#Override
public Course updateCourse(int courseId, Course course)
{
Course c=this.userlist.findById(courseId).get();
c.setId(course.getId());
c.setTitle(course.getTitle());
c.setDescription(course.getDescription());
return this.userlist.save(c);
}
#Override
public void deleteCourse(int courseId)
{
//Course c= this.userlist.findById(courseId).get();
this.userlist.deleteById(courseId);
}
}
Entity Layer
package com.springrest.springrest.entities;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
#Document(collection="Course")
public class Course {
#Field( name="id")
private int id;
#Field(name="title")
private String title;
#Field(name="description")
private String description;
public Course(int id, String title, String description) {
super();
this.id = id;
this.title = title;
this.description = description;
}
public Course() {
super();
}
#Override
public String toString() {
return "Course [id=" + id + ", title=" + title + ", description=" + description + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the error I am getting on a Delete Request
{
"timestamp": "2022-11-09T18:45:58.630+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/api/courses/147"
}
Are you getting an error in get and save operations? Because although you inject CourseService in controller, you did not override get and save operations methods in CourseServiceimpl class.

Spring-Data Project is not receiving my Get/Post "404 not found"

I finished creating a simple Spring-boot project in which I can enter users and through the Get command it returns me the name (from a list of identical names) with the oldest entry date. Unfortunately, every time I ask for Get it returns this ERROR:
D:\>curl -G localhost:8080/demo/first?=Biagio
{"timestamp":"2020-10-04T22:46:35.996+00:00","status":404,"error":"Not Found","message":"","path":"/demo/first"}
And to each of my POST / Add requests like this ERROR:
D:\>curl localhost:8080/demo/add -d name=Giovanni -d email=giovanni#gmail.com -d surname=Jackie
{"timestamp":"2020-10-04T22:40:51.928+00:00","status":404,"error":"Not Found","message":"","path":"/demo/add"}
Below I enter the interested parties of my project to try to get something out of it, because I have been stuck for days now
AccessingDataMysqlApplication.java
package com.example.accessingdatamysql;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
public class AccessingDataMysqlApplication {
public static void main(String[] args) {
SpringApplication.run(AccessingDataMysqlApplication.class, args);
}
}
MainController.java
package com.example.accessingdatamysql.rest;
import javax.persistence.NoResultException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.service.UserService;
#RestController
#RequestMapping("/demo")
public class MainController {
#Autowired
private UserService userService;
#Transactional
//#RequestMapping(value = "/add/", method = RequestMethod.POST)
#PostMapping(path="/demo/add")
public String addNewUser(#PathVariable("name") String name, #PathVariable("email") String email,
#PathVariable("surname") String surname) {
UserDto n = new UserDto();
n.setName(name);
n.setSurname(surname);
n.setEmail(email);
userService.create(n);
return "User Saved in DB";
}
#SuppressWarnings({ "rawtypes", "unchecked" })
//#RequestMapping(value = "/fetchUser/{name}", method = RequestMethod.GET)
#GetMapping("/demo/first")
public ResponseEntity<UserDto> fetchUser(#PathVariable("name") String name) {
System.out.println(name);
try {
UserDto namefound = userService.findFirstByName(name);
System.out.println("Name found");
ResponseEntity<UserDto> user = new ResponseEntity<UserDto>(namefound, HttpStatus.OK);
return user;
} catch(NoResultException ne) {
System.out.println("User not found");
return new ResponseEntity("User not found with name : " + name, HttpStatus.NOT_FOUND);
}
}
}
UserService.java
package com.example.accessingdatamysql.service;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
#Service
public interface UserService {
UserDto findFirstByName(String name);
void create(UserDto user);
}
UserServiceImpl.java
package com.example.accessingdatamysql.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
import com.example.accessingdatamysql.util.UserMapper;
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
UserMapper mapper;
#Override
public UserDto findFirstByName(String name) {
UserEntity entity = userRepository.findFirstByName(name);
return mapper.toDtoMapper(entity);
}
#Override
public void create(UserDto user) {
UserEntity entity = mapper.toEntityMapper(user);
userRepository.create(entity);
}
}
UserMapper.java
package com.example.accessingdatamysql.util;
import org.mapstruct.Mapper;
import com.example.accessingdatamysql.model.UserDto;
import com.example.accessingdatamysql.model.UserEntity;
#Mapper(componentModel = "spring")
public interface UserMapper {
public UserEntity toEntityMapper (UserDto user);
public UserDto toDtoMapper (UserEntity userEntity);
}
UserRepository.java
package com.example.accessingdatamysql.repo;
import org.springframework.stereotype.Repository;
import com.example.accessingdatamysql.model.UserEntity;
#Repository
public interface UserRepository {
UserEntity findFirstByName(String name);
void create(UserEntity entity);
}
UserRepositoryImpl.java
package com.example.accessingdatamysql.service;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Component;
import com.example.accessingdatamysql.model.UserEntity;
import com.example.accessingdatamysql.repo.UserRepository;
#Component
public class UserRepositoryImpl implements UserRepository {
private final EntityManager em;
public UserRepositoryImpl(EntityManager entityManager) {
this.em = entityManager;
}
#Override
public UserEntity findFirstByName(String name) {
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<UserEntity> criteria = builder.createQuery(UserEntity.class);
Root<UserEntity> root = criteria.from(UserEntity.class);
criteria.select(root).where(builder.equal(root.get("name"), name));
criteria.orderBy(builder.asc(root.get("timestamp")));
TypedQuery<UserEntity> query = em.createQuery(criteria).setMaxResults(1);
return query.getSingleResult();
}
#Override
// per la creazione//
public void create(UserEntity entity) {
em.persist(entity);
}
}
UserDto.java
package com.example.accessingdatamysql.model;
import java.io.Serializable;
import java.sql.Timestamp;
public class UserDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -7621330660870602403L;
/**
*
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
private Timestamp timestamp;
private String email;
private String surname;
}
If you need I can also insert User.java and the pom, but the pom has no problems as the dependencies are all correct.
You have an additional demo in your path descriptions for GET and POST methods, you should remove it:
#GetMapping("/demo/first")
#PostMapping(path = "/demo/first")
It should be :
#GetMapping("/first")
#PostMapping(path = "/first")
This because you have already defined demo in the RequestMapping annotation in the class level.

GraphQL query Invalid syntax error while testing on Postman. Springboot server

The springboot application exposes the graphql API on the endpoint "localhost:8091/rest/books". When I test it with Postman passing the query in the body as graphQL type it gives error "Invalid Syntax", whereas when I pass the same query as raw text, it yields correct results. I'm using HSQL. The structure of my application is:
The files with their code respectively are:
Book.java
package com.techprimers.graphql.springbootgrapqlexample.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
//#AllArgsConstructor
//#NoArgsConstructor
#Setter
#Getter
#Table
#Entity
public class Book {
#Id
private String isn;
public Book() {
super();
}
public Book(String isn, String title, String publisher, String[] authors, String publishedDate) {
super();
this.isn = isn;
this.title = title;
this.publisher = publisher;
this.authors = authors;
this.publishedDate = publishedDate;
}
public String getIsn() {
return isn;
}
public void setIsn(String isn) {
this.isn = isn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String[] getAuthors() {
return authors;
}
public void setAuthors(String[] authors) {
this.authors = authors;
}
public String getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
private String title;
private String publisher;
private String[] authors;
private String publishedDate;
}
BookRepository.java
package com.techprimers.graphql.springbootgrapqlexample.repository;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookRepository extends JpaRepository<Book, String> {
}
BookResource.java
package com.techprimers.graphql.springbootgrapqlexample.resource;
import com.techprimers.graphql.springbootgrapqlexample.service.GraphQLService;
import graphql.ExecutionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#CrossOrigin(origins = "http://localhost:3000")
#RequestMapping("/rest/books")
#RestController
public class BookResource {
#Autowired
GraphQLService graphQLService;
#PostMapping
public ResponseEntity<Object> getAllBooks(#RequestBody String query) {
ExecutionResult execute = graphQLService.getGraphQL().execute(query);
return new ResponseEntity<>(execute, HttpStatus.OK);
}
}
AllBooksDataFetcher.java
package com.techprimers.graphql.springbootgrapqlexample.service.datafetcher;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import com.techprimers.graphql.springbootgrapqlexample.repository.BookRepository;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public class AllBooksDataFetcher implements DataFetcher<List<Book>>{
#Autowired
BookRepository bookRepository;
#Override
public List<Book> get(DataFetchingEnvironment dataFetchingEnvironment) {
return bookRepository.findAll();
}
}
BookDataFetcher.java
package com.techprimers.graphql.springbootgrapqlexample.service.datafetcher;
import com.techprimers.graphql.springbootgrapqlexample.model.Book;
import com.techprimers.graphql.springbootgrapqlexample.repository.BookRepository;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class BookDataFetcher implements DataFetcher<Book>{
#Autowired
BookRepository bookRepository;
#Override
public Book get(DataFetchingEnvironment dataFetchingEnvironment) {
String isn = dataFetchingEnvironment.getArgument("id");
return bookRepository.findById(isn).get();
}
}
And in the resources folder is
Books.graphql (contains schema)
schema {
query: Query
}
type Query {
allBooks: [Book]
book(id: String): Book
}
type Book {
isn: String
title: String
publisher: String
authors: [String]
publishedDate: String
}

Why does java springboot print an empty json in the browser?

The Java Rest Api prints on http://localhost:8080/books
[{},{},{}]
instead of the booklist object. I use a main method a book_controller and a book model. Firstly I add a couple of books in the list in the method getbooks() and then I return them as a list.
Why does this happen?
application.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
#SpringBootApplication (exclude = SecurityAutoConfiguration.class)
public class Lab6NosApplication {
public static void main(String[] args) {
SpringApplication.run(Lab6NosApplication.class, args);
}
}
Book_controller.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import ch.qos.logback.classic.Logger;
import net.minidev.json.JSONArray;
#Controller
public class Book_controller implements ErrorController, Serializable {
#GetMapping("books")
public #ResponseBody List<book> getbooks() {
List<book> bookList = new ArrayList<book>();
bookList.add(new book(1,"lokesh","gupta"));
bookList.add(new book(2,"lokesh","gupta"));
bookList.add(new book(3,"lokesh","gupta"));
java.lang.System.out.print(bookList);
return bookList;
}
#RequestMapping("/error")
#ResponseBody
public String handleError(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
return String.format("<html><body><h2>Error Page</h2><div>Status code: <b>%s</b></div>"
+ "<div>Exception Message: <b>%s</b></div><body></html>",
statusCode, exception==null? "N/A": exception.getMessage());
}
#Override
public String getErrorPath() {
return "/error";
}
}
Book.java
public class Book {
public Book(Integer id, String title, String author) {
super();
this.id = id;
this.title = title;
this.author = author;
}
private Integer id;
private String title;
private String author;
//getters and setters
#Override
public String toString() {
return "Employee [id=" + id + ", title=" + title
+ ", author=" + author + "]";
}
}
Thank you!
You see it empty because your Book class doesn't have public getters or properties, so the serializer won't be able to access it's values.
Add getters to your Book class:
public Integer getId(){
return this.id;
}
public String getTitle(){
return this.title;
}
public String getAuthor(){
return this.author;
}
You can also improve your code, with better naming such as BookController instead of Book_controller. Have a look at java naming conventions.
Finally, take a look at a #RestController. If you use #RestController, you don't need to have #ResponseBody

Getting internal server error - #XmlRootElement

I have this Model class:
package org.myapp.model;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name="Message")
#XmlAccessorType(XmlAccessType.FIELD)
public class Message {
public long id;
public String message;
public Date created;
public String author;
public Message() {
}
public Message(long id,String message, String author) {
this.id = id;
this.message = message;
this.author = author;
this.created = new Date();
}
#XmlElement
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
#XmlElement
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
#XmlElement
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
The Service Class:
package org.myapp.services;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.myapp.model.Message;
public class MessageService {
public List<Message> getAllMessages(){
Message msg1 = new Message(1L,"How are you?", "natalie");
Message msg2 = new Message(2L,"How are you?", "amir");
List<Message> msglist = new ArrayList<Message>();
msglist.add(msg1);
msglist.add(msg2);
return msglist;
}
}
The Resource Class:
package org.myapp.resource;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.myapp.model.Message;
import org.myapp.services.MessageService;
#Path("messageresource")
public class MessageResource {
MessageService messageService = new MessageService();
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Message> getMessage() {
return messageService.getAllMessages(); //"app chal rhi hai!";
}
#GET
#Produces(MediaType.APPLICATION_XML)
#Path("/{messageId}")
public String getMessageID(#PathParam("messageId") String messageId) {
Message message = new Message(1L,"How are you?", "natalie");
return message.getMessage()+", "+messageId;
}
}
I am trying to print the data in Service(MessageService) class in an XML format. I think, the error is being caused because the return value of this class' method (return type List<Message>) and the tag #XMLRootElement on the top of the Model (Message) class are not consistent. I tried different MediaType properties but nothing helped.
When I am accessing this path : localhost:8080/messengerapp/webapi/messageresource
I am getting this error - Internal Server Error
I have just started to learn to write web services.I have tried different ways to get around this problem but nothing is helping me. Please help me understand and solve this.
try with this,
annotate the root element of xml
#XmlRootElement (name="Messages")
public class MessageService implements Serializable{
private List<Message> msglist = new ArrayList<Message>();
public List<Message> getAllMessages(){
Message msg1 = new Message(1L,"How are you?", "natalie");
Message msg2 = new Message(2L,"How are you?", "amir");
msglist.add(msg1);
msglist.add(msg2);
return msglist;
}
public void setAllMessages(List<Message> msglist){
this.msglist = msglist;
}
}
structure of the xml
<Messages> <!-- root element of xml -->
<Message>
...
</Message>
<Message>
...
</Message>
</Messages>

Categories