JOptionpane is showing on server machine only - java

JOptionPane.showMessageDialog(null, "User Account already Exist !!", "Signup", JOptionPane.ERROR_MESSAGE);
response.sendRedirect("http://localhost:8084/app/index.html");
I wrote above code in servlet.
First problem :
I'm getting dialogbox in local machine but after dialog box, page is not redirecting to index.html. I mean it remain on same screen.
Second problem :
When I'm trying to access my app from different machine using ip address like http://xxx.xxx.xxx.xxx:8084/app/index.html. In that case dialog box showing on server machine not in client machine.
Please help me to solve these problem. Also, dialog box always showing behind the browser, is there any way, it will show in front browser screen ?

This is because you are using Swing JdialogBox which is standalone and can not be used on web apps.
if you need to show any dialog box for client then better use Javascript alert like below
function x()
{
alert("user account already exists");
}
see this how javascript alert works
link

You cannot use Java Swing Components in Servlet.
Instead, you could show an Javascript Alert
//servlet code
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('User Account already Exist !!');");
out.println("</script>");
EDIT (I have tried myself and it works)
My Servlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class JavaScriptAlertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public JavaScriptAlertServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<script type=\"text/javascript\">");
out.println("alert('User Account already Exist !!');");
out.println("</script>");
}
}

Related

Server Sent event code not working on jelastic

