There is a servlet that accepts files from the client and stores them in a folder.
It is now necessary to list the files from this folder and create links to them (that is, click on the file name and it's downloaded from you).
Now just output a list of files in the form of text. How to create links to them? I read that for this it is enough to expose the headers, but how this is done and has not been found.
Sample Code:
public class FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String param = "/dirs";
PrintWriter w = res.getWriter();
res.setContentType("text/html");
String root="/dirs";
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
w.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
w.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + param + "</FONT></H3><HR>");
w.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++)
printName(fileList[i], w);
w.println("</TABLE><HR>");
}
private void printName(File name, PrintWriter output)
{
String type = name.isDirectory()
? " (Directory)" : " (File)";
output.println("<TR><TD>" + type + "</TD><TD><FONT COLOR=BLUE>"
+ name.getName() + "</FONT></TD></TR>");
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
I solved my problem. In case someone needs it or someone knows a more beautiful way.
import java.io.File;
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 FileListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
response.setContentType("text/html");
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
java.io.File dir = new java.io.File(root);
File[] fileList = dir.listFiles();
printWriter.println("<H2><FONT COLOR=TEAL>" + "Total number of files in the choosen directory - " +
fileList.length + "</FONT></H2>");
printWriter.println("<H3><FONT COLOR=PURPLE>" +
"Directory path - " + root + "</FONT></H3><HR>");
printWriter.println("<TABLE BORDER=0 CELLSPACING=5>");
for(int i = 0; i < fileList.length; i++) {
printName(fileList[i], printWriter);
}
printWriter.println("</TABLE><HR>");
}
private void printName(File file, PrintWriter output)
{
System.out.println(file.getName());
output.println("<tr><td><a href=\"https://Upload/DownloadServlet?name="
+file.getName()+"\">" + file.getName() + "</a></td></tr>" );
}
public String getServletInfo()
{
return "This servlet shows a content of a directory" +
"mentioned in dirToShow parameter or property.";
}
}
And DownloadServlet
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class DownloadServlet
*/
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public DownloadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String fileType = "multipart/form-data";
response.setContentType(fileType);
response.setHeader("Content-disposition", "attachment; filename=" + name);
File currentFolder = new File(".");
File workingFolder = new File(currentFolder, "Sorted files");
String root = workingFolder.getAbsolutePath();
File file = new File(root + File.separator + name);
OutputStream output = response.getOutputStream();
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[4096];
int lenght;
while( ( lenght = input.read(buffer) ) > 0 ) {
output.write(buffer, 0, lenght);
}
input.close();
output.flush();
output.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Related
I have set cookies in a servlet class and read those cookies values in another servlet class. In another servlet class along with the set cookies values, I am getting some unusual values.
My Home.java servlet class results set ::
first result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello RACHEL
Hello last_name, Hello KIM
second result
Hello JSESSIONID, Hello A502A7144AE035ED9B1A2549F5C7B74B
Hello first_name, Hello CAIRO
Hello last_name, Hello SENGAL
in both the results I am getting the set cookies values and names but along with them I am getting JSESSIONID and A502A7144AE035ED9B1A2549F5C7B74B. I can't understand from where do these cookies values are appearing? How can I remove this? Why are these values appearing?
My code :
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Authenticate
*/
#WebServlet("/Authenticate")
public class Authenticate extends HttpServlet {
private static final long serialVersionUID = 1L;
public Authenticate() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
out.print("Welcome "+ firstname);
// Create cookies for first and last names.
Cookie f_name = new Cookie("first_name", firstname);
Cookie l_name = new Cookie("last_name", lastname);
// Add both the cookies in the response header.
response.addCookie( f_name );
response.addCookie( l_name );
//creating submit button
out.print("<form action='Home' method='post' >");
out.print("<input type='submit' value='cookie click' />");
out.print("</form>");
out.close();
}
catch(Exception ex)
{
System.out.println("exception occured");
System.out.println(ex.toString());
}
}
}
Code for Home servlet
#WebServlet("/Home")
public class Home extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Home() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[] = request.getCookies();
if (ck != null) {
for (int i = 0; i < ck.length; i++) {
out.print("Hello " + ck[i].getName() + ", ");
out.print("Hello " + ck[i].getValue());
out.print("<br />");
}
}
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
My servlet lets user upload a file, I've created a button to view the uploaded file.
now, on click of that button I want the uploaded file to open. How do I do this on the JSP side or servlet.java side?
it is located in WEB-INF/Uploads/my.txt folder.
=====================================EDIT=========================================
Based on answers below, I've modified my code and I'm pasting the same here for more answers,
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext context = getServletContext();
String path = context.getRealPath("/u/poolla/workspace/FirstServlet/WebContent/WEB-INF/Uploads/Config.txt");
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String firstline = br.readLine();
System.out.println(firstline);
}
PS: This is not working, still looking for answers.
Thank You!
You can do this by using the ServletContext:
ServletContext#getResourceAsStream()
As far as I know the classLoader can only access WEB-INF/classes and WEB-INF/lib but not WEB-INF/Uploads. Try to put the file in the classes sub-folder.
try to do the following :
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/Uploads/my.txt");
then read the URL content like the following :
BufferedReader br = new BufferedReader(new InputStreamReader(
is));
int value=0;
// reads to the end of the stream
while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;
// prints character
System.out.println(c);
}
and please give me some feedback
Hope That Helps .
if it is a image file then u can do following using jstl tag
<img src="<c:url value='Uploads/yourImg.png' />">
Assuming you web-inf file in the src folder you can try folloing
File f = new File("src/web-inf/Uploads/YourFile.txt");
If the file name is not fixed then use <form> in jsp to get the file name from the jsp page
In Java class: If you need to direct access then you have to extends HttpServlet like
public class FileReader extends HttpServlet {
....
....
....
public void readAFile(){
ServletContext servletContext=super.getServletContext();
InputStream initFileStream = servletContext.getResourceAsStream("/WEB-INF/<path>");
//TODO : according to your need
}
{
Tested Servlet
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class STest
*/
#WebServlet("/STest")
public class STest extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public STest() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
process();
}
private void process() throws IOException {
ServletContext servletContext=super.getServletContext();
InputStream initFileStream = servletContext.getResourceAsStream("/WEB-INF/test.txt");
BufferedReader reader=new BufferedReader(new InputStreamReader(initFileStream));
StringBuffer stringAll=new StringBuffer();
while(reader.ready()){
stringAll.append(reader.readLine());
}
System.out.println(stringAll);
}
}
In your Servlet class, you can use the following code :
ServletContext context = getServletContext();
String path = context.getRealPath("/WEB-INF/Uploads/my.txt");
Then the path should be correct. And then you can use a normal FileReader :
FileReader reader = new FileReader(path);
BufferedReader br = new BufferedReader(reader);
String firstline = br.readLine();
System.out.println(firstline);
...
I am trying to upload a file to web server and read the same. file uploading is working and the file is uploaded but when i call some methods to manipulate saved file the method is not getting called.
in the following file i call readFile method from post method.
I am using tomcat 7.0. Please save me from this. the code is :
package org.slingemp.fileupload;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slingemp.bean.setNotification;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Servlet implementation class Fileupload
*/
#WebServlet("/Fileupload")
public class Fileupload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Fileupload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("file upload started....Antony");
// TODO Auto-generated method stub
List fileItemsList = null;
float filesize = 0;
String _fileLink;
String _fileName = null;
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
// Change upload with your directory
HttpSession session = request.getSession(true);
try {
if (ServletFileUpload.isMultipartContent(request)) {
ServletFileUpload servletFileUpload = new ServletFileUpload(
new DiskFileItemFactory());
try {
fileItemsList = servletFileUpload.parseRequest(request);
} catch (FileUploadException ex) {
Logger.getLogger(Fileupload.class.getName()).log(
Level.SEVERE, null, ex);
// Change above line replace FileUploadExample with your
// file name
}
String optionalFileName = "";
FileItem fileItem = null;
Iterator it = fileItemsList.iterator();
while (it.hasNext()) {
FileItem fileItemTemp = (FileItem) it.next();
if (fileItemTemp.isFormField()) {
if (fileItemTemp.getFieldName().equals("filename")) {
optionalFileName = fileItemTemp.getString();
}
/*
* If you want to pass some other data from JSP page.
* You can access then in this way. For each field you
* have do create if like below. if
* (fileItemTemp.getFieldName
* ().equals("Name of other field like:Firstname")) {
* String Firstname = fileItemTemp.getString(); }
*/
} else {
fileItem = fileItemTemp;
}
}
if (fileItem != null) {
long size_long = fileItem.getSize();
filesize = size_long / 1024;
filesize = filesize / 1000;
// If you want to limit the file size. Here 30MB file size
// is allowed you can change it
//if (filesize > 30.0) {
// Pass error message in session.
//setNotification _sN = new setNotification();
//_sN.setError("File size can't be more than 30MB");
//session.setAttribute("error", _sN);
//} else {
_fileName = fileItem.getName();
if (fileItem.getSize() > 0) {
if (optionalFileName.trim().equals("")) {
_fileName = FilenameUtils.getName(_fileName);
} else {
_fileName = optionalFileName;
}
_fileLink = "../accesscarddata/" + _fileName;
try {
File file = new File(new File(_uploadDir + "/"),fileItem.getName());
fileItem.write(file);
} catch (Exception e) {
e.printStackTrace();
}
setNotification _sN = new setNotification();
_sN.setError("File Uploaded to : " + _fileLink + "");
session.setAttribute("accesscardDatafileNname", _fileName);
session.setAttribute("error", _sN);
}
//}
}
//SELECT * FROM leave_application WHERE from_date >= '2004-01-01' AND to_date <'2004-01-30' and emp_id=128
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("before calling readFile");
readFile(request,response);
System.out.println("after calling readFile");
response.sendRedirect("index.jsp");
}
protected void readFile(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("readFile is called..");
Map employeeMap = null;
String fileName = "",employeeAttendanceFilePath="";
String _uploadDir = getServletContext().getRealPath("/accesscarddata/");
HttpSession session = request.getSession(true);
if(session.getAttribute("accesscardDatafileNname") != null)
fileName = (String) session.getAttribute("accesscardDatafileNname");
employeeAttendanceFilePath = _uploadDir+fileName;
System.out.println("File Path : "+employeeAttendanceFilePath);
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(employeeAttendanceFilePath);
// Create an excel workbook from the file system.
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);// gets the first sheet on workbook
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
//count=count+1;
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
session.setAttribute("sheetData", sheetData);
processEmployeeAttendance(request,response);
System.out.println("employeeMap : "+employeeMap);
if(session.getAttribute("employeeMap")!=null)
employeeMap = (LinkedHashMap) session.getAttribute("sheetData");
Iterator<Map.Entry> entries = employeeMap.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
}
protected void processEmployeeAttendance(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
System.out.println("processEmployeeAttendance is called...");
String tempEmpid="",strdepartment="";
int j=1;
List sheetData =null;
HttpSession session = request.getSession(true);
if(session.getAttribute("sheetData")!=null)
sheetData = (ArrayList) session.getAttribute("sheetData");
Map employeeMap = new LinkedHashMap();
Map tempEmployeeMap = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
HSSFCell employeeid = (HSSFCell) list.get(0);
HSSFCell department = (HSSFCell) list.get(3);
HSSFCell date = (HSSFCell) list.get(5);
strdepartment = department.getRichStringCellValue().getString();
if(!tempEmpid.equals("")){
if(tempEmpid.equals(employeeid.getRichStringCellValue().getString()) && !(employeeid.getRichStringCellValue().getString().equals("EmpID") || date.getRichStringCellValue().getString().equals("Date") || department.getRichStringCellValue().getString().equals("Department"))){
if(!(strdepartment.equals("Temporary Card") || strdepartment.equals("Contractor"))){
employeeMap.put(employeeid.getRichStringCellValue().getString()+"_"+j,date.getRichStringCellValue().getString());
// System.out.println("j value : "+j+":"+employeeid.getRichStringCellValue().getString()+"_"+j+","+date.getRichStringCellValue().getString());
j++;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
j=0;
}
}else{
tempEmpid = employeeid.getRichStringCellValue().getString();
}
// System.out.println("");
}
session.setAttribute("employeeMap", employeeMap);
}
}
I wanted to put it as a comment, but somehow I am unable to comment.
My suggestion would be to debug the code using your IDE. Put breakpoints at relevant positions and see where its going.
I am using spring framework and i am having Index.jsp like :
Code:
<html>
<head></head>
<body>
<p>File Upload</p>
<form action="ImportService" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
</form>
</body>
I have ImportService as
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class ImportService extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "c:\\files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if (!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
// String realPath =
// getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(DESTINATION_DIR_PATH);
if (!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH
+ " is not a directory");
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = "param";
String value = request.getParameter(name);
String welcomeMessage = "Welcome " + value;
System.out.println("Message=" + welcomeMessage);
response.setContentType("text/html");
response.setContentType("text/plain");
System.out.println("Inside Get Method");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside Post Method");
PrintWriter out = response.getWriter();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
/*
* Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
/*
* Set the temporary directory to store the uploaded files of size above
* threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if (item.isFormField()) {
out.println("File Name = " + item.getFieldName()
+ ", Value = " + item.getString());
} else {
// Handle Uploaded files.
out.println("Field Name = " + item.getFieldName()
+ ", File Name = " + item.getName()
+ ", Content type = " + item.getContentType()
+ ", File Size = " + item.getSize());
}
out.close();
}
} catch (FileUploadException ex) {
log("Error encountered while parsing the request", ex);
} catch (Exception ex) {
log("Error encountered while uploading file", ex);
}
// doGet(request, response);
}
}
In my web.xml, I have
<servlet>
<servlet-name>ImportService</servlet-name>
<servlet-class>com.service.ImportService</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImportService</servlet-name>
<url-pattern>/ImportService/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/Index.jsp</welcome-file>
</welcome-file-list>
Now when I try to hit the url: http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp then it gives me blank message and html form is not rendered.
Any suggestions or pointers?
change your entry URL from http://localhost:8080/delta-webapp/ImportService/jsp/Index.jsp
to http://localhost:8080/delta-webapp/jsp/Index.jsp
You've mapped ImportService servlet to handle all requests to /ImportService/*.
Your index.jsp is located at /jsp/Index.jsp. If instead you just put /delta-webapp It /may/ work.
In general though, I don't think welcome files have hard coded paths. Typically you specify something like index.jsp as your welcome file and if nothing handles the request at a particular location, it will fall back to see if one of the welcome files listed is available and will render that.
Hi just wanted to share this servlet it takes 2 arguments ( img-> image name , rot ->rotation of the images) loads the image from the images directory rotates it and outputs it to the servlet stream
you can find it in the answer below
package at.buchinger.mapdisplay;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RotatedImage
*/
public class RotatedImage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RotatedImage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String img = (String) request.getParameter("img");
String path = getServletContext().getRealPath("image/"+img);
String r;
r=request.getParameter("rot");
if(r==null){
r="0";
}
double rot = Double.parseDouble( r);
BufferedImage image = ImageIO.read(new File(path));
AffineTransform tx = new AffineTransform();
tx.rotate(Math.toRadians(rot), image.getWidth()/2, image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
ServletContext sc = getServletContext();
String filename = getServletContext().getRealPath(path);
// Get the MIME type of the image
String mimeType = sc.getMimeType(filename);
if (mimeType == null) {
sc.log("Could not get MIME type of "+filename);
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
// Set content type
response.setContentType(mimeType);
ServletOutputStream out = response.getOutputStream();
Iterator iter = ImageIO.getImageWritersByMIMEType(mimeType);
ImageIO.write(image, "png", out);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}