I have tried to serve simple html documents using embedded Jetty, but I keep getting 404 error. Here's my relevant setup
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase(".");
server.setHandler(resource_handler);
As I run this from Eclipse and print out the BaseResource, I'll get my project's workspace directory where I have a simple index.html. However if I try the url http://127.0.0.1:8888/index.html, I'll get a 404 error - what am I missing?
Related
This is driving me crazy, I'm developing a django app and need to provide a download link to a file located in the media folder. If I type the url in a blank tab it works fine, the file is downloaded, but if I click on the link from the website nothing happens. I realize this might be because the url to the file doesn't have the same origin that the website and from what I understood the browser won't allow the download, is this correct? Is there any way around?
url of the website (in development): http://localhost:8000/django_app/view_name
url of the file: http://localhost:8000/django_app/media/file.ext
I've tried the following html href:
href="../media/file.ext" download target="_blank"
And the following view:
def download_file(request):
fl_path = settings.MEDIA_ROOT + "\\filename.ext"
filename = "file_name"
mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % filename
return response
Nothing happens when I click on the link, no error generated. If I open the link in a new tab it downloads the file normally... Note that I need to be able to change the href link dynamically.
Thanks!
Is it possible to configure the ErrorPageErrorHandler in way that it redirects to a static Page if no content/service is found?
Here is my Code:
server = new Server(port);
Resource webRoot = Resource.newResource(webContent);
if (!webRoot.exists()) {
logger.warn("Unable to find root resource:" + webRoot.getName());
} else {
logger.info("Root resource is " + webRoot.getName());
}
ResourceHandler res = new ResourceHandler();
res.setBaseResource(webRoot);
res.setDirAllowed(false);
//servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/service");
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "index.html");
servletCtx.setErrorHandler(errorHandler);
// static file handler
ContextHandler staticCtx = new ContextHandler("/");
staticCtx.setBaseResource(webRoot);
staticCtx.setHandler(res);
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(staticCtx);
// add handerList to server
server.setHandler(handlerList);
This code show me index.html on localhost:8080 and I can access the sample service http://localhost:8080/service/sample. However, I want to show a static error page (i.e. documentation) to show up if an error like "404 Not Found" occured.
With this code, the Error handler logs:
"WARN o.e.j.server.handler.ErrorHandler - No error page found
index.html"
. What is correct way/syntax to define the URI?
Thanks in advance!
This was answered before at https://stackoverflow.com/a/32383973/775715
Don't mix ResourceHandler and ServletContextHandler unless you REALLY know what you are doing, and fully understand the nature of javax.servlet.ServletContext and all of the rules it brings to the table.
See also:
What is difference between ServletContextHandler.setResourceBase and ResourceHandler.setResourceBase when using Jetty embedded container?
Serving static files from alternate path in embedded Jetty
Here's an example of your setup working with NO ResourceHandler, 1 ServletContextHandler, and a DefaultServlet providing the static file serving.
// servlet handler
ServletContextHandler servletCtx = new ServletContextHandler(ServletContextHandler.SESSIONS);
servletCtx.setContextPath("/");
servletCtx.setBaseResource(webRoot); // what static content to serve
servletCtx.setWelcomeFiles(new String[] { "index.html" });
servletCtx.addServlet(new ServletHolder("sample", new MyServletSample()), "/service/sample");
ErrorPageErrorHandler errorHandler = new ErrorPageErrorHandler();
errorHandler.addErrorPage(404, "/index.html");
servletCtx.setErrorHandler(errorHandler);
// static file serving, and context based error handling
ServletHolder defaultServ = new ServletHolder("default", DefaultServlet.class);
defaultServ.setInitParameter("dirAllowed","false");
servletCtx.addServlet(defaultServ,"/");
// add handlers
HandlerList handlerList = new HandlerList();
handlerList.addHandler(servletCtx);
handlerList.addHandler(new DefaultHandler()); // non-context error handling
I am developing a multi-module spring boot project. My project structure look like
myProject(parent)
front-end
src/main/resources
frontend
index.html
rest
src/main/java
com.example
MyWebApp.java
com.example.config
WebAppConfig.java
I am trying to configure jetty by injecting JettyServerCustomizer as bean in WebAppConfig as following
#Bean
public JettyServerCustomizer customizeJettyServer()
{
return new JettyServerCustomizer()
{
#Override
public void customize(final Server server)
{
ContextHandler frontEndContext = new ContextHandler();
frontEndContext.setContextPath(""); //what should be here
frontEndContext.setResourceBase("");//what should be here
ResourceHandler frontEndResourceHandler = new ResourceHandler();
frontEndResourceHandler.setWelcomeFiles(new String[] { "index.html" });
frontEndContext.setHandler(frontEndResourceHandler);
ContextHandlerCollection contexts = new ContextHandlerCollection();
contexts.setHandlers(new Handler[] { frontEndContext});
server.setHandler(contexts);
}
};
}
What value to set to contextPath and ResourceBase so that I could run my index.html which is in front-end module? How the url will looks like?
Thank you :)
Spring Boot can serve static content for you. Instead of trying to configure Jetty, place your static content beneath src/main/resources/static and they'll be loaded straight from the classpath.
I've developed REST services. I can test the GET methods by the browser, or by a Client Application. But those who have PUT methods I don't know how to consume them by the browser...
For example, I have this method that turns a lamp on, after I insert the userId:
#PUT
#Path("/lampon")
#Produces({"application/json", "text/plain"})
#Consumes("multipart/form-data")
public boolean turnOnLamp(#FormParam("userId") String userId) throws Exception
{
boolean response = new LampManager().turnOnLamp(userId);
return response;
}
In my client application I do this, and it works:
String webPage = "http://localhost:8080/BliveServices/webresources/services.actuators/lampon";
URL urlToRequest = new URL(webPage);
//Authentication
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Authorization", basicAuth);
urlConnection.setRequestProperty("Content-type", "multipart/form-data");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", "2"));
(...)
But how can I send the userId by the browser?
Another thing, I get this message when I build my project:
SEVERE: Resource methods utilizing #FormParam and consuming "multipart/form-data" are no longer supported. See #FormDataParam.
Thanks
If you want to test the REST-Webservice with your Browser you must install an plugin.
If you use Google Chrome you can install REST Console I also use these plugin to test my Webservice.
https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn
For Firefox install these REST-Client
https://addons.mozilla.org/en-us/firefox/addon/restclient/
REST CLient is also available for Safari
http://restclient.net/
For Opera you can check out the Simple REST-Client
https://addons.opera.com/en/extensions/details/simple-rest-client/
For your second Question
please try as Consumes value 'application/x-www-form-urlencoded'
To issue a put-request from a browser you could use jQuery's jQuery.ajax(). (http://api.jquery.com/jQuery.ajax/)
For example:
$.ajax({
url: "test-url",
type: "PUT",
data: {userid: 1}
})
Would send a put-request to test-url with the specified data.
Is it possible using embedded Jetty to serve static files from directory X but mapped to URL Y? I have static files stored under directory "web", but I want the URL be something like http://host/myapp.
I have already successfully ran a server configured with ResourceHandler in the following way:
ResourceHandler ctx = new ResourceHandler();
ctx.setResourceBase("path-to-web");
HandlerList list = new HandlerList();
list.addHandler(ctx);
...
server.setHandler(list);
But the result is serving the files under /web and not under the desired URL mapping.
The ResourceHandler has no context configurable, but you can simply wrap it in a ContextHandler to achieve that.
Try this instead:
ContextHandler ctx = new ContextHandler("/my-files"); /* the server uri path */
ResourceHandler resHandler = new ResourceHandler();
resHandler.setResourceBase("path-to-web");
ctx.setHandler(resHandler);
server.setHandler(ctx);
That will serve /my-files as the ResourceHandler content of the filesystem path-to-web
The above doesn't work for Jetty 9, but this does:
ContextHandler contextHandler = new ContextHandler("/my-files");
contextHandler.setResourceBase("/tmp/static");
ResourceHandler resourceHandler = new ResourceHandler();
contextHandler.setHandler(resourceHandler);
server.setHandler(contextHandler);