I am using following meta tags to prevent browser caching for page:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate, max-stale=0, post-check=0, pre-check=0" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Vary" content="*" />
Case:
Browser is already opened with page1.
New link is pasted in the browser address bar and now secured page page2 is opened.
User performs action on page2 and is redirected to page3.
When clicking back button on page3, then user gets redirected to page1 (no caching and works fine in this case). When user clicks forward button on page1, then the user is forwarded to the secured page page2. This shouldn't happen.
All of above is tested on IE9.
How is this caused and how can I solve it?
Your initial attempt with HTML <meta http-equiv> tags specifies the right header values, however, this doesn't work at all because your pages are already served over HTTP. The <meta http-equiv> headers specifies "HTTP-equivalent" headers which are only used when the pages are not served using the HTTP protocol.
For example, when the pages are opened from local disk file system like as if you were doubleclicking a .html file in local disk file system explorer. This would open the .html file via file:// URI instead of http:// URI.
You should be setting those headers on the real HTTP response. You can investigate the headers of the current HTTP response by pressing F12 in Chrome/FireFox>=23/IE>=9 and exploring the HTTP traffic in Network tab. In case of specifically IE9/10, click the Start capturing button, reload the page, select the HTML page, click Go to detailed view button and finally click the Response headers tab. Here's a screenshot of how it look like in IE10 on your current question:
The right way to get those headers to end up there is using HttpServletResponse#setHeader() and friends like setDateHeader(), addHeader(), etc. As you figured, one way is a servlet filter.
See also:
Avoid back button on JSF web application
I found out that the best solution is the following filter:
import java.io.IOException;
import javax.faces.application.ResourceHandler;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet Filter implementation class NoCacheFilter
*/
#WebFilter(urlPatterns = {"*.xhtml"})
public class NoCacheFilter implements Filter {
/**
* Default constructor.
*/
public NoCacheFilter() {
// TODO Auto-generated constructor stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// apply no caching for all web pages except resources, you can customize that to be applied for specific pages
if (!req.getRequestURI().startsWith(req.getContextPath() + ResourceHandler.RESOURCE_IDENTIFIER)) { // Skip JSF resources (CSS/JS/Images/etc)
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
res.setHeader("Pragma", "no-cache"); // HTTP 1.0.
res.setDateHeader("Expires", 0); // Proxies.
}
chain.doFilter(request, response);
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
according to the answer in this question:
Redirect to login page when user clicks on back button after logout in JSF
Related
I'm trying to make a Spring MVC app with Spring boot, Spring Security and Thymeleaf.
The problem is - when i'm requesting a page with it's html and css, i'm not getting the correct MIME type for my css file, thus why Chrome cannot load it with status "canceled" and the message "Refused to apply style from 'http://localhost:8080/login' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."
I'm linking the css file correctly:
" "
The css file is contained in:
resources -> static -> css - > style.css
I've allowed all resouces from the resources folder in the Security config file:
package org.isp.configuration;
import org.isp.services.api.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserService userService;
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider
= new DaoAuthenticationProvider();
authProvider.setUserDetailsService(this.userService);
authProvider.setPasswordEncoder(getBCryptPasswordEncoder());
return authProvider;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
String[] permitted = new String[]{
"/", "/home","/register","/about","/png/**",
"/css/**","/icons/**","/img/**","/js/**","/layer/**"
};
http
.authorizeRequests()
.antMatchers(permitted).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").permitAll()
.defaultSuccessUrl("/dashboard")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/unauthorized")
.and()
.csrf().disable();
}
#Bean
public BCryptPasswordEncoder getBCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
This is my html page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org" >
<head>
<title>Index</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
**<link rel="stylesheet" href="../static/css/style.css" type="text/css">**
</head>
<body>
<div th:include="~{fragments/navbar :: navbar}"></div>
<div class="container">
<h3>Home</h3>
<p>This is the home page of the project!</p>
</div>
<div th:include="~{fragments/footer :: footer}" class="footer"></div>
</body>
</html>
Any ideas how can i fix the incorrect MIME type? Is there any configuration im missing?
In my case, I have to permit requests for static files to get it to work.
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Overide
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/js/**", "/css/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll();
}
}
I've just been struggling with the same issue, and I finally realized that it was a red herring - the real problem was 404, and the MIME type error came from Spring's handling of it. As explained in the Spring Boot docs, its built-in error handling automatically redirects to /error and outputs the error details as JSON. When I checked my logs, I saw a 404 in my webserver access log and the following in my application log:
DEBUG DispatcherServlet:869 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /error
DEBUG RequestMappingHandlerMapping:317 - Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
DEBUG HttpEntityMethodProcessor:234 - Written [{timestamp=Fri Apr 06 14:06:54 PDT 2018, status=404, error=Not Found, message=No message available, path=/css/style.css}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#5ef96137]
So, your real problem is that Spring is not finding your static resources. You'll want to make sure the resources folder is in your classpath, or explicitly set the locations using the spring.resources.static-locations property.
In my case, I have used additional filter. So all kind of request will go through that filter. even css and js file used to go through that.
At this point, for some request in the ratio of 1/7 or 1/10, I get mime type issue, for css file the server returns with the type of application/javascript or application/json and ect.
Then I used #WebFilter and allows only api request to go through that filter.
#WebFilter(urlPatterns = "/api/*")
Now the css and js files not allowed in that additional filter. and then I did't find issue with mime type.
In my point of view, when we have too many filters the backend fails to handle frequent request for resources (js, css, img ...), So it returns with wrong MIME type.
Hope, this would help someone, who face this kind of issue
A client had the case today (24 nov 2021) when Spring Security was redirecting most of the requested urls to "/login" equivalent functional endpoint. No assets were loaded, and the same message you get about mimetype was in their Google Chrome console logs.
Diagnostic was done with entering the assets with wrong mimetype and see the loading of the "/login" endpoint.
It was resolved with adding some Spring Security mapping rules in their SecurityConfig.class of their Spring Boot Application, so the webapp is running well now.
We have a requirement of enabling universal link in our application. We have a java based web application(spring) and a iOS app. To enable universal link as per apple we need to create a json file apple-app-association-file and host this file in the server.
Now java web app is deployed in tomcat in windows server and apche 2.4 is being used as web server. Please let me know how to host the apple-app-association-file in the tomcat or web server or inside the war file(inside the code), we are using maven structure.
according to docs, we need to remove the file extentsion and file should be access as below:
url of web app: https://xyz.example.com
where xyz.example.com is mapped to a web app which is there in webapp folder in tomcat.(localhost:8080/webApp)
apple-app-association-file to be accessed as: https://xyz.example.com/apple-app-association-file
now as the extension is not there how can i host it.Do i need to make the code changes and treated it as servle request. Even if i do so it wont be a good idea to execute a servet just to access a file
Also, it's also important that the file is served with the correct MIME-type, for Universal Links it can be served as application/json. How to set mime type in tomcat or java web app(spring)
First rename file to apple-app-site-association.json, then write next Spring configuration:
#EnableWebMvc
public class WebClientConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/.well-known/*")
.addResourceLocations("/path/to/your/static/resources")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
#Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
if (resourcePath.equals("apple-app-site-association")) {
return location.createRelative("apple-app-site-association.json");
}
return super.getResource(resourcePath, location);
}
});
}
}
As described here: developer.apple.com
You can place the file at the root of your server or in the .well-known subdirectory.
Then the file will be served with the correct MIME-type "application/json" and accessed as: https://xyz.example.com/.well-known/apple-app-association-file
The Solution from pITer Simonov works for me! But i had to add the root path
inside
< servlet-mapping > (in web.xml)
like this:
< url-pattern >/</url-pattern >
After that, the resource handler work fine!
I did it with a standard REST controller + endpoint.
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
#RestController
#RequestMapping("/.well-known")
#Slf4j
public class WebClientConfig {
#GetMapping(value = "/apple-app-site-association",
produces = MediaType.APPLICATION_JSON_VALUE)
public String addResourceHandlers() {
String json = "";
InputStream inputStream = getClass().getResourceAsStream("/apple-app-association.json");
try(InputStream stream = inputStream) {
json = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
} catch (IOException ioe) {
log.error("Apple app association could not be retrieved! iOS app will be impacted. Error: " +
ioe.getMessage());
}
return json;
}
}
Note: the apple-app-asociation.json file is under src/main/resources
I am facing the issue with IE browser.It is loading the icons for first time load. but if i refresh the page the icons are not visible. Can you please tell me how to fix this from server side? This is related to Font-awesome disappears after refresh for all ie browsers ie11,ie10,ie9 . but it does nt have the complete solution
We had this same problem because we were storing the FA CSS file locally. The font #import's would fail on refreshes, probably because it does a different HTTP call than the one for the local file. We reverted to their CDN and it fixed the problem. If you downloaded the FA files and aren't pulling them in through a CDN, then change your <link> tag in your <head> to:
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
Once we did that FontAwesome was being served up on every refresh without problem.
In my case i was using java and the only thing that works was this cache filter that i made.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebFilter("*")
public class CacheFilter implements Filter {
/**
* #constructor CacheFilter
* #date 28/09/2015
*/
public CacheFilter() {
//construtor
}
/* (non-Javadoc)
* #see javax.servlet.Filter#destroy()
*/
#Override
public void destroy() {
//metodo vazio
}
/* (non-Javadoc)
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpServletRequest httpRequest = (HttpServletRequest) request;
String page = httpRequest.getRequestURI();
if (!page.contains("fontawesome-webfont") || !page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
httpResponse.setHeader("Pragma", "no-cache");
}else if(page.contains("fontawesome-webfont") && page.endsWith(".eot")){
httpResponse.setHeader("Expires", "-1");
httpResponse.setHeader("Cache-Control", "public");
httpResponse.setHeader("Pragma", "cache");
}
chain.doFilter(request, response);
}
/* (non-Javadoc)
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
#Override
public void init(FilterConfig fConfig) throws ServletException {
//metodo vazio
}
}
I did the same thing as https://stackoverflow.com/a/37196841/1982385 except that I did it on the reverse proxy (HAProxy) instead of from the servlet itself.
backend app
server server1 10.10.14.4:9090 check
acl is_woff capture.req.uri -m sub .woff
acl is_ttf capture.req.uri -m sub .ttf
acl is_eot capture.req.uri -m sub .eot
http-response set-header Cache-Control public if is_eot or is_woff or is_ttf
http-response set-header Expires -1 if is_eot or is_woff or is_ttf
http-response set-header Pragma cache if is_eot or is_woff or is_ttf
Suggestion provided by CV Harris is working fine. But, we didn't want to use files from CDN.
For us, icons issue occurred after upgrading Spring Security to 4.2.3. So, as given in Spring security configuration, added following in spring configuration.
defaults-disable="true"
Now icons are displayed in IE11.
I know... old question... but still relevant. I had the same issue... using a CDN worked, but not hosting the FA css myself.
Turns out it was related to caching as others have suggested. I had turned caching off for everything in the BeginRequest method below (for some reason which now escapes me... troubleshooting something else probably), but it seems that FA really wants to be cached... /shrug.
protected void Application_BeginRequest()
{
Context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
Commenting this out fixed FA icons on refreshes, though I now have the task of making it a little more fine grained...
I am unable to read JSON from rest webservice using angularjs $http. I have a simple rest webservice in a different project which return JSON. When I try to hit rest service from angular it goes to error part.
Below is my code:
Restful service in Java :
package com.demoapp.rest;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
/**
* REST Web Service
*/
#Path("Employee")
public class EmployeeResource {
#Context
private UriInfo context;
/**
* Creates a new instance of EmployeeResource
*/
public EmployeeResource() {
}
/**
* Retrieves representation of an instance of com.demoapp.rest.EmployeeResource
* #return an instance of java.lang.String
*/
#GET
#Produces("application/json")
public String getJson() {
//TODO return proper representation object
return "({\"id\":3,\"name\":\"Joe\"})";
}
/**
* PUT method for updating or creating an instance of EmployeeResource
* #param content representation for the resource
* #return an HTTP response with content of the updated or created resource.
*/
#PUT
#Consumes("application/json")
public void putJson(String content) {
}
}
Angularjs code :
angular.module('myApp.controllers', [])
.controller('MyCtrl1', ['$scope', '$http', function($scope, $http) {
$http.jsonp(
/*Doesn't work*/ 'http://localhost:8080/mavenproject1/webresources/Employee?callback=JSON_CALLBACK'
/*Works*/ /*'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&callback=JSON_CALLBACK'*/
)
.success(function(data) {
console.log('Success '+data);
})
.error(function(data) {
console.log('Error '+data);
});
}])
.controller('MyCtrl2', [function() {
}]);
I am getting error for first url (localhost..) and same angularjs code works for another public restful service.
Can anyone please tell why angularjs returns error in console for (http://localhost..) restful service and goes to success for (http://api.openweathermap.org/....) ?
Where exactly am I going wrong?
You are trying to access a resource by jsonp but your REST service returns plain json. You need to use
$http.get('http://localhost:8080/mavenproject1/webresources/Employee').
The url http://api.openweathermap.org works because they return the jsonp format. You need this format if you make request to other domains. Jsonp means that the result is wrapped in a function call. The name of the function is dynamically generated and is specified by the callback parameter in your example.
EDIT (results from the discussion above - in production this app will also run on two different servers, so there are the following options to solve the problem)
1) you may use the Access-Control-Allow-Origin header in your jboss server. Have a look at this answer how to do this: Set response headers not using filter - RESTeasy.
2) you may use a reverse proxy in front of your tomcat and your jboss server. For example the apache webserver can do this. Here is an answer that addresses this problem: How to correctly configure a reverse proxy with Apache, to be used for cross-domain AJAX?
3) you can switch to jsonp - this is a little bit complicated because it is not supported directly by RESTEasy. Have a look at this post: How enable JSONP in RESTEasy?
I have made a servlet program to insert image into an Oracle database. The program is as follows.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InsertImage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url=request.getParameter("image");
File image=new File(url);
FileInputStream fis;
PrintWriter pw=response.getWriter();
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String str = "jdbc:oracle:thin:#localhost:1521:XE";
Connection con = DriverManager.getConnection(str,"system","root");
PreparedStatement pstmt=con.prepareStatement("insert into insertimage(image) values(?)");
fis = new FileInputStream(image);
pstmt.setBinaryStream(1, (InputStream)fis, (int)(image.length()));
int size=pstmt.executeUpdate();
if(size>0)
{
pw.println("<html>Image Uploaded Successfully.</html>");
}
else
{
pw.println("<html>Image could not be uploaded.</html>");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
And the HTML page, from where the input is coming is:
<!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">
</head>
<body>
<form action="InsertImage" name="form1">
INSERT IMAGE
<input type="file" name="image"></input>
<input type="submit" name="upload"></input>
</form>
</body>
</html>
When I try to run this code from the HTML page, whatever picture input I give, it always throws FileNotFoundException. I can't understand why I am getting this. The stacktrace is:
java.io.FileNotFoundException: Counter-Strike-Servers.jpg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at InsertImage.doGet(InsertImage.java:39)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:179)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:241)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:580)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
I tried to print the URL in the servlet and got only shocked.jpg and not the full filepath. Maybe the full filepath is not coming and that is the cause of not finding the file error. So how can I send the full filepath?
While uploading a file from JSP/HTML, you must have the form method set to POST with encType set to multipart/form-data. (HTTP specification)
<form action="InsertImage" method="post" encType="multipart/form-data" name="form1">
Implement the doPost method to get the same file. You may want to take a look at Apache Commons FileUpload to upload files and Stack Overflow post How to upload files to server using JSP/Servlet? for further details.
I tried one way to upload the file without using the Apache Common FileUpload and it's working.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form action="InsertImage" name="form1" method="post" enctype="multipart/form-data">
INSERT IMAGE
<input type="file" name="image"></input>
<input type="submit" name="upload"></input>
</form>
</body>
</html>
</body>
</html>
Servlet doPost:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url=request.getParameter("image");
InputStream is = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
PrintWriter pw=response.getWriter();
pw.println("Reading file");
while ((line = reader.readLine()) != null) {
pw.println(line);
}
pw.flush();
}
Now you have to parse the file contents as per your needs. Refer blog post Upload and store files. However, I would strongly suggest using Apache Commons FileUpload for the same.
It looks like a local error in the sense that it really can't find the file specified by url. I would suggest debugging by printing out the url String and creating a dummy class to feed the doGet method a handmade request/response to make sure whether the problem is in the program itself or in some unexpected passing/formating of the request (you might want to comment out some parts of the method for this, e.g. the connection and statement part).
EDIT: Example of the dummy class (or method, in this case):
private void testDoGet() {
// I would suggest commenting out all the Connection and PreparedStatement
// parts of the doGet method so you don't have to establish the connection.
// - this is just to test if you can get to the image on your machine.
HttpServletRequest request;
//insert into request the image parameter with the string to the requested image
HttpServletResponse response //TODO initialize with some class implementing it
doGet(request, response);
// if you want to, set a breakpoint somewhere here to check
// what's in the classes now
}