I want to create an application that will fetch a JSON object from a servlet to deserialize it, and then use its variables to do other things.
My servlet has the following code in the doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ObjectOutputStream os;
os = new ObjectOutputStream(response.getOutputStream());
String s = new String("A String");
Gson gson = new Gson();
String gsonObject= gson.toJson(s);
os.writeObject(gsonObject);
os.close();
}
Now, while the servlet is running, I can access it via a browser, if I post same code in the doGet method, that would download a servlet file, which is not what I want.
What should I use in my second application that would connect to the servlet, fetch the object, so that I can manipulate it later?
Thanks in advance.
You need few changes in your servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = new String("A String");
String json = new Gson().toJson(s);
this.response.setContentType("application/json");
this.response.setCharacterEncoding("UTF-8");
Writer writer = null;
try {
writer = this.response.getWriter();
writer.write(json);
} finally {
try {
writer.close();
}
catch (IOException ex) {
}
}
}
If its downloading the servlet file instead of showing it in the browser , most probably you have not set the content type in the response. If you are writing a JSON string as the servlet response , you have to use
response.setContentType("text/html");
response.getWriter().write(json);
Please note the order , its "text/html" and not "html/text"
IfI understood the question correctly then you can use, java.net.HttpURLConnection and java.net.URL objects to create a connection to this servlet and read the JSON streamed by the above JSON servlet in your second servlet.
Related
I am trying to use jsp and java to display information read from a csv to a website. I'm using Tomcat v9.0 with Eclipse.
The java code works as expected when running it just in java—it reads the csv data into an ArrayList of Song objects. However, when running the jsp file, it throws a filenotfoundexception.
The original java code reads and parses the csv in the getter function of "ReadBillboardCSV" here:
public ArrayList<BillboardSong> getReadBillboardCSV() throws FileNotFoundException {
Reader in = new FileReader("testFile.csv");
ArrayList<BillboardSong> readSongs = new ArrayList<BillboardSong>();
try {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
BillboardSong newSong = new BillboardSong();
readSongs.add(newSong);
newSong.setPosition(Integer.parseInt(record.get(0)));
My servlet calls the getter, then sets the attribute.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession ses = request.getSession(true);
ReadBillboardCSV readData = new ReadBillboardCSV();
ArrayList<BillboardSong> songsArray = readData.getReadBillboardCSV();
ses.setAttribute("billboardArray", songsArray);
}
Here is the main portion of the jsp:
<%
RequestDispatcher rd = request.getRequestDispatcher("/ServletOne");
rd.forward(request, response);
%>
Is there a reason it cannot read the file when I run it on Tomcat?
I have an applet and I must send a request to a web application to get data from the server that is in a database. I am working with objects and it is very useful that the server responses me with objects!!
How an applet can communicate with a server?
I think web services method, RMI and... make me happy, but which is the best and reliable?
As long as its only your applet communicating with the server you can use a serialized object. You just need to maintain the same version of the object class in both the applet jar and on the server. Its not the most open or expandable way to go but it is quick as far as development time and pretty solid.
Here is an example.
Instantiate the connection to the servlet
URL servletURL = new URL("<URL To your Servlet>");
URLConnection servletConnect = servletURL.openConnection();
servletConnect.setDoOutput(true); // to allow us to write to the URL
servletConnect.setUseCaches(false); // Write the message to the servlet and not from the browser's cache
servletConnect.setRequestProperty("Content-Type","application/x-java-serialized-object");
Get the output stream and write your object
MyCustomObject myObject = new MyCustomObject()
ObjectOutputStream outputToServlet;
outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
outputToServlet.writeObject(myObject);
outputToServlet.flush(); //Cleanup
outputToServlet.close();
Now read in the response
ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream());
MyRespObject myrespObj;
try
{
myrespObj= (MyRespObject) in.readObject();
} catch (ClassNotFoundException e1)
{
e1.printStackTrace();
}
in.close();
In your servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
MyRespObject myrespObj= processSomething(request);
response.reset();
response.setHeader("Content-Type", "application/x-java-serialized-object");
ObjectOutputStream outputToApplet;
outputToApplet = new ObjectOutputStream(response.getOutputStream());
outputToApplet.writeObject(myrespObj);
outputToApplet.flush();
outputToApplet.close();
}
private MyRespObject processSomething(HttpServletRequest request)
{
ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream());
MyCustomObject myObject = (MyCustomObject) inputFromApplet.readObject();
//Do Something with the object you just passed
MyRespObject myrespObj= new MyRespObject();
return myrespObj;
}
Just remember that both Objects that you are passing need to implement serializable
public Class MyCustomObject implements java.io.Serializable
{
I'm having trouble sending a json object from javascript to java controller,
Ajax:
var xmlHttp = getXmlHttpRequestObject();
if(xmlHttp) {
var jsonObj = JSON.stringify({"title": "Hello","id": 5 });
xmlHttp.open("POST","myController",true);
xmlHttp.onreadystatechange = handleServletPost;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send(jsonObj);
}
function handleServletPost() {
if (xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
alert(window.succes);
}
}
}
What I tried in Java:
public void process(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final TemplateEngine templateEngine)
throws Exception {
String jsonObj = request.getParameter("jsonObj");
}
They all are null.
I tried reading related posts and multiple ways of sending the data but same result. I don't know how to use Jquery for ajax, so I'm looking for a js solution mainly.
Can someone tell me what I'm missing? As I spent about three hours trying to figure it out
To get your JSON sent with a POST request, you have to read the body of the request in a doPost method. Here's one way to do it :
protected void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
StringWriter sw = new StringWriter();
IOUtils.copy(hreq.getInputStream(), sw, "UTF-8");
String json = sw.toString();
And then you'll have to parse the JSON. This may be done for example using Google gson.
Supposing you have a class Thing with public parameters id and title, this would be
Gson gson = new GsonBuilder().create();
Thing thing = gson.fromJson(json, Thing.class);
int id = thing.id;
String title = thing.title;
Of course there are other solutions than gson to parse JSON but you have to parse it.
I think you are confusing URL parameters with request body. To get json string from request you need read it from request.getReader().
I have figured it out.
The Json should be sent like this:
xmlHttp.send("jsonObj="+jsonObj);
instead of
xmlHttp.send(jsonObj);
In order to receive it as parameter.
I am using OpenCsv API and now i am stuck in some problem.Here's my code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
List<UserRegData> userRegDataList = new ArrayList<UserRegData>();
HttpSession session = request.getSession();
userRegDataList = (List<UserRegData>) session.getAttribute("referralData");
List<String[]> dataToWrite = new ArrayList<String[]>();
String csv = "E:\\carewave_backup\\csv\\UserReferral.csv";
CSVWriter writer = new CSVWriter(new FileWriter(csv));
for (UserRegData obj : userRegDataList) {
dataToWrite.add(new String[]{obj.getReferred_by_name(), obj.getInvitee_name(), obj.getInvitee_email(), obj.getInvitee_date(), obj.getIsInviteeRegistered(), obj.getDate_of_invitee_registered()});
}
writer.writeAll(dataToWrite);
writer.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
This servlet basically retrieves list from session and writes it to csv file.This servlet is triggered after user clicks download csv button.Now what i need is, browser should give a download dialogue.Is there anyway to download it in csv format without writing it to file first?.
I assume you're asking about how to stream the output on the server directly to the client without writing it first to a temp file on the server.
You don't need to write the data to a file first.
Set the resonse content-type to text/csv
Call getOutputStream() on the response object
Write the contents of dataToWrite as individual lines to the output stream
No disk file needed.
How can I configure tomcat so when a post request is made the request parameters are outputted to a jsp file? Do I need a servlet which forwards to a jsp or can this be handled within a jsp file ?
Here is my method which sends the post request to the tomcat server -
public void sendContentUsingPost() throws IOException {
HttpConnection httpConn = null;
String url = "http://LOCALHOST:8080/services/getdata";
// InputStream is = null;
OutputStream os = null;
try {
// Open an HTTP Connection object
httpConn = (HttpConnection)Connector.open(url);
// Setup HTTP Request to POST
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("User-Agent",
"Profile/MIDP-1.0 Confirguration/CLDC-1.0");
httpConn.setRequestProperty("Accept_Language","en-US");
//Content-Type is must to pass parameters in POST Request
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// This function retrieves the information of this connection
getConnectionInformation(httpConn);
String params;
params = "?id=test&data=testdata";
System.out.println("Writing "+params);
// httpConn.setRequestProperty( "Content-Length", String.valueOf(params.length()));
os = httpConn.openOutputStream();
os.write(params.getBytes());
} finally {
if(os != null)
os.close();
if(httpConn != null)
httpConn.close();
}
}
Thanks
First of all, your query string is invalid.
params = "?id=test&data=testdata";
It should have been
params = "id=test&data=testdata";
The ? is only valid when you concatenate it to the request URL as a GET query string. You should not use it when you want to write it as POST request body.
Said that, if this service is not supposed to return HTML (e.g. plaintext, JSON, XML, CSV, etc), then use a servlet. Here's an example which emits plaintext.
String id = request.getParameter("id");
String data = request.getParameter("data");
response.setContentType("text/plain");
response.setContentEncoding("UTF-8");
response.getWriter().write(id + "," + data);
If this service is supposed to return HTML, then use JSP. Change the URL to point to the JSP's one.
String url = "http://LOCALHOST:8080/services/getdata.jsp";
And then add the following to the JSP template to print the request parameters.
${param.id}
${param.data}
Either way, you should be able to get the result (the response body) by reading the URLConnection#getInputStream().
See also:
How to use URLConnection to fire and handle HTTP requests?
Unrelated to the concrete problem, you are not taking character encoding carefully into account. I strongly recommend to do so. See also the above link for detailed examples.
A servlet can handle both get and post request in following manner:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//remaning usedefinecode
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
If you have a tomcat installation from scratch, don't forget to add the following lines to web.xml in order to let the server accept GET, POST, etc. request:
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
...
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>
...
</servlet>