I am learning Server Sent events in java and for that I am using a simple example. I am using Windows 7, Java 1.7, Tomcat 7, Eclipse Indigo. I have created a servlet (SseServer.java), the code for this servlet is as follows:
package sse;
import java.io.IOException; <br/>
import java.io.PrintWriter;<br/>
import java.util.Date;<br/>
import javax.servlet.ServletException;<br/>
import javax.servlet.annotation.WebServlet;<br/>
import javax.servlet.http.HttpServlet;<br/>
import javax.servlet.http.HttpServletRequest;<br/>
import javax.servlet.http.HttpServletResponse;<br/>
#WebServlet("/SseServer")<br/>
public class SseServer extends HttpServlet {<br/>
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Besides "text/event-stream;", Chrome also needs charset, otherwise
// does not work
// "text/event-stream;charset=UTF-8"
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
PrintWriter out = response.getWriter();
while (true) {
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + new Date().toLocaleString() + "\n\n");
out.flush();
// out.close(); //Do not close the writer!
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
And I am displaying the results in an html, SSE.html, the code for this is as shown below:
<!DOCTYPE html>
<html>
<body>
<h1>Current Server Time : </h1>
<div id="ServerTime"></div>
<script>
if (typeof (EventSource) !== "undefined") {
var source = new EventSource("http://localhost:8080/SSE/SseServer");
// http://eastern1.j.layershift.co.uk
//var source = new EventSource("http://eastern1.j.layershift.co.uk/SSE/SseServer");
source.onmessage = function(event) {
document.getElementById("ServerTime").innerHTML += event.data
+ "<br><br>";
};
} else {
document.getElementById("ServerTime").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>
</body>
</html>
When I run this code locally after every one second I am able to see the current time. I have also checked it on several browsers like chrome, firefox etc.
Since this code is working fine I decided to deploy this on cloud so I chose Jelastic.com. I created a war file and deployed it on Jelastic and tried running my sample application. But when I run the application from cloud, I can only see
Current Server Time :
I do not see the time. Can someone please tell me why this is happening? Is there something I need to change in my code? If yes then can someone please advice what it should be? Or should I change some other file/settings in eclipse while creating a war file?
Any help is much appreciated.
You had used absolute link, It's a bad practice. Try to use relative link.
Your mistake was that link not corresponding to path on server
var source = new EventSource("/SseServer");

HTTP Callback in Java

I'm trying to write some code to handle the process of an HTTP callback in Java.
I have very little knowledge of Java and was hopping you could lend me a hand or point me in the right way.
I want to call the script from a page that will listen for a POST from other machine with some parameters and their values.
I then want the script to save them somewhere (a file or a database).
Any help would be really appreciated.
For further clarification, I want to create a servlet on a specific URL to handle a HTML post from another machine and receive all parameters and their values and insert them into a database for example.
Another edit, got to this code so far:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class CallbackServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
IOException,ServletException
{
String instId=req.getParameterValues("instId")[0];
String cartId=req.getParameterValues("cartId")[0];
String desc=req.getParameterValues("desc")[0];
String cost=req.getParameterValues("cost")[0];
String amount=req.getParameterValues("amount")[0];
String currency=req.getParameterValues("currency")[0];
String name=req.getParameterValues("name")[0];
String transId=req.getParameterValues("transId")[0];
String transStatus=req.getParameterValues("transStatus")[0];
String transTime=req.getParameterValues("transTime")[0];
String cardType=req.getParameterValues("cardType")[0];
Connection conn = null;
Statement stmt = null;
PrintWriter out=res.getWriter();
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");
stmt = conn.createStatement();
int i=stmt.executeUpdate("insert into orderdetails values('"+transId+"','"+instId+"','"+cartId+"','"+desc+"'"+cost+"','"+amount+"','"+currency+"','"+name+"','"+transStatus+"','"+transTime+"','"+cardType+")");
if(i>0)
out.println("Inserted Successfully");
else
out.println("Insert Unsuccessful");
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
}
I can't test it atm unfortunately. Could you guys take a look at it and point out any mistakes/improvements?
Cheers
Probably easiest way for this would be to use Servlet api with some Java application server (tomcat, jetty, ...).Look at http://www3.ntu.edu.sg/home/ehchua/programming/java/javaservlets.html

display an image from a blob field using servlet

i created a jsp page that calls another jsp page that show an image took from a blob field in my mysql db:
<img src="blob.jsp">
it works. But, somewhere in this forum i read that this is not the right way to do it. I should, instead, using a servlet this way:
<img src="servlet_name">
I created a servlet, but it doesent show me the image it shows me this
ÿØÿàJFIFHHÿí$Photoshop 3.08BIMí ResolutionHH8BIM FX Global Lighting Anglex8BIMFX Global Altitude8BIMó Print Flags 8BIM Copyright Flag8BIM'Japanese Print Flags 8BIMõColor Halftone SettingsH/fflff/ff¡™š2Z5-8BIMøColor Transfer Settingspÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿèÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿè8BIM Layer State8BIM Layer Groups8BIMGuides##8BIM URL overrides8BIMSlicesuƒD Untitled-1Dƒ8BIMICC Untagged Flag
This is my simple servlet
package Jeans;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BlobDisplay")
public class BlobDisplay extends HttpServlet {
private static final long serialVersionUID = 1L;
GestioneDB gestioneDB ;
public BlobDisplay() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Blob image = null;
byte[ ] imgData = null ;
String query = null;
query = request.getParameter(query);
gestioneDB = new GestioneDB();
ResultSet rs = gestioneDB.rs("select immagine_principale from news where id ='217'");
try{
if (rs.next()) {
image = rs.getBlob("immagine_principale");
imgData = image.getBytes(1,(int)image.length());
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
}
}
catch(Exception e){}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
Here is a debugging hint for now.
JSPs are just "inside out" servlets and they are translated to servlets by the container. Since your JSP works and your servlet doesn't, why don't you check out (and post) the generated servlet. If you are using tomcat, it would be in a file called blob__jsp.java deep in the work directory. Then compare the calls and set up of your servlet and the generated servlet.
(My first guess is the content type, but you seem to be setting that)

slideshow using a servlet

I am trying a slideshow using a servlet . Though the photos are loaded but is not a slideshow. What i get is a series of images.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class PhotoCollection extends HttpServlet{
private String array[] = {"first.jpg","second.jpg","third.jpg","fourth.jpg"};
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<head>");
writer.println("<title>");
writer.println("SlideShow");
writer.println("</title>");
writer.println("</head>");
writer.println("<body>");
writer.println("<table>");
writer.println("<tr>");
try {
for(int i=0;i<=3;i++) {
writer.println("<td>");
writer.println("<img src=" + array[i] + " height=100 width=110>");
writer.println("</td>");
Thread.sleep(1000);
}
}catch(Exception exc) {
writer.println("<br />" + exc + "<br />");
}
writer.println("</tr>");
writer.println("</table>");
writer.println("</body>");
writer.println("</html>");
}
}
I have made the thread sleep 1 second but that doesn't affect the loading. How can i do a slideshow using it ? What changes do i have to make in the above servlet ?
You should use jQuery plugins for displaying it on browser pretty, use servlet just to serve image
Note : adding sleep in doGet doesn't make sense here, out put is sent once the method is executed so it would pause the execution

How to upload and save file in java servlet without using apache?

out.println("<tr><td><FORM ENCTYPE='multipart/form-data'"+
"method='POST' action='ProcessUpload' ></td>"+
"<td><INPUT TYPE='file' NAME='mptest'></td>"+
"<td><INPUT TYPE='submit' VALUE='upload'></td>"+
"</FORM></tr>");
This codes can help me upload file but the problem is after I click upload, I cant save the uploaded file in particular directory.Anyone can give some suggestion?
The code above simply outputs the HTML for an upload button. It does not do anything with any upload requests that form might start.
May I ask why you don't want to use Apache Commons FileUpload? To not use it will mean that you will need to implement RFC 1867. A lot of time and effort wasted when an implementation already exists.
You have to write another servlet (or some CGI, jsp ...etc.) to retrieve the file from the request and save it to wherever you like:
http://www.frontiernet.net/~Imaging/FileUploadServlet.html
Apache Commons FileUpload is the way to go as others suggested. If you don't want use that for any reason, you can also look at this class,
http://metatemplate.googlecode.com/svn/trunk/metatemplate/java-app-framework/tomcat-adapter/src/com/oreilly/servlet/MultipartRequest.java
This is not as robust as FileUpload but it works fine for simple file upload.
If you want to use Multipart request you need to write your processUpload servlet to handle this eg:
private String fileSavePath;
public void init(){
fileSavePath = getServletContext().getRealPath("/") + "data";
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
MultipartRequest mpr = new MultipartRequest(request, fileSavePath);
}
And I really wouldn't output pure html from a servlet as in your question - try dispatching to a jsp - even better if nothing else is required just use plain html.
The COS libary http://servlets.com/cos/ (not apache)
I second mlk's suggestion and think reading the Users Guide to Commons FileUpload will help you get started. It will handle receiving the file, but you still have to tell it "where" to store it. From your description, sounds like you want the user to choose "where" to store the file. You will have to write this portion yourself.
I hacked together a quick lister in a servlet. All the other comments are correct. Not a good idea to write html in a servlet, but this sounds like a good learning experience.
package somepackage;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DirectoryChooserServlet extends HttpServlet {
public DirectoryChooserServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Writer w = response.getWriter();
w.write("<html><body>");
String action = request.getParameter("action");
String directory = request.getParameter("directory");
String startDirectory = "/private";
if ("list".equals(action)) {
startDirectory = directory;
}
File dir = new File(startDirectory);
if (dir != null) {
w.write("..<br/>");
for(File f: dir.listFiles()) {
if(f.isDirectory()) {
w.write("" + f.getName() + "<br/>");
}
}
}
w.write("</body></html>");
}
}

Categories

Resources