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();
Related
I want to pass parameter from servlet to jsp page . That is why , in servlet , I have written the following code :
request.setAttribute("errorMessage", dbMessage);
response.sendRedirect(redirectURL + "index.jsp");
In index.jsp I have written the following code :
<%
String error_msg = (String)request.getAttribute("errorMessage");
out.println(error_msg);
if (error_msg != null) {%>
<div class="alert alert-danger">
<%=error_msg%>
</div>
<% } %>
But I do not have the value of errorMessage in index.jsp page. What is the reason ? Please help me . Point to be noted : error Message is not null .
You can not pass hidden params while using request.sendRedirect. You have following options to pass parameters to the JSP from servlet.
Set request params in the url itself as
response.sendRedirect(redirectURL + "index.jsp?errorMessage=", dbMessage);
and then in JSP change code to
String errorMsg = request.getParameter("errorMessage")
Error message will be visible in URL on the browser side.
Use server-side forwarding as mentioned in the answer by Jaydip as shown below.
request.setAttribute("errorMessage", dbMessage);
RequestDispatcher dispatcher = serveltContext().getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
Using session
request.getSession().setAttribute("errorMessage", dbMessage);
on the JSP, change code to
String error_msg=(String)request.getSession().getAttribute("errorMessage");
Using cookie
Cookie errorCookie = new Cookie("errorMessage", dbMessage);
errorCookie.setPath(request.getContextPath());
response.addCookie(errorCookie);
On browser side you can read cookie via js or from the request itself
String error_msg = null;
Cookie [] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if ("errorMessage".equals(cookie.getName())) {
error_msg = cookie.getValue();
}
}
You should write like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
**request.getSession().setAttribute("mango", "Mango is a sweet Fruit");**
response.sendRedirect(request.getContextPath() + "/index.jsp");
}
The problem here is you are using sendRedirect. Understand that sendRedirect will initiate new request to different url. Try to using forward or include to maintain the request parameter.
I wrote this Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter printWriter=response.getWriter();
printWriter.write("Hello!");
}
and also this java script in index.jsp:
<script>
var resource = new EventSource("/servlet");
resource.onmessage = function (e) {
document.getElementById("container").innerHTML = e.data;
}
</script>
in order to create demo on server-sent events in html5. I inspected the jsp page in firefox and I got this error: the resource from this url is not text and nothing shows up. by the way request status is 200, OK. What is wrong with that?
Try to change the response header
response.setContentType("text/event-stream");
I am using $.ajax() function to call servlet in my application and i am forwarding request to anothor jsp page and setting request attribute.....I just want to know is it good approach to forward request and setting request parameter in ajax based servelt?
Here is my sample code.....
var id= $("#id").val();
$("#add-btn").click(function(e) {
e.preventDefault();
var dataString ='action=insert'+'&id='+id
console.log(dataString);
$.ajax({
type: "POST",
url: "RecordHandler",
data: dataString,
success: function(data){
console.log('Add');
$('body').html(data);
$('body').prepend('<div style="width:100%;text-align:center;"><h3 style="color:green" >Record Added Succesfully</h3></div>')
}
});
});
and here is my servlet code......
private static String UserRecord = "/list.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String redirect = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("insert")) {
String id= request.getParameter("id");
int uid = Integer.parseInt(id);
RecordBean record = new RecordBean();
record.setId(uid);
dao.addRecord(record);
redirect = UserRecord;
request.setAttribute("records", dao.getAllRecords()); //Is it good approach to set request attribute in ajax based servlet?
System.out.println("Record Added Successfully");
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
How to do it using ajax without refreshing page......
even i use window.location.herf="list.jsp" in ajax success method it is refreshing page
When you call a servlet via AJAX, you stay on the same page by definition, regardless of the headers sent by the server.
If you want to change the page, you must do it with javascript, in the success handler function for the $.ajax(..) call.
You can read the Location response header and set the window.location.href to that value. See here for other options.
I am trying to communicate with a servlet and jsp via an applet. When the button in the applet is clicked request is fired to the servlet and then i try to forward from that servlet to a jsp page. Though the request is made successfully to the servlet's doGet method,i neither see a servlet page in the browser nor a jsp page. why is that ? what am i missing ?
applet button click code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("pressed the button !");
try {
URLConnection connection = new URL("http://localhost:8084/poll/servlet_1").openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream response = connection.getInputStream();
connection.connect();
}catch(Exception exc) {
exc.printStackTrace();
}
}
servlet code :
#Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
System.out.println("---inside the doGet method of servlet----");
PrintWriter writer = response.getWriter();
response.setContentType("text/plain");
writer.println("You just landed on a servlet from an applet !");
RequestDispatcher rd = request.getRequestDispatcher("jsp_1.jsp");
rd.forward(request, response);
}
What i see in the server log is the message : ---inside the doGet method of servlet----
when i fire the event the first statement inside the doGet method gets printed but the request is not forwarded to the jsp page. why is that ?
If I am getting you correctly you need to Redirect from an applet to servlet and then forward JSP page?
after your servlet response
.....redirect to jsp from applet.
AppletContext appletContext = getAppletContext();
appletContext.showDocument(new URL(getDocumentBase(), "yourJsp.jsp"));
I'm trying to display a PDF report on a webApp, I've been following this tutorial here
and it creates the pdf file fine, but I'm having trouble trying to display it in the browser. In my xhtml I have a button, once that button is clicked, a function calling the servlet is called. it goes into the servlet and created a pdf document fine. but I can't seem to figure out how to display it on the screen. is there a way to show the document on a new browser window, or new tab? or even the same one.
I'm working with Java Server faces 2.0 in Eclipse. and have a Tomcat 7.0 server.
on my webxml I added the following code specified in the example:
<servlet>
<servlet-name>PdfServlet</servlet-name>
<servlet-class>com.bravo.servlets.PdfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PdfServlet</servlet-name>
<url-pattern>/PdfServlet</url-pattern>
</servlet-mapping>
and my servlet looks like this ( pretty much the same as the example):
#WebServlet("/PdfServlet")
public class PdfServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Font font = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
/**
* Default constructor.
*/
public PdfServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
invokePDFViewer(response);
Document document = new Document();
try{
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
addContent(document);
document.close();
}catch(DocumentException e){
e.printStackTrace();
}
}
private void invokePDFViewer(HttpServletResponse response){
response.setContentType("application/pdf");
}
private void addContent(Document document)throws DocumentException {
PdfPTable table = new PdfPTable(2);
Paragraph paragraph = new Paragraph ("Este es un parrafo en celda 1", font);
table.addCell(paragraph);
table.addCell("2");
table.addCell("3");
table.addCell("4");
table.addCell("5");
table.addCell("6");
document.add(table);
}
}
the xhtml I'm calling the servlet from looks like this:
....
function callPdfServlet(){
$.ajax({
type: 'POST',
cache: 'false',
data: 'codeType=notUsed',
url: '/miloWeb/PdfServlet',
async: false,
success: function(data){
},
error: function (xhr, ajaxOptions, thrownError){
alert(ajaxOptions);
}
});
}
.....
<h:commandButton id="reportButton" action=" " styleClass="button" value="get Report" onclick="callPdfServlet();"></h:commandButton>
So at the end, all it does right now is I go into the xhtml in my browser, click on the button, and it hits the servlet, goes through the code, and then thats it. my browser just reloads the screen and nothing else happens. so i need to show the pdf I just created. Thanks in advance for your help!
//************************************************************************************
EDIT 01/02/12:
after reading this and this
I can see that the action in the commandButton will take me to the "response".xhtml with "response" being a string that I either hardcode in, or is returned by an action in a Managed Bean. that response ( if not put in my faces-config file ) will take me to the page IF it's in the same folder as my current page.
so I believe that when I put "miloWeb/PdfServlet" as a response for the action, It looks for the page in the same folder ( which it's not) and since it doesn't find anything just reloads the page. And since I have a break point In the servlet, I am 100% sure it's not hitting it.
so my question is: How do I redirect my page to miloWeb/PdfServlet??
to clarify, it works fine if I put the name of another xhtml in the same folder. so it is working that way.
//This is what I tried just for reference:
Instead of going through the ajax call I've changed the button to
<h:commandButton id="reportButton" action="/miloWeb/PdfServlet" styleClass="button" value="get Report"></h:commandButton>
but it Just reloads the page and doesn't take me to the Servlet.
so another thing I tried was tried to go thought the action of the button calling a Managed Bean:
public String actionPdf(){
return "/miloWeb/PdfServlet";
}
again,same thing, the function returns the string, but it still doesn't take me to the servlet.
Just post a regular form rather than posting in AJAX, and the browser will load the response from your PDF servlet in the page rather than loading it from JavaScript and ignoring it completely:
<form method="post" action="/miloWeb/PdfServlet">
<input type="hidden" name="codeTyped" value="notUsed"/>
<input type="submit" value="Show PDF"/>
</form>
in the action of the commandButton, I had to type this in:
public String doThis(){
String url = "url of your servlet";
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().dispatch(url);
}catch (Exception e) {
e.printStackTrace();
}
finally{
context.responseComplete();
return "";
}
So with this, I get the context root and redirect it there. url being /PdfServlet