JAVA - get response from system to the UI - java

I'm new to java and I have servlet which connect to some system and get data, while debug the code I see that I was able to connect and get the data, ( I dont get any error) . I use the following code :
try {
urlConnection.connect();
} catch (IOException e) {
String messagePrefix = "Connection error: ";
LOGGER.error(messagePrefix, e);
}
OutputStream clientOutStream = responseToClient.getOutputStream();
copyStream(backendInStream, clientOutStream);
responseToClient.setStatus(backendResponseCode);
int backendResponseCode = urlConnection.getResponseCode();
InputStream backendInStream = null;
try {
if (backendResponseCode < 400) {
backendInStream = urlConnection.getInputStream();
}
} catch (IOException e) {
String messagePrefix = "Input stream error: ";
LOGGER.error(messagePrefix, e);
}
Now I have this simple index.html and my question how should I print the data back to the browser ?
( I wasnt able to copy the html file as code :(
Any idea how to pass the response to the UI , I try to add response tag and put the variable as global without success...

Yes you can send the response using dispatcher or httpsession and use jsp to get the response in UI
in your back end simply use
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.setAttribute("backendresponse",backendresponse))
}
and in your jsp you can get and store that data in an arraylist as
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
Now you can use this list to populate data in any tag using <%= %> as this is equivalent to a print statement as any expression say
<%for(int i=0;i<list.size();i++)
{%>
<%=list.get(i).getData() %>
<%}%>
will print the response in your browser
UPDATE
in your servlet you can get the parameters as
String url=request.getParameter("url")
Class obj=new Class(url)
session.setAttribute("obj",obj);
response.sendredirect("disp.jsp")
in your disp.jsp
<%
ArrayList<> list=(ArrayList<>)session.getAttribute("backendresponse");
%>
<html>
<head>
</head>
<body>
<%for(int i=0;i<list.size();i++)
{%>
<h1> <%=list.get(i).getData() %></h1>
<%}%>
</body>
</html>

You should have doGet method which has PrintWriter taking each line of the HTML:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
.
.
.
}

Related

Using jsp page instead of java servlet

I have created a login page using HTML page and Java Servlet class. However I am wondering if it is possible to have a JSP instead of the Java file? So essential use this code in the Java class into a JSP page and still have the same functionality?
<form action="Lognn" method="post">
<input type="text" name="name"/>
<input type="text"name="pass"/>
Java class
Public class Login extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String name = request.getParameter("name");
String pass = request.getParameter("pass");
MyDb1 db = new MyDb1();
Connection con = db.getCon();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select uid,name,pass from register where email = '"+name+"' and pass = '"+pass+"'");
while ((rs.next())) {
String uid = rs.getString("uid");
//out.println("User id"+uid);
HttpSession session=request.getSession();
session.setAttribute("name",uid);
response.sendRedirect("http://localhost:8080/Final/userprofile.jsp");
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
Generally, each JSP is translated and compiled to a servlet, and a lot of things you can do with servlets you can do with JSP.
You can change your form action="Lognn" method="post" to form action="Lognn.jsp" method="post", then
in Lognn.jsp you can read your input parameters from html like <%= request.getParameter("name")%>, then
in Lognn.jsp you can connect to a database directly or you can use EJB
and finally you can give html output back from the same JSP.
It formally will work without servlet, but in CATALINA_HOME/WORk directory a servlet will be internally created and compiled from your JSP.

AJAX call is not reaching Servlet

I am trying to make a simple textbox which initiate a suggestive feedback based on the characters entered by the user. I am trying to fetch a JSON object from a Servlet but my AJAX call is somehow not reaching the servlet. On checking the status of AJAX request using this.status I am getting error code 404. Can anyone suggest me a solution:
[![enter image description here][1]][1]
Here's my servlet: FetchServ.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
Connection con;
ResultSet rs;
java.sql.PreparedStatement pst;
String ch = request.getParameter("q");
String data;
ArrayList<String> list = new ArrayList();
response.setContentType("application/JSON");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("drivers registered");
con = DriverManager.getConnection(con_url, userID, password);
System.out.println("connection created");
pst = con.prepareStatement("SELECT * FROM candidates where FirstName LIKE ?");
pst.setString(1, ch + "%");
rs = pst.executeQuery();
System.out.println("query executed");
while(rs.next())
{
data = rs.getString("FirstName");
list.add(data);
}
String json = new Gson().toJson(list);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
response.getWriter().append("Served at: ").append(request.getContextPath());
} catch (SQLException | ClassNotFoundException e) {
System.err.println(e.getMessage());
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
the jsp code:
<script>
function suggest(str){
if(str.length == 0){
return;
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
document.getElementById("sugg").innerHTML = this.status;
if(this.readyState == 4 && this.status == 200){
//var res = JSON.parse(this.responseText);
document.getElementById("sugg").innerHTML = this.responseText;
}
};
try{
xmlhttp.open("GET", "com.test.java/FetchServ", true);
xmlhttp.send();
}catch(e)
{
alert("unable to connect ");
}
}
}
</script>
</head>
<body>
<form>
Search:<input type="text" onkeyup = "suggest(this.value)">
</form>
<p id = "sugg"></p>
</body>
</html>
and this is the result I am getting:
[![enter image description here][2]][2]
<display-name>ACtxtbox</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.test.java/FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/FetchServ</url-pattern>
</servlet-mapping>
</web-app>
your Web.xml entries are not proper, check the url which you are using in urlbar and the form submitted using xmlhttp.open("GET", "fetch", true); you can debugg the actual url passed as a request to the server by opening developer tools and navigating to the network tab it will look something like below.
also your <servlet-class>ACtxtbox/FetchServ</servlet-class> is not correct, it should be with package path like <servlet-class>sompackagepath.FetchServ</servlet-class>
EDIT
As per your images, I can see you have declare index.jsp which will be accesible by giving url: http://localhost:<port_number>/ACtxtbox/index.jsp.
Now you should note below points:
As you are calling servlet using ajax call where you have given
parameters as fetch in this line of code in you javascript
xmlhttp.open("GET", "fetch", true); hence it is now changing your
url to http://localhost:<port_number>/ACtxtbox/fetch
your web.xml entry should be like this
<servlet>
<servlet-name>FetchServ</servlet-name>
<servlet-class>com.rishal.test.FetchServ</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FetchServ</servlet-name>
<url-pattern>/fetch</url-pattern>
</servlet-mapping>
How come your url pattern is coming like
http://localhost:<port_number>/ACtxtbox/com.test.java/fetch ? is
it you have modified the web.xml entries. Please read the tutorials
and google about web application,jsp,servlets and ajax calls. you
should also note that you have to create your servlet class under
some package as i have given in the web.xml entry
com.rishal.test its package path and class is inside this package
path.
package com.rishal.test;
public class FetchServ extends HttpServlet {
----------------------
---------------------------
}

