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);
...
Related
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);
}
}
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);
}
}
}
Here is my servlet class
package com.zaggle;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FirstServlet
*/
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public FirstServlet() {
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 {
// TODO Auto-generated method stub
String[] data;String val=null,name;
name=request.getParameter("excelsheet");
System.out.println(name);
response.setContentType("text/html");
UploadExcel ex= new UploadExcel();
data=ex.procedure(name);
System.out.println(name);
request.setAttribute("val", data);
System.out.println(val);
String destination="/NewFile1.jsp";
RequestDispatcher rd=getServletContext().getRequestDispatcher(destination);
//doGet(request, response);
rd.forward(request, response);
}
}
Here is my normal java class which I am using in servlet class
package com.zaggle;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.plaf.basic.BasicInternalFrameTitlePane.RestoreAction;
import org.apache.poi.hssf.record.formula.functions.Goto;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class UploadExcel {
public String[] procedure(String filename) {
// Scanner scanner = new Scanner(System.in);
//System.out.println("Please enter a filename with extention to upload");
String fileName = "C:\\"+filename;//+scanner.nextLine();
String[] dataHolder = ReadCSV(fileName);
// printCellDataToConsole(dataHolder);
return dataHolder;
}
public static void printCellDataToConsole(Vector dataHolder) {
// TODO Auto-generated method stub
for(int i=0;i<dataHolder.size();i++)
{
Vector column=(Vector)dataHolder.elementAt(i);
for (int j = 0; j < column.size(); j++) {
HSSFCell myCell = (HSSFCell) column.elementAt(j);
String stringCellValue = myCell.toString();
System.out.print(stringCellValue + "\t");
}
System.out.println();
}
}
public static String[] ReadCSV(String fileName) {
// TODO Auto-generated method stub
Vector cellVectorHolder = new Vector();
String[] col = null;
try {
FileInputStream myInput = new FileInputStream(fileName);
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector column = new Vector();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
column.addElement(myCell);
}
col=column.toString().split(" ");
cellVectorHolder.addElement(column);
}
} catch(IOException ie)
{
System.err.println("Please enter a valid input");
}
catch (Exception e) {
e.printStackTrace();
}
//return cellVectorHolder;
return col;
}
}
When i run I am getting the error like this
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/POIFSFileSystem
com.zaggle.UploadExcel.ReadCSV(UploadExcel.java:52)
com.zaggle.UploadExcel.procedure(UploadExcel.java:24)
com.zaggle.FirstServlet.doPost(FirstServlet.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Why am I getting this error. Can anyone help me?
It looks like you've forgotten to include the POI library on the CLASSPATH (e.g. It's not referenced by your web app). You can include this lib under WEB-INF/lib (in your WAR archive or in the exploded directory format) or it can sit elsewhere in your app server/web server CLASSPATH.
you are getting the exception in this line
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
You are trying to use a library that is not included in your project.
Make sure that import org.apache.poi library in in the web-inf/lib directory
Your POI jars are not in the classpath.You can include this lib under WEB-INF/lib..
Also check could be that your version of jars is different than those expected.
Make sure apache-poi.jar under WEB-INF/lib.
Optional : Based on the your web server or application server, put apache-poi.jar into server-home/lib(depend on server). It is not best solution.
Note
Now, you are developing web application, don't use uploaded file with specific path (eg: C:\....). If so, the program will find out the upload file on local machine Web Server is running. First you have to upload file as byte[] or InputStream or use other third party lib. After that, you have to change HSSFWorkbook.
I'm using Jersey to create RESTful API resources, and ResponseBuilder to generate the response.
Example code for the RESTful resource:
public class infoResource{
#GET
#Path("service/{id}")
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getCompany(#PathParam("id")String id) {
//company is just a POJO.
Company company = getCompany(id);
return Response.status(200).entity(company).build();
}
}
In the response, it's returning chunked transfer encoding in the response headers. What is the proper way in the "Jersey world" to have it return the Content-Length header instead of the Transfer-Encoding: chunked header in the response headers?
Selecting Content-Length or Transfer-Encoding is just those Containers choice. It's really a matter of buffer size.
One possible solution is providing a SevletFilter which buffers all those marshalled bytes and sets Content-Length header value.
See this page.
#WebFilter
public class BufferFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
final ByteArrayOutputStream buffer =
new ByteArrayOutputStream();
// prepare a new ServletResponseWrapper
// which returns the buffer as its getOutputStream();
chain.doFilter(...)
// now you know how exactly big is your response.
final byte[] responseBytes = buffer.toByteArray();
response.setContentLength(responseBytes.length);
response.getOutputStream().write(responseBytes);
response.flush();
}
#Override
public void destroy() {
}
}
In you class that extends ResourceConfig you can set the buffer size. Responses above this size will be chunked, below will have Content-Length.
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
//your initialization
property(CommonProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, 2000000);
}
}
For example, if your inputstream is read from a local file system, just
add:
response.header( "Content-Length", file.length() );
Check the full code for a clearer explanation:
#Path("/files")
public class FileDownloadService {
private static final String TXT_FILE = "C:\\your file";
#GET
#Path("/txt")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getTextFile() throws IOException {
File file = new File(TXT_FILE);
FileInputStream inStream = new FileInputStream(file);
ResponseBuilder response = Response.ok((Object) inStream);
response.header("Content-Disposition", "attachment; filename=\"filename\"");
response.header( "Content-Length", file.length() );
return response.build();
}
}
The client side is a Apache HttpClient code.
An answer to a very similar question on StackOverflow can be found here
I've copied it here to make sure it's not converted to a comment:
A great sample filter for doing this, that can be used standalone from the project, is this ContentLengthFilter.java from the Carrot2 project on github.
Note that uses a response wrapper with a byte stream to solve the issue, so this also ensures that Transfer-Encoding: Chunked doesn't get set by some other Filter/code in the filter chain, and override your Content-Length header when it's set. You can verify that by testing this with larger files, as they'd normally be chunked in the response.
I'm going to copy the contents of the file here as well, to ensure it doesn't become a broken link:
/*
* Carrot2 project.
*
* Copyright (C) 2002-2010, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.webapp;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
/**
* Buffer the output from filters below and set accurate <code>Content-Length</code>
* header. This header is required by flash, among others, to display progress
* information.
*/
public class ContentLengthFilter implements Filter
{
private final static class BufferingOutputStream extends ServletOutputStream
{
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
#Override
public void write(int b) throws IOException
{
baos.write(b);
}
#Override
public void write(byte [] b) throws IOException
{
baos.write(b);
}
#Override
public void write(byte [] b, int off, int len) throws IOException
{
baos.write(b, off, len);
}
}
private final static class BufferingHttpServletResponse extends
HttpServletResponseWrapper
{
private enum StreamType
{
OUTPUT_STREAM,
WRITER
}
private final HttpServletResponse httpResponse;
private StreamType acquired;
private PrintWriter writer;
private ServletOutputStream outputStream;
private boolean buffering;
public BufferingHttpServletResponse(HttpServletResponse response)
{
super(response);
httpResponse = response;
}
#Override
public ServletOutputStream getOutputStream() throws IOException
{
if (acquired == StreamType.WRITER)
throw new IllegalStateException("Character stream already acquired.");
if (outputStream != null)
return outputStream;
if (hasContentLength())
{
outputStream = super.getOutputStream();
}
else
{
outputStream = new BufferingOutputStream();
buffering = true;
}
acquired = StreamType.OUTPUT_STREAM;
return outputStream;
}
#Override
public PrintWriter getWriter() throws IOException
{
if (acquired == StreamType.OUTPUT_STREAM)
throw new IllegalStateException("Binary stream already acquired.");
if (writer != null)
return writer;
if (hasContentLength())
{
writer = super.getWriter();
}
else
{
writer = new PrintWriter(new OutputStreamWriter(
getOutputStream(), getCharacterEncoding()), false);
}
acquired = StreamType.WRITER;
return writer;
}
/**
* Returns <code>true</code> if the user set <code>Content-Length</code>
* explicitly.
*/
private boolean hasContentLength()
{
return super.containsHeader("Content-Length");
}
/**
* Push out the buffered data.
*/
public void pushBuffer() throws IOException
{
if (!buffering)
throw new IllegalStateException("Not buffering.");
BufferingOutputStream bufferedStream =
(BufferingOutputStream) outputStream;
byte [] buffer = bufferedStream.baos.toByteArray();
httpResponse.setContentLength(buffer.length);
httpResponse.getOutputStream().write(buffer);
}
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException
{
final HttpServletResponse response = (HttpServletResponse) resp;
final BufferingHttpServletResponse wrapped =
new BufferingHttpServletResponse(response);
chain.doFilter(req, wrapped);
if (wrapped.buffering)
{
wrapped.pushBuffer();
}
}
public void destroy()
{
// Empty
}
public void init(FilterConfig config) throws ServletException
{
// Empty
}
}
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);
}
}