Return from doPost() in JSP - java

I am trying to implement REST type architecture without using any framework. So I am basically calling a JSP from my client end which is doing a doPost() on to the remote server providing services. Now I am able to pass the data from client to server in JSON format but I don know how to read the response. Can someone help me out with this.
Client Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
....
HttpPost httpPost = new HttpPost("http://localhost:8080/test/Login");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//Send post it as a "json_message" paramter.
postParameters.add(new BasicNameValuePair("json_message", jsonStringUserLogin));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse fidresponse = client.execute(httpPost);
....
....
}
Server Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsonStringUserLogin = (String)request.getParameter("json_message");
....
....
request.setAttribute("LoginResponse", "hello");
// Here I need to send some string back to the servlet which called. I am assuming
// that multiple clients will be calling this service and do not want to use
// RequestDispatcher as I need to specify the path of the servlet.
// I am looking for more like return method which I can access through
// "HttpResponse" object in the client.
}
I just started with servlets and wanted to implement a REST service by myself. If you have any other suggestion please do share... Thank You,

in doPost you simply have to do :
response.setContentType("application/json; charset=UTF-8;");
out.println("{\"key\": \"value\"}"); // json type format {"key":"value"}
and this will return json data to client or servlet..
reading returned data using jquery ajax ...
on client side using jquery do the following :
$.getJSON("your servlet address", function(data) {
var items = [];
var keys= [];
$.each(data, function(key, val) {
keys.push(key);
items.push(val);
});
alert(keys[0]+" : "+items[0]);
});
on servlet you know how to read json data

After you executed the post you can ready the response like this.
HttpEntity entity = fidresponse.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String l = null;
String rest = "";
while ((l=br.readLine())!=null) {
rest=rest+l;
}
Here rest will contain your json response string.
You can also use StringBuffer.

Related

Java Servlet send form data to REST API