Why is the url showing /ServletName though what is displayed is from jsp

I have a servlet where I get data from Sql Server using ResultSet. I use
request.setAttribute("list", list);
request.getRequestDispatcher("Display.jsp").forward(request, response); to display as a table in the jsp.
But in the omnibox of chrome I see /ServletName instead of /JSPName.jsp. The table is displayed in the jsp using foreach based on the list received from servlet.
This is the servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connection = null;
Statement stmt = null;
try {
StringBuffer data = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DesktopScreen","sa","sa123");
stmt = connection.createStatement();
ArrayList list = new ArrayList();
String query = "select * from ClientLogin";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String UniqueId,ClientId,RequestedDateTime,ConnectionStatus;
UniqueId = rs.getString("UniqueID");
ClientId = rs.getString("ClientId");
RequestedDateTime = rs.getString("RequestDateTime");
ConnectionStatus = rs.getString("ConnectionStatus");
BeanClass beanClass = new BeanClass();
beanClass.setUniqueId(UniqueId);
beanClass.setClientId(ClientId);
beanClass.setConnectionStatus(ConnectionStatus);
beanClass.setRequestDateTime(RequestedDateTime);
list.add(beanClass);
}
request.setAttribute("list", list);
request.getRequestDispatcher("Display.jsp").forward(request, response);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
connection.close();
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is Display.jsp:
<table border ="1" style="border: border-collapse">
<tr><td>UniqueId</td><td>ClientId</td><td>Request Date and Time</td><td>Connection Status</td></tr>
<c:forEach items="${list}" var="item">
<tr>
<td>${item.getUniqueId()}</td>
<td>${item.getClientId()}</td>
<td>${item.getRequestDateTime()}</td>
<td>${item.getConnectionStatus()}</td>
</tr>
</c:forEach>
</table>
Your browser has requested for the servlet url and the servlet has forwared it to jsp. Your browswer does not know that. This is because you are using [requestDispatcher.forward()][1] method. Check the image from thejavageek.com
This is what happens
Browser requests the servlet.
Servlet forwards the task to jsp.(Browser doesn't know that)
Broswer still thinks the response has come from servlet and not jsp.
If you want the url to be shown in browser, then you need to user response.sendRedirect() which is explained in image below
If you use response.sendRedirect(), below steps will happen.
Your browser requests servlet.
Servlet calls response.sendredirect();
Browser will make another request to another resource and url will be changed in the address bar.
When you use requestDispatcher.forward(); the resources are forwarded within the server from where the call is made. This is done by container internally and client or browser is not involved in it.

how to pass a value from servlet in javascript

I'm new to servlets and all this topic so sorry if it's a bit messy!
I'm trying to send a value from servlet to javascript or get value of a servlet method in java script.
I'm not sure about the doGet! am I doing it right ? getting the value of fields and sending the result to javascript?
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String passengerCount = request.getParameter("passengerCount");
String departureSchedule = request.getParameter("schedule");
String arrivalSchedule = request.getParameter("returnschedule");
HttpSession session = request.getSession(true);
int departureSID = 0;
int passengerCountInt = 0;
userID = 0;
int arrivalSID = 0;
try {
departureSID = Integer.parseInt(departureSchedule);
passengerCountInt = Integer.parseInt(passengerCount);
userID = Integer.parseInt(session.getAttribute("userID").toString());
arrivalSID = Integer.parseInt(arrivalSchedule);
} catch (Exception e) {
}
if (departureSID != 0) {
ScheduleBean departureSb = new ScheduleBean();
departureSb.selectSchedule(departureSID);
int departureRoute = departureSb.getRouteID();
RouteBean routeB1 = new RouteBean();
routeB1.selectRoute(departureRoute);
double routeCharge = routeB1.getCharge();
double totalDCharge = routeCharge * passengerCountInt;
ReservationBean rb = new ReservationBean();
UserBean us = new UserBean();
if (arrivalSchedule == null) {
rb.saveOneWayReservation(departureSID, userID, totalDCharge, passengerCountInt, "TICKET");
} else {
departureSb.selectSchedule(arrivalSID);
int arrivalRoute = departureSb.getRouteID();
routeB1.selectRoute(arrivalRoute);
double arrivalRouteCharge = routeB1.getCharge();
totalDCharge += arrivalRouteCharge * passengerCountInt;
rb.saveRoundReservation(departureSID, arrivalSID, userID, totalDCharge, passengerCountInt, "TICKET");
}
ScheduleBean sbb = new ScheduleBean();
sbb.selectSchedule(rb.scheduleID);
AirBean bbb = new AirBean();
bbb.selectAir(sbb.getAirID());
String AirCode = bbb.getAirCode();
String username = session.getAttribute("username").toString();
int referenceNumber = rb.reservationID + 100;
rb.updateTicketNumber(AirCode + "-" + username + "-" + String.valueOf(referenceNumber));
out.println("<html>");
out.println("<head>");
out.println("<title>Make payment</title>");
out.println("<script type='text/javascript' src='js/jquery-1.5.2.min.js'></script>");
out.println("<script type='text/javascript' src='js/payment.js'></script>");
out.println("<script src='http://code.jquery.com/jquery-latest.min.js'></script>");
out.println("<link type='text/css' href='css/style.css' rel='Stylesheet' />");
out.println("</head>");
out.println("<body>");
out.println("<div class='bg-light' style='width: 200px; height: 200px; position: absolute; left:50%; top:50%; margin:-100px 0 0 -100px; padding-top: 40px; padding-left: 10px;'>");
out.println("<input id='reservationID' style='display: none' value='" + rb.reservationID + "' />");
out.println("<div>Credit Card Number : </div>");
out.println("<div><input id='creditcard' onKeyPress='return checkIt(event);' type='text' name='creditcard' maxlength='16' /></div>");
out.println("<div>ExpirationDate : </div>");
out.println("<div><input id='expirationDate' type='text' onKeyPress='return checkIt(event);' name='expirationDate' maxlength='4' /></div>");
out.println("<input type='hidden' id='FormName' name='FormName' value='" + HiddenValue + "'>");
out.println("<div><input id='somebutton' type='button' name='buttonsave' value='Make Payment' onclick='makePayment(" + rb.reservationID + ");' /></div>");
out.println("<div><input type='button' name='buttoncancel' value='Cancel Payment' onclick='cancelPayment(" + rb.reservationID + ");' /></div>");
out.println("</div>");
out.println("</body>");
out.println("</html>");
}
} finally {
out.close();
}
}
I'm trying to get the value of the two input fields process on them and send the result to javascript
Servlet doGet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
creditno = request.getParameter("creditcard"); //name of the input field, not id
expiration = request.getParameter("expirationDate"); //name of the input field should be expirationDate
UserBean us = new UserBean();
boolean check = us.checkCC(userID, creditno, expiration); // process the fields
if (check == true) {
CCA = "1";
} else {
CCA = "0";
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(CCA); // Write response body.
}
Servlet doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
Javascript:
var tempresp;
$(document).ready(function() { // When the HTML DOM is ready loading, then execute the following function...
$('#somebutton').click(function() { // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
$.get('MakeReservation', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
alert(responseText);
tempresp=responseText;
});
});
});
Thanks In Advance!
you have your java right, it is request.getParameter(...). However your not sending any data using javascript. If you want to send a "GET" request then use the code you have but make the following change:
$.get('MakeReservation?creditcard=12345&expirationDate=11%2F14', ....);
I would look up some JQuery tutorials on using the get and post methods. Also you may want to comment out that code you have and just test sending across some variables to get the hang of things before you dive right into that java side of things.
You're not sending any parameters to the Servlet. Even if you do, you'll encounter an IllegalStateException. It is because you're writing to the response body, using out.println(), and then setting headers.
The statement
finally {
out.close();
}
also flushes the output stream, preventing you from writing any response headers.
Set any headers before writing to the response body and pass the required parameters in $.get
$.get('MakeReservation', {passengerCount: 2, arrivalSchedule: 123}, function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
alert(responseText);
});

