how to apply css files in servlet code written inside jsp file? - java

Below is my code. I have all css files in webcontent root and inside css folder.
String cssLocation = request.getContextPath() + "/WebContent/css/style.css";
String cssTag = "<link rel='stylesheet'<img class=gallery_img'> type='text/css' href=' "+ cssLocation +" '>";
out.println("<h4> <p><div class='gallery_img'> " + rs.getString("title") + "</div></div></P></h4>");
out.println("");
out.println("<a href='#'><div style='float:left;width:10% border:10px solid;padding:20px ;'><link rel='stylesheet' type='text/css' href='css/style.css'><table style='width:50%' ><td><img width='230' height='230' src=displayphoto?id=" + rs.getString("id") + " style='opacity: 1'></img></td></table></body></a> <p/>");

All jsp files are converted into servlet java files and compiled, you can simply call this jsp file and go get the servlet file from the cache directory. copy the css part and paste into your own servlet,you can even make it a function or a seperate class.
If you can't find the servlet cache directory simply search the name of the jsp file without extension on the hard drive, you will see that there is a java file with that name.
Good Luck

Related

Need to hide the files which are being used from Assets folder

I am using an offline application which has html,css and js files in the assets folder.When i install the application on a device a can access those files from file:////storage/emulated/0/Android/data/myapp.name/files. I need a way to hide these files at it causes a security issue. I load my app from UI webview through one of the files in assets folder
I need a way to hide these files at it causes a security issue
First, they are not files. They are assets. They are stored in the APK file, not as files on the filesystem.
Second, you cannot "hide" assets. They are in your APK, and anyone can take your APK and retrieve those assets. It is unlikely that anyone will bother to do this.
You wont be able to hide assets.
As a workaround, you can do the following:
Copy the content of your HTML, CSS and JS files in a long text String.
When app is loaded for the first time, load the string content and create a Private file at runtime and save it in Internal Storage.
Files written in Internal storage by an app can not be accessed by any other apps, including a file explorer. so they are safe from misuse.
use this code to store private file in internal storage:
String filename = "yourfile.html";
String string = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
To protect assets folder information If the html file is either css or js, the easiest way is to:
Write your code in the html editor first, and then enter it in a Java class as follows :
public class Content{
public static final String myContent ="<!DOCTYPE html> ... </html> "
And then call through the loadDataWithBaseURL method
webView.loadDataWithBaseURL(null,Content.myContent, "text/html" , "UTF-8" ,null);
And you can call js and css in html code :
...
<head>
<link rel="stylesheet" type="text/css"
href="file:///android_asset/css/custom.css" />
<script src="file:///android_asset/js/code.jquery.js"></script>
</head>

Attaching a CSS file to a Java Servlet in Tomcat [duplicate]

This question already has answers here:
Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
(9 answers)
Closed 5 years ago.
After a lot of looking around on various forums and such, I was not able to find an answer to my question.
I want to attach a stylesheet to my servlet instead of having to use <style> tags.
I am using Apache Tomcat 7 in Eclipse and I am manually writing the html code (via a PrintWriter).
I've tried putting the .css file in the ROOT of the WebApp. I've tried putting it in the css. Nothing is working.
Can someone point me in the right direction?
Here is some code that I tried.
Attempt 1 (css is in a folder. WebContent/css:
String cssLocation = request.getContextPath() + "/WebContent/css/styles2.css";
String cssTag = "<link rel='stylesheet' type='text/css' href='" + cssLocation + "'>";
Attempt 2 (css is in the ROOT):
String cssLocation = request.getContextPath() + "/styles2.css";
String cssTag = "<link rel='stylesheet' type='text/css' href='" + cssLocation + "'>";
Neither of those worked.
EDIT: Here is my directory structure:
PROJECT ROOT
src
testPackage
DownloadServlet.java
WebContent
css
styles2.css
files
fonts
js
META-INF
WEB-INF
index.html
To explain: I am trying to reference /WebContent/css/styles2.css in DownloadServlet.java
How I am doing that:
In the method 'doGet', I am initializing a `PrintWriter'. I'm printing out:
<html>
<head>
HERE IS WHERE THE LINK NEEDS TO GO
</head>
<body>
...
</body>
</html>
Where the text "HERE IS WHERE THE LINK NEEDS TO GO" is, that is where I need the link to the css file. I've tried the methods above, but I had no luck.
Just a guess: Try String cssTag = "<link rel='stylesheet' type='text/css' href='/css/styles.css'>";
The browser will look for the css file in the sub-folder of the root directory of the server, which is in your case the WebContent-directory. You usually don't need to call request.getContextPath() when linking resources inside HTML tags.
First you create the css file, suppose style.css in the folder name css inside the WebContent directory of your project.
Then, you must know the tomcat server path where the .css file is located.
String cssTag="<link rel='stylesheet' type='text/css' href='css/style.css'>"
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<head><title>Title Name</title>"+cssTag+"</head>");
out.println("<body>");
/*
Your code
*/
out.println("</body></html>")

Servlet in Eclipse - Where to put static content [duplicate]

This question already has answers here:
Simplest way to serve static data from outside the application server in a Java web application
(10 answers)
Closed 9 years ago.
When writing a servlet with Eclipse, where am I to put my static content (images, CSS, etc.), so that I can make my HTML link to it (e.g. <img src="http://localhost:8080/context/image.png>). I have tried putting it into the WebContent directory, but that didn't work (or I didn't know how to link to it, I tried <img src="image.png"> and also <img src="http://localhost:8080/context/image.png">).
I attached an image of my Project Explorer, so you can maybe sort it in.
To make it easier to find, here is everything I posted in comments or elsewhere:
The project's web.xml: http://pastebin.com/sTg4ugyw
My Servlet code: http://pastebin.com/az97bZAY
One of my HTML templates: http:pastebin.com/6KALf0Bw
Create a test.html file and place it at /Blog/WebContent/test.html in your Eclipse project.
<html>
<head>
<title>Test WebContent</title>
</head>
<body>
<img src="images/test.png" />
</body>
</html>
Also place a test.png image file inside the /Blog/WebContent/images folder.
Now, point your browser to http://localhost:8080/<your-web-app-name>/test.html and check if test.png gets rendered or not. If yes, then the problem lies in the way you're writing HTML output from your servlet.
For a sample ImgServlet configured as
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>pkg.path.to.ImgServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
your doGet() method should ouput HTML as
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Test WebContent</title></head>" +
"<body><img src=\"images/test.png\" /></body></html>");
EDIT: To print all the request parameters your servlet is receiving add the following just before your handleRequest() method call (which you can comment out also for testing)
PrintWriter out = response.getWriter();
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
out.println(param + " = [" + request.getParameter(param) + "]");
}
Try
<img src="/context/image.png">
But it does depend on how you deploy your application. Anyways, files like images must be inside WebContent folder.
First of all, dont hard code your context in your link, it will make you hard to change the link later if your context path is changed. Instead, use EL to make the relative path:
<img src="${pageContext.request.contextPath}/img/abc.png" />
Secondly, I dont see any image in your WebContent, if you put the image manually into the window folder, you need to refresh eclipse project in order to let eclipse detects all the added files. Right click on your project in the Project Explorer and select Refresh

Java Servlet JSP delete file using apache commons FileUpload

I have been searching this topic for quite a while, and haven't found anything that has been able to solve my problem.. so I turn to you!
I have a JSP where I open a file dialog box to select a file. Previously, I used this to upload the file to a specified directory (in my code). This works fine. I am now trying to use the same code to delete that same file by selecting it in the appropriate directory and passing it off to the servlet, which I included below. I am using the Apache Common FileUpload library to do this.
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// checks if the request actually contains upload file
if (!ServletFileUpload.isMultipartContent(request)) {
// if not, we stop here
return;
}
// configures some settings
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload delete = new ServletFileUpload(factory);
// constructs the directory path to delete file
String deletePath = UPLOAD_DIRECTORY;
// parses the request's content to extract file data
List formItems = delete.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// processes only fields that are not form fields
if (!item.isFormField()) {
String fileName = new File(item.getName()).getName();
String filePath = deletePath + File.separator + fileName;
File storeFile = new File(filePath);
//File storeFile = new File("C:\\temp\\discLogo.txt");
// deletes the file on disk
boolean erased = storeFile.delete();
}
}
UPLOAD_DIRECTORY is where I am storing my files from my upload JSP. The delete method works fine if I uncomment the line I commented out for storeFile with the hardcoded directory, as long as I select a DIFFERENT FILE in the directory initially. This leads me to believe the HttpServletRequest is holding the file in memory somewhere.
Is this correct? is there any way I can release it so I can delete the file I select initially? Or is there a much simpler way to do this?
Thanks!
The File#delete() will return false if the file does not exist at all (use File#exists() to test it beforehand), or if the file is locked because it is been opened by another app or even your own code!
Provided that this file is written do disk beforehand by your own code and guaranteed not opened elsewhere, then you should ensure that you're invoking OutputStream#close() in the finally block after writing the file's content. This problem suggests that you didn't. If you leave the file open after writing to it, then it cannot be deleted until you restart the server/JVM.
Apache Commons IO, which you should already have as a dependency of FileUpload, comes with handy utility methods reducing the file copy and close boilerplate.
InputStream input = item.getInputStream();
OutputStream output = new FileOutputStream(storeFile);
try {
IOUtils.copy(input, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
See also:
How I save and retrieve an image on my server in a java webapp.
What is the object of uploading the file? Are you going to check all the files by content?
I would say the simpler way would be to not upload the whole file. What you want to do is to call some code - JSP/Servlet -, pass as a parameter an ID of the file (most usually the path inside the server) and make it delete the file. If all the files uploaded are in the same folder, then the name should be enough (*).
After all, by uploading the file you are forcing you to have a copy in your PC of the file you want to delete (what if you deleted your local file? Should you not be able to delete the file in the server?)
(*) be sure to perform safety checks so nobody can pass ..\..\WEB-INF\web.xml as a parameter.
you can delete the file because the platform indepenedent solution is like this
File deleteFile = new File(<file Path> ) ;
// check if the file present or not
if( deleteFile.exists() )
deleteFile.delete() ;
Be carefule if the file path is directory then the directory must empty before deleting.
UploadFileorDelete
Looks like my issue was in my JSP. I had the following form initially:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>File Delete</title>
</head>
<body>
<form method="post" action="DeleteServlet"
enctype="multipart/form-data">
Select file to delete: <input type="file" name="dataFile"
id="fileChooser" /><br />
<br /> <input type="submit" value="Delete" />
</form>
</body>
</html>
I changed this by deleting encytype="multipart/form-data" from the form, and was then able to use request.getParameter("dataFile") to get the file name.

How to download a complete web page (with all its contents) in Java?

Using Java, I need to save a complete webpage(with all its contents like images, css, javascript e.t.c) like how we can do with save as-->complete webpage option with HttpClient lib. How can I do this?
You can try lib curl java
http://curl.haxx.se/libcurl/java/
And you can refer to this discussion also
curl-equivalent-in-java
You have to write an application that fetches the html file, parses it and extracts all the references, and then fetches all the files found by parsing.
It's not so easy because some CSS/JS/Images files paths might be "hidden". Just consider the following example:
<script type="...">
document.write("&bla;script" + " type='...' src='" + blahBlah() + "'&bla;" + "&bla;/script&bla;");
</script>
However, fetching page source, parsing in the search for URLs and downloading founded URLs is pretty everything you'll probably need.

Categories

Resources