Receiving payload request and displaying it on a webpage using spring - java

First of all I'm new to Spring and tried my best to get this working. So this is my question.
I have a spring MVC project which is supposed to receive a request payload (JSON request) and display the payload body on a webpage. Please see my project content and the controller class below
#Controller
public class CallbackPayloadController {
public CallbackPayloadController() {
System.out.println("In controller class!!!!");
}
#RequestMapping(value = "/requestreceiver", consumes = "application/json", method = RequestMethod.POST)
public void receivePayload(#RequestBody String payload) {
System.out.println("In the controller method....");
System.out.println("Payload is : " + payload);
}
}
Now if I do a POST to http://localhost:8080/PayloadReceiver/requestreceiver/ using POSTMAN it says HTTP STATUS 404. My Json content that I am posting is
{
"key":"123"
}
My web.xml is as follows
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>PayloadReceiver</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>requestreceiver</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>requestreceiver</servlet-name>
<url-pattern>/requestreceiver.jsp</url-pattern>
<url-pattern>/requestreceiver.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
</web-app>
Second question is if I successfully receive the payload, how do I display the payload content on a new webpage?

Try to add the return statement to your method like this:
#RequestMapping(value = "/requestreceiver",consumes="...",method = RequestMethod.POST)
public String receivePayload(...)
...
return "requestreceiver";

Related

Writing to JSONobject through Restful Webservice

I am learning how to use Restful Webservice, i dont really know if my approach is good or totally wrong, so bear with me
I got a project structure, which look like this :
I want to by calling the right URL, save the string accordingly in Datum.Json
Here is my Java Class of the WebService :
package Rest;
#Path("/calendar")
public class CalendarTest {
public List<Date> dates;
#GET
#Path("/dates/get/")
#Produces(MediaType.APPLICATION_XML)
public List<Date> getUsers(){
return dates;
}
#PUT
#Path("/dates/put/{param1}+{param2}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public void updateDate(#PathParam("param1") String city, #PathParam("param2") String date) throws IOException {
JSONObject obj = new JSONObject();
obj.put("City", city);
obj.put("Date", date);
try (FileWriter file = new FileWriter("/RestTest/Datum.json")) {
file.write(obj.toJSONString());
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
}
}
I tested the localhost, it works fine (i can open the form.html with my localhost)
My web.xml file :
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Restful Web Application</display-name>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>Rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<security-constraint>
</security-constraint>
</web-app>
But when i tried the URL http://localhost:8080/RestTest/rest/calendar/dates/put/Berlin+20-12-2019
It says the method not allowed.
Can anyone explain to me why ?
It's because when you are typing in a URL in your browser, it sends a HTTP GET request by default, so it throws an error because you do not have a GET request handler for that URL, you only have a handler for a PUT request.
You can't change the browser's default request type. What you have to do is send the request yourself using something like jQuery in your frontend / javascript.
How to send a PUT/DELETE request in jQuery?
You could use the ajax method:
$.ajax({
url: '/rest/calendar/dates/put/Berlin+20-12-2019',
type: 'PUT',
success: function(result) {
// Do something with the result
}
});

jaxrs - Unable to call the webservice : 404 Not Found Error

I have created a simple webservice but I am unable to call it. I get 404 Not found error.
package com.fms.mdw.rest;
#Path("/Search")
public class SearchWebService {
#POST
#Path("/searchData")
#Consumes(MediaType.APPLICATION_JSON)
#Produces("application/json")
public FMSResponseInfo getSearchData(SearchDTO searchDTO) {
System.out.println("Entered the getSearchData()");
FMSResponseInfo fmsResponseInfo = new FMSResponseInfo();
List<SearchDetailsDTO> searchDetailsDtoList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
SearchDetailsDTO searchDetailsDto = new SearchDetailsDTO();
searchDetailsDto.setBarcode("barcode" + i);
searchDetailsDto.setDocNo("docNo" + i);
searchDetailsDto.setDocType("docType" + i);
searchDetailsDtoList.add(searchDetailsDto);
}
fmsResponseInfo.setStatus("200");
fmsResponseInfo.setMessage("Success");
fmsResponseInfo.setData(searchDetailsDtoList);
System.out.println("Leaving the getSearchData()");
return fmsResponseInfo;
}
}
SearchDTO has two fields searchType, searchText both of type string.So the json payload will be {"searchType":"", "searchText":""}
I have registered the webservice in the following manner in web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
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_3_0.xsd">
<display-name>LatestFMS</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LatestFMS Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.fms.mdw.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>LatestFMS Web Application</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
I am able to access the webpages, but I am unable to call the webservice. I am using RESTClient to send post request. The web server is apache tomcat 7 and jersey 2.16 .
The url I am hitting is http://localhost:8082/LatestFMS/rest/Search/searchData.
I am unable to resolve the issue, please help ! ! !

