I am trying to pass a string from one servlet to another but I always get a null value in the second servlet. I've banged my head against this one for almost 2 weeks to no avail and I've run out of ideas. I've read all the similar question posted on here and I still get a null value.
This is the first servlet
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
int userId = DBConnect.getIdByName(name);
int lobbyId = DBConnect.insertInLobby(userId);
request.setAttribute("lobbyId", lobbyId);
request.getRequestDispatcher("PlatformPairsLobby.jsp").forward(request, response);
}
catch (ServletException | IOException e)
{
logger.error("Error " + e);
}
}
This is the second servlet with the name string that always is null.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
int id = DBConnect.getIdByName(name);
request.setAttribute("id", id);
String lobbyId = request.getParameter("lobbyId");
request.setAttribute("lobbyId", lobbyId);
response.setContentType("application/x-java-jnlp-file");
try
{
request.getRequestDispatcher("PairsJnlp.jsp").include(request, response);
}
catch (ServletException | IOException e)
{
logger.error("Error " + e);
}
}
To access the second servlet, I use a button in this JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.awt.List"%>
<%#page import="java.util.*"%>
<%#page import="database.DBConnect"%>
<%# taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
<head>
<%
ArrayList<String> list = (ArrayList<String>)
request.getAttribute("lobbyList");
Integer lobbyId = (Integer) request.getAttribute("lobbyId");
%>
------------------
window.location.href =
"http://192.168.100.154:8080/GamePlatformCore/SecondServlet?lobbyId=<%=lobbyId%>";
The name is set in a different servlet.
request.setAttribute("verificare", verificare);
HttpSession session = request.getSession();
session.setAttribute("name", name);
if(request.getServletContext().getAttribute("userMessages")==null)
{
request.getServletContext().setAttribute("userMessages",new ArrayList<String>());
}
request.getRequestDispatcher(WELCOME_PAGE).forward(request, response);
You are using request scope attribute to get String value, use following code to get Session value:
<% String lobbyId = (String)request.getSession().getAttribute(lobbyId); %>
Related
I have a Java Dynamic Web Project where one of the Servlets does the following:
/**
* Servlet implementation class DataAPIServlet
*/
#WebServlet(name = "data", urlPatterns = { "/data" })
public class DataAPIServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String format;
/**
* #see HttpServlet#HttpServlet()
*/
public DataAPIServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
format = request.getParameter("format").replaceAll("\"", "");
// create data model and add to request object
RequestDispatcher requestDispatcher = null;
if (format.equals(null)) {
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
} else {
System.out.println("SERVING FORMATTED DATA : " + format);
String returnString;
switch (format.toLowerCase()) {
case "xml":
returnString = Films.getFilmsXML();
request.setAttribute("data", returnString);
requestDispatcher = xmlDispatcher(request);
response.setContentType("text/xml;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
case "csv":
returnString = Films.getFilmsCSV();
request.setAttribute("data",returnString);
requestDispatcher = csvDispatcher(request);
response.setContentType("text");
break;
case "json":
returnString = Films.getFilmsJSON();
request.setAttribute("data", returnString);
requestDispatcher = jsonDispatcher(request);
response.setContentType("text/json");
response.setContentType("text/json;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
break;
}
}
// Forward the request to the view
requestDispatcher.forward(request, response);
}
private RequestDispatcher xmlDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("xml.jsp");
}
private RequestDispatcher jsonDispatcher(HttpServletRequest request) {
return request.getRequestDispatcher("json.jsp");
}
private RequestDispatcher csvDispatcher(HttpServletRequest request){
return request.getRequestDispatcher("csv.jsp");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doGet(request, response);
}
}
One of the servlets spits out the data in xml/json/csv format based on the url query (for exmaple /data?format=json will return json data for all the films in databse).
Through debug I have found that my JAXB/GSON methods are properly creating a data set from my model however when viewed in the response to the browser something is going wrong which likely looks like the HTML escape sequences for special characters such as "<" on xml tags.
This narrows it down to something to do with the "" method in JSTL.
My XML is displayed by the following jsp:
<%#page contentType="application/xml" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# page trimDirectiveWhitespaces="true"%>
<c:set var="data" value="${data}"></c:set>
<c:out value="${data}" />
I can tell the data being passed by the response to the JSP is correct by debug :
Unless the issue with what I'm doing would be resolved by some better mechanism for serving the xml/json/csv data than simply serving it to a jsp file? suggestions welcome.
In the tag of JSTL set escapeXML to false in order to maintain the original characters. Otherwise escapeXML true will do the opposite.
<c:out value='${foo(someParameter)}' escapeXml="false"/>
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>");
.
.
.
}
I have two html pages - one for login and one that takes in a persons details. The login page is the first page and when the database is checked for the username and password, the user is allowed to enter their details. The SQL code works perfectly, it is just a problem with the mapping I am having. I am using the Tomcat server by the way. Could anybody help or spot what i am doing wrong?
This is my java code for logging in and entering details
public class Details extends HttpServlet {
private Connection con;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
//return writer
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = request.getParameter("password");
out.close();
try {
login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
res.sendRedirect("/redirect.html");
String name = request.getParameter("name");
String address = request.getParameter("address");
String age = request.getParameter("age");
out.println("<HTML><HEAD><TITLE>Personnel Details</TITLE></HEAD><BODY>");
out.println(name + address + age);
out.println("</BODY></HTML>");
System.out.println("Finished Processing");
}
out.close();
}
In my web.xml file I have:
<web-app>
<servlet>
<servlet-name>Details</servlet-name>
<servlet-class>Details</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Details</servlet-name>
<url-pattern>/Details</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>redirect</servlet-name>
<url-pattern>/redirect</url-pattern>
You may try this :
response.sendRedirect("redirect.html");
or
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", "redirect.html");
Alternative way,
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/redirect.html").forward(request, response);
Redirect to HTML
RequestDispatcher ds = request.getRequestDispatcher("index.html");
ds.include(request, response);
you can use
1.response.sendRedirect("redirect.html") or
2.String path= "/redirect";
RequestDispatcher dispatcher =servletContext().getRequestDispatcher(path);
dispatcher.forward(request,response);
I have this ajax call from a javascript file and I want to pass as a parameter the id of the user that I want to delete:
function eliminaUtente(id,nome){
if (confirm("Sei sicuro di voler eliminare l'utente "
+ nome
+ "?")) {
var xmlHttp2 = new XMLHttpRequest();
xmlHttp2.open("POST", "EliminaUtente", true);
xmlHttp2.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
var params2 = "id=" + id;
xmlHttp2.send(params2);
xmlHttp2.onreadystatechange = function() {
if (xmlHttp2.readyState == 4)
{
alert(xmlHttp2.status); <-----------this prints always 0!
if (xmlHttp2.status == 200) //
{
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
}
};
}
}
in the correspondant Servlet called EliminaUtente i have this code:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");
System.out.println(id);
String query = "delete from utente where idutente=" + id;
System.out.println(query);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost/Spinning?user=root");
PreparedStatement prest = con.prepareStatement(query);
prest.executeUpdate();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ok");
ajaxWriter.flush();
ajaxWriter.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
response.setContentType("text/plain");
PrintWriter ajaxWriter = response.getWriter();
ajaxWriter.print("ko");
ajaxWriter.flush();
ajaxWriter.close();
}
}
}
I can't understand where is the problem...can you help me please? ;)
I try your code and change a little bit i want to explain what did i and what i learn from it.I read some source. First i read XMLHttpRequest object and onreadyState event.
I implement your example both PUT and GET action method.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.test.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/test/*</url-pattern>
</servlet-mapping>
</web-app>
testServlet.java
package com.test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class testServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
/*super.doPost(req, resp);*/
String strId = req.getParameter("id");
System.out.println(strId);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
String strId = req.getParameter("id");
System.out.println(strId);
}
}
and main part NewFile.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Submit" onclick="eliminaUtente('1')" width="100%" />
</body>
<script language="javascript" type="text/javascript">
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("POST", url, true);
xmlHttp.send(url);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
</script>
</html>
with this way i write the parameter 1(i hardcode it in jsp file method invoke) and write it to console, the first thing in here the difference your code and mine i remove the xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); because if the method type is POST default encryption is this.
enctype = content-type [CI]
This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file".
So no need to enctype default is OK for POST.
And this is open method signature open(method, url, async, user, password) here async is the parameter which means if it is false don't wait a response from server implement the other line when response is come it will run. If it is true wait until response is come. Actually i try bot of them and it is worked.
Lastly i try it with GET. If you want use it with GET you should add xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded"); code for encryption and remove the url parameter from send() method.
function eliminaUtente(id) {
var xmlHttp = new XMLHttpRequest();
var url = "test/NewFile.jsp?id=" + id;
xmlHttp.open("GET", url, true);
xmlHttp2.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
alert("utente eliminato!");
} else {
alert("An error occurred while communicating with server.");
}
};
}
Note: I try this code in firefox, i create xmlHttpRequest object. For all browser(include IE6) sure you know use:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
typo?
alert(xmlHttp2.status); <-----------this prints always 0! Now has "2'
The problem was that I have to put false in this line:
xmlHttp2.open("POST", "EliminaUtente", FALSE);
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();