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>");
}
}
Related
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");
I'd like to make one text for multiple html files, something like greating. Let's say greating is:
"Hello, if you have any questions please conatact me."
What I want is to recall that text on every html page. And later if I change it, the change would appear on all the html pages.
I am weak on java, but I think I need to create some javascript and recall the text with div class function, like the facebook button is made.
P.S. Facebook button recall:
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data- layout="standard" data-action="like" data-show-faces="true" data-share="true">
with javascript you can change the content of a tag with html() function, or you could include the resource, i guess it depends on the technology being used
In the simplest form, you can create a function in your javascript master copy and make a document.write call. You would need to call that script file on every page.
function greetingMessage() {
document.write('your message);
};
Then
call greetingMessage();
you can also put the javascript in a master file and then have the div in each HTML page:
function greetingMessage(){
document.getElementById('Message').innerHTML = 'Your Message';
};
HTML:
<body onload="greetingMessage();">
<div id="Message" style="color:red;"></div>
If you are using JSP's or Servlets you can have a resource/properties file that contains many Strings being used throughout your application. The properties file would contain key=value pairs. You could then simply reference a particular key in the properties file, for instance:
greeting=Hello, if you have any questions please contact me
The key is "greeting", the value is "Hello, if you have any questions please contact me"
To read in the properties file you would use the Properties class like so:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MyWebPage extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
{
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.print("<html><head></head><body><div class=\"someclass\">" +
getGreeting() + "</div>"
"</body></html>"
);
}
public String getGreeting()
{
String greeting = "";
try{
Properties prop = new Properties();
InputStream input = new FileInputStream("config.properties");
// load a properties file
prop.load(input);
greeting = prop.getProperty("greeting");
input.close();
}
catch(IOException ioe){ioe.printStackTrace();}
finally{
if (input != null)
{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return greeting;
}
}
The same sort of thing can be effectively used in Java Server Pages. Hope this helps.
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)
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>");
}
}
Typically resource bundles are loaded and used within a JSP using JSTL and fmt, but this requires to always use the syntax <fmt:message key=""/> to access the value.
When the text to be localized looks like
<a href="url" title="message"> it is awkward (though valid to write):
<a href="url" title="<fmt:message key="key"/>">
and plain awkward to use the scoped syntax
<fmt:message key="key" var="var">
<a href="url" title="${var}">
</fmt:message>
Is there a simpler way to do this? I am looking for something like just
<a href="url" title="${messages.key}">
Yes, the below is a copy of my answer at Is there a shorthand for <fmt:message key="key" />? as mentioned in Bozho's comment on your question. But since that question is actually Spring-targeted, my answer wasn't fully applicable there. Your question is however not Spring-targeted, but just plain JSP/Servlet targeted and can therefore not be closed as exact dupe. So I think the answer is better at its place here:
You can create a class which extendsResourceBundle, manage the loading yourself with help of a Filter (based on request path?) and store it in the session scope. The ResourceBundle is accessible the usual JSP EL way. You can access it as if it's a Map. The handleGetObject() method will be invoked on every access.
Here's a kickoff example:
package com.example.i18n;
import java.util.Enumeration;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
public class Text extends ResourceBundle {
private static final String TEXT_ATTRIBUTE_NAME = "text";
private static final String TEXT_BASE_NAME = "com.example.i18n.text";
private Text(Locale locale) {
setLocale(locale);
}
public static void setFor(HttpServletRequest request) {
if (request.getSession().getAttribute(TEXT_ATTRIBUTE_NAME) == null) {
request.getSession().setAttribute(TEXT_ATTRIBUTE_NAME, new Text(request.getLocale()));
}
}
public static Text getCurrentInstance(HttpServletRequest request) {
return (Text) request.getSession().getAttribute(TEXT_ATTRIBUTE_NAME);
}
public void setLocale(Locale locale) {
if (parent == null || !parent.getLocale().equals(locale)) {
setParent(getBundle(TEXT_BASE_NAME, locale));
}
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
#Override
protected Object handleGetObject(String key) {
return parent.getObject(key);
}
}
(note the TEXT_BASE_NAME constant should refer to name of the resource bundle files, the above example assumes that you've text.properties, text_en.properties, etc in the com.example.i18n package)
The Filter:
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Text.setFor((HttpServletRequest) request);
chain.doFilter(request, response);
}
JSP:
<p>${text['home.paragraph']}</p>
If you want to change the locale from inside some servlet or filter:
Text.getCurrentInstance(request).setLocale(newLocale);
Related/interesting-to-know:
Overriding ResourceBundle#Control to read files using UTF-8
List all available ResourceBundle files
Iterating through multiple properties from ResourceBundle
How to internationalize a Java web application?
To do what you want you may need to create and register your own ELResolver. Take a look at this answer - Alternative to using c:out to prevent XSS.
So you might reserve a prefix such as MESSAGES and translate that into a ResourceBundle lookup.
i.e. ${MESSAGES.key} gets processed by your ELResolver as bundle.getString(key).