Rest Jersey does not consume POST Request Payload JSON object

This is my ajax code, here I send json object as Request payload.
$(document).ready(function() {
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var address = $("#address").val();
$("#studentInsert").click(function() {
student.presonal_details = {
firstName: $("#firstName").val(),
lastName: $("#lastName").val(),
address: $("#address").val(),
}
$.ajax({
type: "post",
url: "http://localhost:8080/RestJersey/rest/jsonRequestReceiver/saveStudentDeta il",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(student.presonal_details),
success: function(data) {
console.log(data);
}
});
});
});
Java Code:
I want to know how do I write REST service API code for receiving the json Object.
#POST
#Path("/saveStudentDetail")
#Consumes(MediaType.APPLICATION_JSON)
public void saveStudentDetail() {
}
This is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>RestJersey</display-name>
<welcome-file-list>
<!-- <welcome-file>index1.html</welcome-file> -->
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey-servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jersey-servlet</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
And may POJO class:
package com.rest.test.to;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class StudentDetailsTO {
private String firstName;
private String lastName;
private String address;
// getters and setters
}
Use below code
#POST
#Path("/saveStudentDetail")
#Consumes(MediaType.APPLICATION_JSON)
public void saveStudentDetail(StudentDetailsTO student){
String fname= student.getFirstName();
String lname= student.getLastName();
String address= student.getAddress();
}

#RequestMapping in spring not working

I am new in Spring MVC. I created one controller newController.java in springproject. My code is below:
#RequestMapping(value = "/Receiver", method = RequestMethod.GET)
public void recvHttpGet(Model model) {
System.out.println("here get");
newmethod();
}
#RequestMapping(value = "/Receiver", method = RequestMethod.POST)
public void recvHttpPost(Model model) {
System.out.println("here post");
newmethod();
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String show(Model model) {
return "index";
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>ClassPath:/spring/applicationContext.xml, ClassPath:/spring/hibernateContext.xml</param-value>
</context-param>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
whenever I try to run it then index.jsp page is shown but whenever I try to call /Receiver url it shows a 404 error. Please help me. Also when I changed in recvHttpGet method return "index" it also shows a 404 error. Also nothing is wrote to the console.
I wants to just check which method calls so wants to write in console window but it does not show anything.
You need to return a JSP page, just like return "index";
If you have a receiver.jsp page in views, then...
#RequestMapping(value = "/Receiver", method = RequestMethod.GET)
public String recvHttpGet(Model model) {
return "receiver";
}

How to use #RequestMapping headers?

I am studying springmvc. When I use #RequestMapping(value="/helloWorld", headers = "content-type=text/*") and connect to http://localhost:8080/SpringMVC_10100/helloWorld, the following is output in the console:
WARN
org.springframework.web.servlet.PageNotFound
- No matching handler method found for servlet request: path '/helloWorld',
method 'GET', parameters
map[[empty]]
My code is:
#Controller
public class HelloWordController {
private Logger logger = LoggerFactory.getLogger(HelloWordController.class);
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
public ModelAndView helloWorld() {
logger.debug("jin ru le");
logger.info("The helloWorld() method is use");
ModelAndView view = new ModelAndView();
view.setViewName("/helloworld");
return view;
}
}
web.xml is
<servlet>
<description>This is Spring MVC DispatcherServlet</description>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<description>SpringContext</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC DispatchServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Why?
Its most likely the case that /helloworld is not inside the path configured for your dispatcher servlet
e.g. If i have a servlet configured like so:
<servlet>
<servlet-name>BMA</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>BMA</servlet-name>
<url-pattern>/bma/*</url-pattern>
</servlet-mapping>
And i have a controller configured like so:
#RequestMapping(value = "/planner/plan/{planId}/delete", method = RequestMethod.GET)
public ModelAndView deletePlanConfirm(HttpServletRequest request,
#PathVariable("planId") Long planId) {}
Then the request in browsder would be:
http://localhost:8080/bma/planner/plan/1223/delete
Edit:
Also if you have content-type header narrowing on your handler, make sure that content-type haeder is sent in your request.
In the below annotation remove the headers:
#RequestMapping(value="/helloWorld", headers = "content-type=text/*")
to:
#RequestMapping(value="/helloWorld", method = RequestMethod.GET)
or to:
#RequestMapping(value="/helloWorld")
should make it work.

Categories