I have a simple HTML form to send a request to a REST API. It works well, when I submit, it sends the form data to API and displays the response in the browser.
<form name="theForm" action="localhost:8080/App/rest/consumeForm" method="post">
<input name="userName" value="Bob Smith" /><br/>
<input type="submit" value="submit"/>
</form>
Browser shows:
{"address": "12 First St.", "city": "Toronto"}
I would like to capture the response. Any ideas? (no ajax or javascript, just plain old Servlet or JSP please)
PART 2:
I now POST my form to a servlet I created, which handles the request and response from the REST API. It works nicely, but it needs the form data URLEncoded. Anyone know if there is a way to convert form data to such a string, or even convert form data to JSON directly?
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String userName = "Bob Smith";
String country = "Canada";
String queryString = String.format("userName=%s&country=%s"
,URLEncoder.encode(userName, charset)
,URLEncoder.encode(country, charset)
);
Can I build the above queryString dynamically?
//// send request
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(queryString.getBytes(charset));
}
//// get response
BufferedReader apiResponse = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("\n\n\nrecieved....");
while ((output = apiResponse.readLine()) != null) {
System.out.println(output);
}
I would like to capture the response. Any ideas?
Install a servlet Filter that handles this. When it receives a request for the REST API endpoint, it can feed an HttpServletResponse to the next element in the chain that is equipped with any tooling you want. You would probably find HttpServletResponseWrapper to be a useful base class for your custom-tooled response class.
The Filter implementation might be along these lines:
public class ResponseCapturingFilter implements Filter {
private static final String SERVLET_TO_FILTER = "...";
#Override
public void init(ServletConfig config) {
// ...
}
#Override
public void destroy() {
// ...
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (((HttpServletRequest) request).getServletPath().equals(SERVLET_TO_FILTER)) {
response = new MyCapturingResponseWrapper(response);
}
chain.doFilter(request, response);
}
}
To capture the response text, you would want your wrapper to override at least getOutputStream() and getWriter() appropriately.
It turns out that submitting to a servlet using POST and communicating with the REST API using the servlet works for me. There may be better ways, but this seems relatively clean for junior developers to follow and maintain. (I'm still open to other options).
I build a queryString with the form data (req is the HttpServletRequest)
String theQueryString="domainId=1";
for(Entry<String, String[]> qsParm:req.getParameterMap().entrySet()) {
theQueryString+="&"+qsParm.getKey()+"="+URLEncoder.encode(req.getParameter(qsParm.getKey()), charset);
}
// set up connection to use as API interaction
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST apparently
connection.setRequestProperty("Accept-Charset", java.nio.charset.StandardCharsets.UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + java.nio.charset.StandardCharsets.UTF_8.name());
// send request to API via connection OutputStream
try (OutputStream output = connection.getOutputStream()) {
output.write(theQueryString.getBytes(java.nio.charset.StandardCharsets.UTF_8.name())); // this sends the request to the API url
}
// get response from connection InputStream and read as JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonMap = mapper.readTree(connection.getInputStream());
// now the response can be worked with in at least two ways that I have tried
String user1 = jsonMap.get("userName").asText();
String user2 = jsonMap.at("user").getValueAsText();

how to send data from servlet to rest api

I want to send data from my servlet to a rest api .
Is it how it's done :
protected void doPost(
HttpServletRequest request
, HttpServletResponse response
) throws ServletException, IOException {
String Id= "MyId";
response.setContentType("application/json");
response.getWriter().write(Id);
getServletContext()
.getRequestDispatcher("<PathofAPI>")
.forward(request, response);
}
And once the data is send how to retreive it in my rest api
Alternatively you must create POJO class for you Id parameter with getters and setters:
String createRequestUrl="YOUR_LINK WHERE_YOU GET answer FROM";
RestTemplate template=new RestTemplate();
your_POJO_object.setYour_Pojo_Object(Id);
ObjectMapper objectMapper = new ObjectMapper();
MultiValueMap<String, String> orderRequestHeaders=new
LinkedMultiValueMap<String,String>();
orderRequestHeaders.add("Content-Type", "application/json");
orderRequestHeaders.add("Accept", "application/json");
String orderCreateRequest=objectMapper.writeValueAsString(YOUR POJO object.class);
HttpEntity<String> orderRequest=new HttpEntity<String>(orderCreateRequest, orderRequestHeaders);
String response=template.postForObject(createRequestUrl, orderRequest, String.class);
What you want to acheive is a bit unclear to me.
By writing "MyId" to the response before letting "PathofServet" process the request, you're breaking the json format in the response.
Have you an exemple of what the servlet "PathofServlet", expects as request and send as response ? And what you would like your servlet to response ?

Does a HttpServlet have to respond to a request?

I have several servlets that do things server side. On a few I just encode some unnecessary data and send it back, which seems pointless. Do you have to respond ? What happens when you just say return ? I've done that before and nothing seems to go wrong but I am relatively new to servlets. Are there consequences for simply returning that go above my head ? And what exactly happens when you return;
if(request.getParameter("name").equals("saveusedcards")) {
String sessId = request.getSession().getId();
//encode request with confirmation that cards were successfully updated
if(usersUpdatedCards.get(sessId).isEmpty()){
//no cards were seen
}
boolean success = DataDAO.updateCards(usersUpdatedCards.get(sessId));
if(success){
System.out.println("Data base update successfull!");
String responseMessage = new Gson().toJson("card successfully udpated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
} else {
System.out.println("Data base update failed...");
String responseMessage = new Gson().toJson("card was not successfully updated");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
System.out.println("updated cards response message: "+responseMessage);
response.getWriter().write(responseMessage);
return;
}
}
The servlet must produce an HTTP response for the client, however it is perfectly acceptable to return no content in the response body. When doing so your servlet should make this clear to the client by sending a response code of 204 (no content). Reference: https://httpstatuses.com/204
Here is an example of how you would set the response code from the doGet method. You could do the same from doPost or service methods.
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// Do whatever work you need to do here...
res.setStatus(HttpServletResponse. SC_NO_CONTENT); // This returns a 204
}

How can I recover the value after recovering control in a servlet?

I am trying to include several servlets in the main servlet to get finish some processs and retrieve values. In this example, I am receiving the control from a jsp file to the main servlet. After this servlet send call to the next servlet to carry out an operation related to a Java List and after returns the control to the main servlet. However, I am not able to recover the value of this List. How can I recover values from servlets that I am calling from the main servlet? The part of source code is the next:
(Main Servlet)
DeletePolicy.java:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
//create an object of RequestDispatcher
RequestDispatcher rd = request.getRequestDispatcher("GetPolicy");
// send the client data available with req of delete to req of getPolicy with include()
rd.include(request, response);
// To receive the parameter from the second servlet
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
printWriter.print("List of books in Delete: ");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
printWriter.print("I am comming back in Delete to send a request to Delete method");
/*ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
delete(ClientResponse.class,input);
printWriter.print("Delete a policy");*/
}
/* Include solution provided by Jozef Chocholacek: request.setAttribute("policies", policies);
GetPolicy.java(Second Servlet):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter printWriter = response.getWriter();
Client client= Client.create();
WebResource webResource= client.resource("http://localhost:8080/clientLibrary/webapi/policy");
printWriter.println("<u>Searching for current policies...</u><br>");
ClientResponse rs=webResource.accept(
MediaType.APPLICATION_JSON_TYPE,
MediaType.APPLICATION_XML_TYPE).
get(ClientResponse.class);
//ClientResponse rs = webResource.type(MediaType.APPLICATION_JSON).delete(ClientResponse.class,input);
/*Transform json to java object*/
String jsonPolicy=rs.getEntity(String.class);
Gson gson = new Gson();
Policy[] PolicyA = gson.fromJson(jsonPolicy, Policy[].class);
List<Policy> policies = Arrays.asList(PolicyA);
for(Policy policy : policies) {
System.out.println(policy.getId()+" "+policy.getMax_books()+", "+policy.getYear_book()+", "+policy.getActivate()+", ");
}
//Send List to the servlet that is calling
request.setAttribute("policies", policies);
/*Display book list in the servlet*/
printWriter.println("<h1>List of Policies</h1>");
if (policies.isEmpty()){
printWriter.println("<html><body>Sorry, we did not have any policy"+"<br>");
}else{
printWriter.println("<html><body>The complete list of policies: <br>");
printWriter.println("<ul>");
for(Policy policy : policies) {
printWriter.println("<li>"+"ID: "+policy.getId()+"<br>"+"Max Number of Books: "+policy.getMax_books()+"<br>"+"Year of Book: "+policy.getYear_book()+"<br>"+"Activated: "+policy.getActivate()+"<br></li><br>");
}
}
printWriter.println("</body></html>");
}
Thank you in advance
Cheers
Well, in your first servlet (DeletePolicy.java) you use
List<Policy> policies = (List<Policy>) request.getAttribute("policies");
but the second servlet (GetPolicies.java) does not store this list into request. You have to add
request.setAttribute("policies", policies);
into your second servlet.

How to send and catch parameter from JavaScript (AJAX request) to Servlet

I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5

Categories

Resources