This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 1 year ago.
I can able to upload image in database but unable to upload into "files" folder. web
#WebServlet(name="AdminServlet",urlPatterns="/AdminServlet")
#MultipartConfig
public class AdminSevlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException, SQLException {
try (PrintWriter out = response.getWriter()) {
UserDAO UserDAO = new UserDAO();
User User = new User();
String sid = request.getParameter("aid");
int id = Integer.parseInt(sid);
String userid = request.getParameter("userid");
String password = request.getParameter("password");
String fname = request.getParameter("fname");
String ic = request.getParameter("ic");
String gender = request.getParameter("gender");
String dob = request.getParameter("dob");
String addr = request.getParameter("addr");
String email = request.getParameter("email");
String phoneNo = request.getParameter("phoneNo");
String dept = request.getParameter("dept");
String position = request.getParameter("position");
String eduqual = request.getParameter("eduqual");
String role = request.getParameter("role");
Part part = request.getPart("file"); // Retrieves <input type="file" name="file">
String image = part.getSubmittedFileName();
String path = getServletContext().getRealPath("./"+"web"+File.separator+"files"+File.separator+image);
InputStream is = part.getInputStream();
boolean succs = uploadFile(is, path);//
User.setadmin_id(id);
User.setuser_id(userid);
User.setpassword(password);
User.setuser_name(fname);
User.setIC(ic);
User.setGender(gender);
User.setdob(dob);
User.setAddress(addr);
User.setemail(email);
User.setphoneNo(phoneNo);
User.setDepartment(dept);
User.setPosition(position);
User.setEducationbackground(eduqual);
User.setRole(role);
User.setimage(image);
int result = UserDAO.addUser(User);
RequestDispatcher dispatcher = request.getRequestDispatcher("/view-user");
dispatcher.forward(request, response);
}
}
public boolean uploadFile(InputStream is, String path){
boolean test = false;
try{
byte[] byt = new byte[is.available()];
is.read();
FileOutputStream fops = new FileOutputStream(path);
fops.write(byt);
fops.flush();
fops.close();
test = true;
}catch (Exception e){
e.printStackTrace();
}
return test;
}
This is the image upload servlet. Once the image has been uploaded it should be inserted in the files folder. I don't know what mistake I have done. Could anyone let me know what is the problem? Do I need to add upload directory or the file path C: inside?
Updated answer and changed it
public boolean uploadFile(InputStream is, String path) {
boolean test = false;
try {
File targetFile = new File(path);
Files.copy(is, targetFile.toPath());
test = true;
} catch (Exception e) {
e.printStackTrace();
}
return test;
}
Related
#Controller
#RequestMapping(value = "/admin/room")
public class Roomcontroller {
#Autowired
private RoomService roomService;
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws SQLException {
map.addAttribute("Room", roomService.getAll());
return "admin/room/index";
}
#RequestMapping(value = "/addroom", method = RequestMethod.GET)
public String addRoom() throws SQLException {
return "admin/room/addroom";
}
#RequestMapping(value = "/editroom/{ro_id}", method = RequestMethod.GET)
public ModelAndView edit(#PathVariable("ro_id") int ro_id) throws SQLException {
ModelAndView mv = new ModelAndView("admin/room/editroom");
mv.addObject("Room", roomService.getById(ro_id));
return mv;
}
#RequestMapping(value = "/deleteroom/{ro_id}", method = RequestMethod.GET)
public String delete(#PathVariable("ro_id") int ro_id) throws SQLException {
roomService.delete(ro_id);
return "redirect:/admin/room";
}
this portion of the code is used for saving image and other entities but I am not able to see the image stored in desired folder
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("roomType") String roomType,
#RequestParam("roomDescription") String roomDescription, #RequestParam("roomNumber") int roomNumber,
#RequestParam("file") MultipartFile multipartFile, HttpServletRequest req) throws SQLException, IOException {
Room room = new Room();
room.setRoom_type(roomType);
room.setRoom_description(roomDescription);
room.setRoom_number(roomNumber);
// TO DO : Save room, fetch the id of saved room and set it through
// setter in above object.
if(room.getRo_id()==0){
String serverRootPath = req.getServletContext().getRealPath("");
System.out.println(serverRootPath);
// You can change the directory.
File roomImageDirectory = new File(serverRootPath + "D:\\Hotels\\ploadedImages");
if (!roomImageDirectory.exists()) {
roomImageDirectory.mkdirs();
}
String[] fileNameToken = multipartFile.getOriginalFilename().split("\\.");
// You can change file name to be saved.
String newFileName = "room-" + room.getRo_id() + "." + fileNameToken[fileNameToken.length - 1];
File roomImage = new File(roomImageDirectory, "/" + newFileName);
roomImage.createNewFile();
multipartFile.transferTo(roomImage);
room.setImage(newFileName);
roomService.insert(room);
}
else{
roomService.update(room);
}
return "redirect:/admin/room";
}
}
According to your code, you want to save your file under D:\\Hotels\\ploadedImages. So you don't need to use req.getServletContext().getRealPath(""). Just change your code like this
File roomImageDirectory = new File("D:\\Hotels\\ploadedImages");
...
File roomImage = new File(roomImageDirectory, "/" + newFileName);
I prefer File.separator instead of using / or \\
probably you are constructing a wrong path
try,
String pathToUpload = req.getServletContext().getRealPath("/fileuploads");
File f = new File(pathToUpload);
if(f.exists() && !f.isDirectory()) {
f.mkdir();
}
String orgName = multipartFile.getOriginalFilename();
String filePath = pathToUpload + orgName;
File dest = new File(pathToUpload);
file.transferTo(dest);
you should see file created inside root folder of your application context.
Some background information of what I'm trying to achieve is a user hits the submit button on my JSP page it needs to send the message submitted to a text file and then I need to access the file and retrieve all the messages in the file in my JSP page. Please help me out, I have spent too long and I'm not sure what I need to do to be able to iterate over the hash map to show all the messages.
This is what my code looks like right now:
Controller:
public class TwitServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String twits = "";
String path = getServletContext().getRealPath("/WEB-INF/twit.txt");
HttpSession session = request.getSession();
String tweet = request.getParameter("tweet");
System.out.print(tweet);
String usern = (String) session.getAttribute("user");
String alias = (String) session.getAttribute("uname");
twitDB.insert(tweet, usern, alias, path);
Map test = twitDB.getTwit("/Users/emilio/Desktop/twit.txt");
session.setAttribute("test",test);
getServletContext()
.getRequestDispatcher("/home.jsp").forward(request, response);
}
}
Database(using txtfile for now):
ublic class twitDB {
public static void insert (String twit, String user, String uname, String path) throws IOException {
Date date = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("yyyy/MM/dd");
String dateString = ft.format(date);
File file = new File ("/Users/emilio/Desktop/twit.txt");
try ( PrintWriter out = new PrintWriter(new FileWriter(file, true))){
out.println("[#"+uname+"]:" + " " + dateString);
out.println(user);
out.println(twit);
out.println(".");
out.close();
}
catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
public static Map<String,Tweet> getTwit(String filename) throws IOException {
Map<String,Tweet> tweets = new HashMap<String,Tweet>();
File file = new File ("/Users/emilio/Desktop/twit.txt");
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String uname = in.nextLine();
String name = in.nextLine();
String twit = in.nextLine();
String filler = in.nextLine();
Tweet tweet = new Tweet(uname, name, twit);
tweets.put(uname, tweet);
tweets.put(name, tweet);
tweets.put(twit,tweet );
}
in.close();
return tweets;
}
}
Part of my JSP:
<button type="submit" method="post" class="btn btn-twitter">
<span class="glyphicon glyphicon-pencil"/>Tweet
</button>
</div>
</form>
</div>
</div>
<div class = "row feed">
<p>
<c:forEach items="${test}" var="test">
</c:forEach>
</p>
You are missing tag to do print if you are really getting data from the server.
<c:forEach items="${test}" var="test">
<c:out value="${test}"/>
</c:forEach>
I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}
The functions are working locally, but once I host this message display for some of the pages
java.sql.SQLException: Access denied for user 'myshelf'#'54.235.58.92' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.GeneratedConstructorAccessor71.newInstance(Unknown Source
i am trying to create a new catalog and add the picture of the cover to S3 bucket
String awsAccessKey = "";
String awsSecretKey = "";
String name_val="";
String desc_val="";
// HttpSession session = request.getSession(true);
//String username = (String) session.getAttribute("user_session");
//String clubfield=(String) session.getAttribute("res_ses");*/
// int att_id=0;
//String[] ccode;
String fieldname ="",fieldvalue="",fieldname1="" ,fieldvalue2="",fieldname2="",fieldvalue1="" ,fieldvalue3="",fieldname3="";
String categori="" ;
String category="" ;
String catalog="" ;
String nb="" ;
// String cclub="";
Connection con = null;
// ccode = clubfield.split("-");
// cclub=ccode[0];
String filetit="";
String filename="";
String test="";
int s=0;
// System.out.println("club code"+cclub);
try{
AWSCredentials awsCredentials =
new AWSCredentials(awsAccessKey, awsSecretKey);
S3Service s3Service = new RestS3Service(awsCredentials);
S3Bucket[] myBuckets = s3Service.listAllBuckets();
System.out.println("How many buckets to I have in S3? " + myBuckets.length);
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
fieldname = item.getFieldName();
if(fieldname.equals("catalog")){
name_val=item.getString();
}
if(fieldname.equals("catalog")){
catalog=item.getString();
System.out.println(catalog);
}
if(fieldname.equals("desc")){
desc_val=item.getString();
}
if(fieldname.equals("cat")){
category=item.getString();
System.out.println(category);
}
if(fieldname.equals("nb")){
nb=item.getString();
System.out.println(nb);
}
fieldvalue = item.getString();
fieldname1 = item.getFieldName();
System.out.println("fieldname1"+fieldname1);
fieldvalue1 = item.getString();
fieldname2 = item.getFieldName();
fieldvalue2 = item.getString();
System.out.println("fieldname1"+ fieldvalue);
System.out.println("fieldname"+fieldname+ "--"+fieldvalue);
System.out.println(fieldname1+ "--"+fieldvalue1);
System.out.println(fieldname3+ "--"+fieldvalue3);
filetit=fieldvalue+"/"+filename;
} else {
// Process form file field (input type="file").
filename = FilenameUtils.getName(item.getName());
System.out.println("filename come on come on--"+filename);
if(!filename.equals(""))
{ InputStream filecontent = item.getInputStream();
// System.out.println(att_id+"/"+cclub+"_clubcode.jpg");
//filetit= request.getParameter("file");
System.out.println( filename );
S3Object s3obj = new S3Object("myshelf/brand/"+filename);
s3obj.setDataInputStream(filecontent);
s3Service.putObject("foofystestbucket", s3obj);
}
}
}
i think i have the problem in this part because i am using different way to connect to the database
public class Connect {
private java.sql.Connection conn=null;
public Connect () {}
public boolean dbConnect(){
boolean ok = false;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex){
ok = false;
}
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/myshelf?useServerPrepStmts=false", "myshelf", "myshelffoofysPASS");
// conn=DriverManager.getConnection("jdbc:mysql://174.129.206.66:3306/myshelf","myshelf","myshelffoofysPASS");
// conn=DriverManager.getConnection("jdbc:mysql://localhost/myshelf","root","");
ok = true;
}
catch (SQLException e) {
ok = false;
}
return ok;
}
public static Connection DbConn() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// return DriverManager.getConnection("jdbc:mysql://174.129.206.66/myshelf","myshelf","myshelffoofysAPI");
//return DriverManager.getConnection("jdbc:mysql://localhost/myshelf","root","");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/myshelf?useServerPrepStmts=false", "myshelf", "myshelffoofysAPI");
}
public java.sql.Connection getConn() {
return conn;
}
}
Maybe I do not understand the servlet lifecycle very well, but this is what i want:
I want to display a page generated by a servlet let's say servlet: paginaAmd.
On this page I want to display a list of images stored in folder on web server.
The address of url of the images is something like:
/img/80-80-1-1-1-1-1-1-1-1-1
where /img/* is my servlet for displaying images.
All works well if I want to display one image at a time in browser.
But when I want to put all the list at once, the images are not displayed correctly. Sometimes are not displayed at all, sometimes are displayed in wrong position (the position does not alter in time), and sometimes are displayed only some images.
I suspect that somehow not all the doGet() methods are catched.
Can someone give me some advice?
Here are the servlet code witch is implemented by the tutorial here: http://balusc.blogspot.fr/2007/04/imageservlet.html
#WebServlet(name = "ImgDisplay", urlPatterns = {"/img/*"})
public class ImgDisplay extends HttpServlet
{
private SessionFactory sessionfactory = new AnnotationConfiguration().configure().buildSessionFactory();
private Query query;
private String mesajEroare = "";
private HttpServletRequest _request;
private HttpServletResponse _response;
private int width = 0;
private int height = 0;
private int idImagine = 0;
private int format = 0;
private String titluArticol = "";
private String numeImagine = "";
private boolean imgValida = false;
private int DEFAULT_BUFFER_SIZE = 1024 * 100;
String fileUploadPath = "";
#Override
public void init() throws ServletException {
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this._request = request;
this._response = response;
this.SetVariabile();
if(imgValida)
{
String nImagine = this.GetImageFromDisk();
this.DisplayImage(nImagine);
}
}
private void SetVariabile()
{
String reqUrl = _request.getRequestURL().toString();
String aUrl[] = reqUrl.split("/");
String urlImg = aUrl[aUrl.length - 1];
aUrl = urlImg.split("-");
try
{
this.width = Integer.parseInt(aUrl[0]);
this.height = Integer.parseInt(aUrl[1]);
this.idImagine = Integer.parseInt(aUrl[2]);
this.format = Integer.parseInt(aUrl[3]);
this.numeImagine = aUrl[aUrl.length - 1];
this.imgValida = true;
}
catch(Exception e)
{
this.imgValida = false;
}
}
private String GetImageFromDisk()
{
String nImagine;
//preiau imaginea
PaginiImagini pa = new PaginiImagini();
Session session;
try
{
session = sessionfactory.openSession();
session.beginTransaction();
query = session.getNamedQuery("PaginiImagini.findByImagineID");
query.setInteger("imagineID", this.idImagine);
pa = (PaginiImagini) query.uniqueResult();
session.getTransaction().commit();
session.close();
}
catch( Exception e )
{
this.mesajEroare = "Nu pot citi din baza de date!";
}
// citesc imagine de pe disk
ServletContext sctx = getServletContext();
this.fileUploadPath = sctx.getInitParameter("file-upload-path");
String pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMici;
if(this.width > Setari.wImagineMica || this.height > Setari.hImagineMica)
{
pathImagine = this.fileUploadPath + "/" + Setari.pathImaginiMari;
}
nImagine = pathImagine + "/" + pa.getNumeImaginePeDisc();
return nImagine;
}
private void DisplayImage(String imageToRead) throws FileNotFoundException, IOException
{
File image = new File(imageToRead);
String contentType = getServletContext().getMimeType(image.getName());
_response.setContentType(contentType);
_response.setHeader("Content-Length", String.valueOf(image.length()));
_response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");
_response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
_response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
_response.setDateHeader("Expires", 0); // Proxies.
// Prepare streams.
BufferedInputStream input = null;
BufferedOutputStream output = null;
try
{
// Open streams.
input = new BufferedInputStream(new FileInputStream(image), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(_response.getOutputStream(), DEFAULT_BUFFER_SIZE);
// Write file contents to response.
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0)
{
output.write(buffer, 0, length);
}
}
finally
{
// Gently close streams.
close(output);
close(input);
}
}
/**
*
* #param resource
*/
private static void close(Closeable resource)
{
if (resource != null)
{
try
{
resource.close();
}
catch (IOException e)
{
// Do your thing with the exception. Print it, log it or mail
// it.
//e.printStackTrace();
}
}
}
}
You have serious concurrency issues in your servlet. A single instance of the servlet is used to serve all the requests to this servlet. So a servlet should be stateless. But the first thing you're doing is
this._request = request;
this._response = response;
This means that if two concurrent requests are made to the servlet, you might have the first one set these two instance variables, then the second one resetting the same instance variables. The first image would thus be sent as a response to the second request, and nothing would be sent as a response to the first request. And this is only one of the strange things that could happen. You could also have exceptions and inconsistent data.
Don't store the request and response (and any other state) in instance variables. Pass them from method to method. I've not analyzed the whole code, but the only instance field that you should have in the servlet is sessionFactory field.