I can't retrieve responseText from servlet using AJAX

I have a servlet file called NewServlet.java. This servlet is called by my AJAX script to retrieve the response.
I have verified the servlet by testing it in a browser.
But when I call it from my AJAX script it gives me a blank responseText and an error that says
XMLHttpRequest cannot load
http://localhost:8084/WebApplication1/NewServlet.
Origin null is not allowed by
Access-Control-Allow-Origin
NewServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<option value='1'>one</option>");
out.println("<option value='2'>two</option>");
out.println("<option value='3'>three</option>");
out.println("<option value='4'>four</option>");
out.println("<option value='5'>five</option>");
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return "Short description";
}
}
test.html
<html>
<head>
<script language = "javascript">
var xmlDoc = 0;
var xhttp = 0;
function reciveData()
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // IE 5/6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = redirectUser;
xhttp.open("GET","http://localhost:8084/WebApplication1/NewServlet",true);
xhttp.send();
}
function redirectUser()
{
if (xhttp.readyState == 4)
{
log = 0;
xmlDoc = xhttp.responseText;
alert(xmlDoc);
}
}
</script>
</head>
<body onload="reciveData()">
</body>
</html>
Can some one point me in a right direction ?
Thanks.
That's on the browser side...the security model only allows AJAX requests to the same host/port that you fetched the page from. Make sure that you've fetched your page via the server (e.g. http://localhost:8084/test.html) and not loaded it via the filesystem. Then you should be good to go...or at least continue debugging. ;)
This can indeed happen when the servlet runs on a different port than where the ajax request is coming from. This violates the Same Origin Policy for ajax requests and thus the browser won't process the ajax response. Apart from hosting the servlet behind the same port, other solutions are to return JSONP instead or to let the servlet set the HTTP Access-Control headers.
response.setHeader("Access-Control-Allow-Origin", "*");
You however need to keep in mind that this way your servlet is by Ajax accessible to everyone. If the servlet returns sensitive information, then this is a security hole. But if it does not and it is supposed to be a public webservice, then it's safe.
in my experience, if you want to load data with ajax, send your request to a jsp file, and get your response text from that jsp file. it is a lot easier to handel. see this example if you like
EDITED<<
==========================
ajax_load.js :
var xmlhttp;
function loadAdminRight(category){
xmlhttp = GetXmlHttpObject();
if (xmlhttp == null) {
alert("Your browser does not support Ajax HTTP");
return;
}
var url = "load.jsp";
url = url + "?category="+category;
xmlhttp.onreadystatechange = getLoad;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function getLoad(){
if (xmlhttp.readyState == 4) {
document.getElementById("right_content").innerHTML = xmlhttp.responseText;
//or what you want to do
}
}
===========================
load.jsp :
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
String l_category = request.getParameter("category");
if(l_category.equals("article")){
out.write("You have choosen article category");
out.write("<br/>");
}
}else if(l_category.equals("news")){
out.write("You have choosen article category");
out.write("<br/>");
}
%>
and to make the ajax going you just need to call the .js function from where you want, for example on a button click action :
onClick="loadAdminRight("article");"
and you can import your java classes in a jsp file with adding <%page import="" %> to the top of your jsp page for example :
<%#page import="com.omicc.classes.Article"%>
write your own load.jsp file which handles the response, then use out.write in your jsp file to write the response text.
i wish it helps you
This will solve your issue..
// Ajax response
res.setContentType("text/javascript");
res.setCharacterEncoding("UTF-8");
res.setHeader("Cache-Control", "no-cache");
PrintWriter out = res.getWriter();
out.print("GRANTED");
out.close();

Categories