I have a ServiceHandler class and I want to essentially read in a file. In my init() function:
private String languageDataSet = null; // This variable is shared by all HTTP requests for the servlet
private static long jobNumber = 0; // The number of the task in the async queue
private File f;
public void init() throws ServletException {
ServletContext ctx = getServletContext(); // Get a handle on the application context
languageDataSet = ctx.getInitParameter("LANGUAGE_DATA_SET"); // Reads the value from the <context-param> in web.xml
// You can start to build the subject database at this point. The init() method is only ever called once during the life cycle of a servlet
f = new File(languageDataSet);
}
In a doGet function, I want to display some info on this file:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
out.print("Language Dataset is located at " + languageDataSet + " and is <b><u>" + f.length() + "</u></b> bytes in size");
}
In my web.xml file, I have the context-param as so:
<context-param>
<param-name>LANGUAGE_DATA_SET</param-name>
<param-value>wili-2018-Edited.txt</param-value>
</context-param>
I get the following output:
Language Dataset is located at wili-2018-Edited.txt and is 0 bytes in size
It can't seem to find the file as I have verified there is text in the file, therefore it shouldn't be displaying as 0. Any idea why the file seemingly can't be found? (The file is in the same directory as the web.xml file).
Related
My problem is, that I want to list all the images what is located
project/src/main/webapp/images
I know if I know the image(s) name(s) I can make an URL like this:
assetSource.getContextAsset(IMAGESLOCATION + imageName, currentLocale).toClientURL();
But what if I dont know all the images name?
Thanks for the answers in advance!
The web app (and tapestry as well) doesn't know/care about absolute path of files, as it could be deployed anywhere.
You can get absolute path of some file by calling getRealPath of HttpServletRequest.
#Inject
private HttpServletRequest request;
...
// get root folder of webapp
String root = request.getRealPath("/");
// get abs path from any relative path
String abs = root + '/' + relPath;
getRealPath of HttpServletRequest is deprecated, it's recommended to use ServletContext.getRealPath instead but it's not so easy to get ServletContext.
I prefer to use WebApplicationInitializer implementation
public class AbstractWebApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Here we store ServletContext in some global static variable
Global.servletContext = servletContext;
....
}
You basically need the ability to read files in a given folder. Here's some very basic code that will iterate through all of the files in a folder:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
}
// else, it's a directory
}
All of the imports should be from the java.io package.
I am working on a Java application and what I want to do is to give to the users the functionality to upload an image and view it at their profile. I know similar questions have been answered many many times but this is my first time doing this and I am really struggling to make it work.
So this is my testing code:
upload.jsp
...
<body>
<form method="post" action="FileUploader" encType="multipart/form-data">
<input type="file" name="file" value="select images..."/>
<input type="submit" value="start upload"/>
</form>
</body>
...
FileUploader.java
As you can see here, I store all my images in Tomcat's webapps/ROOT/files folder.
#WebServlet("/FileUploader")
public class FileUploader extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
if(!ServletFileUpload.isMultipartContent(request)){
out.println("Nothing to upload");
return;
}
FileItemFactory itemfactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(itemfactory);
try{
List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
for(FileItem item:items){
String contentType = item.getContentType();
if(!contentType.equals("image/png")){
out.println("only png format image files supported");
continue;
}
File uploadDir = new File("/home/agg/apache-tomcat/webapps/ROOT/files");
File file = File.createTempFile("img",".png",uploadDir);
item.write(file);
out.println("Filename: " + file.getName());
out.println("File Saved Successfully");
response.sendRedirect("message.jsp");
}
}
catch(FileUploadException e){
out.println("upload fail");
}
catch(Exception ex){
out.println("can't save");
}
}
}
message.jsp
Here, I am trying to load one of the images saved through another servlet.
...
<body>
<img src="file/img1.png">
</body>
FileServlet.java
Servlet that retrieves the image.
#WebServlet("/file/*")
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
private String filePath;
public void init() throws ServletException {
this.filePath = "/files";
}
protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("================In do get==================");
// Get requested file by path info.
String requestedFile = request.getPathInfo();
System.out.println("Requested File: " + requestedFile);
// Check if file is actually supplied to the request URI.
if (requestedFile == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Decode the file name (might contain spaces and on) and prepare file object.
File file = new File(filePath, URLDecoder.decode(requestedFile, "UTF-8"));
System.out.println("Filename: " + file.getName());
System.out.println(file.getAbsolutePath());
// Check if file actually exists in filesystem.
if (!file.exists()) {
System.out.println("DOES NOT EXIST");
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// more code here but it does not matter
}
}
The problem is that the image does not load. The path printed at the console seems to be correct. What am I missing here?
For me your problem is here
<img src="file/img1.png">
It doesn't seem to be the correct path for the next reasons:
The root directory is /.../webapps/ROOT/files so it should start with files not file.
The name of the file should be img + a random long + .png here you set the random long to 1 which doesn't seem to be correct
As it is in the ROOT webapp, you should rather put an absolute path instead of a relative path, in other words the path should start with a slash
I am using Tess4j API for performing OCR and have created a dynamic web project in eclipse. If I create a new java class directly under the Java resources folder, the code is working fine.
public static void main(String[] args){
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try{
String result = instance.doOCR(image);
System.out.println(result);
}catch(TesseractException e){
System.err.println(e.getMessage());
}
}
However I am getting an exception when I am calling the same code from my Servlets doPost method.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Validate valObj = new Validate();
valObj.validate();
}
public void validate() {
File image = new File("Scan0008.jpg");
ITesseract instance = new Tesseract();
try {
String result = instance.doOCR(image);
System.out.println(result);
} catch (TesseractException e) {
System.err.println(e.getMessage());
}
}
I have included all the required jars under lib folder of WEB-INF. Have also added the jars in the projects build path. Could anyone please let me know what I am doing wrong.
Exception :
java.lang.IllegalStateException: Input not set
23:33:45.002 [http-bio-8080-exec-5] ERROR net.sourceforge.tess4j.Tesseract - Input not set
java.lang.IllegalStateException: Input not set
I think your current directory is different when you are calling from servlet. the current directory is you tomcat bin folder. so when you are calling like this:
File image = new File("Scan0008.jpg");
your scan0008.jpg must be put in bin folder of tomcat or you must use absolute path of your file.
I'd like to test my servlet by printing the results to the console. System.out.println does not seen to work for a servlet. Does anyone know how I can achieve this? Main purpose is for debugging at a later stage.
public class GetAllStaff extends HttpServlet {
private static final long serialVersionUID = 1L;
static StaffDAO dao = new StaffDAO();
static ArrayList<Staff> sList = null;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
sList = dao.getAllStaff();
for (int i = 0; i < sList.size(); i++)
{
}
}
You could use
ServletContext context = getServletContext( );
context.log("This is a log item");
The logs are not printed in Eclipse console but can be found at logs folder of servlet container (say Apache Tomcat)
Reference: http://www.tutorialspoint.com/servlets/servlets-debugging.htm
You may want to print everything on a browser with the following code?
PrintWriter out = res.getWriter();
out.println("Some information on the browser...");
P.S I tried System.out.println("something"); in my IDE (Intellij), the result showed up in the console.
The following servlet creates a directory named Shared and then copies the video into this directory.Next it presents the link,to download this video. But when I click the link,nothing happens. Why is this ?
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String path = request.getServletContext().getRealPath("/") + "Shared/" + "sweet-love-story-that-might-make-your-day[www.savevid.com].3gp";
path = path.replace("\\","/");
try {
File f = new File(request.getServletContext().getRealPath("/") + "Shared/");
if(!f.exists()) {
f.mkdir();
// now copy the animation to this directory
} else {
System.out.println("directory already made");
}
writer.println("<html> <head> <title> </title> </head>");
writer.println("<body>");
writer.println("Click to download");
writer.println("</body>");
writer.println("</html>");
}catch(Exception exc) {
exc.printStackTrace();
}
}
Ironically when I write a html that is in the same directory as the video (in Shared) I am able to download/see the video. Why doesn't the link work when I access it via localhost ?
(I am using Tomcat)
**Note: The statement request.getServletContext().getRealPath("/") prints W:\UnderTest\NetbeansCurrent\App-1\build\web**
The following are the snapshots of html accessed from localhost and locally respectively.
and