Java servlet annotations - java

Is there any way to use pure Java servlets not spring mvc request mapping to map a URL to a method?
something like:
#GET(/path/of/{id})

It's also possible with "plain vanilla" servlets (heck, Spring MVC and JAX-RS are also built on top of servlet API), it only requires a little bit more boilerplate.
#WebServlet("/path/of/*")
public class PathOfServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getPathInfo().substring(1);
// ...
}
}
That's all. Thanks to the new Servlet 3.0 #WebServlet annotation, you don't need any web.xml entry.
See also:
Our Servlets wiki page

Related

Swagger Java: Add custom servlet without JAXRS annotations

I have an application that is using JAX-RS (and swagger) annotations heavily and all is shown nicely in the swagger definition.
However one servlet implements a customer restful interface (oData, Apache oLingo) and this is not using any of the JAX-RS annotations. Yet I would like to document it.
To make it as simple as possible, let's say I have a class
#WebServlet("/rest1")
public class Login extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
response.setHeader("Content-Type", "application/json");
PrintWriter out = resp.getWriter();
out.print("{ \"text\": \"Hello World\" }");
}
}
I would like that servlet to show up in the swagger output as well without losing the JAX-RS entities.
According to the docs I would think I need to extend the reader to output this servlet as well and a custom ModelConverter?? to add hardcoded properties. But even if that is correct, I can't find a good starting point. Not to mention that I hope there is a simpler, more direct, way. Samples of swagger have been of no help either.

How to create a RESTful Web Service using Servlet (without Jersey, etc)?

How to use Servlet in creating a RESTful web service without using any JAX-RS implementation (Jersey, etc)?
Basically you absolutely right, you don't need a framework in order to implement REST API.
For instance, you could do basic crud operations in simple servlet class, like this:
#WebServlet(urlPatterns = "/book/*")
public class BookServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) {
// fetch from db
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
//update
}
#Override
public void doDelete(HttpServletRequest request, HttpServletResponse responce) {
//delete
}
}
It's a little bit inconvenient since you need to manually parse url params, do serialization, but under the hood, JAXRS and Spring MVC is just a servlets!
So, if you don't want dependencies in your code, I could suggest to just implement some convenient wrappers over servlet api.
Tip: you could parse path params from request like this:
String info = request.getPathInfo();
String[] parts = pathInfo.split("/");
String param1 = pathInfo[0];
So, for instance, if you have request like this:
HTTP GET /book/{id}
You'll get {id} in param1 which can be later used in database lookup.

How to Add robots.txt to a Vaadin 7 Application with CDI-Integration?

how can I add a robots.txt file to a Vaadin application?
I found nearly nothing related, but what I found states that there is no support for such a file.
I'm using Vaadin 7.1.1 with JBoss 7.1.1 and Vaadin-CDI-Integration.
My workaround approach is: By adding RobotsUI to the project, the URL http://localhost:8080/App/robots.txt becomes accessible.
#CDIUI(value="robots.txt")
public class RobotsUI extends UI {
#Override
protected void init(VaadinRequest request) {
// Send a response with mimetype
// `text/plain` with self defined content.
}
}
My problem is: How can I deliver a self-edited, text/plain response?
Thanks for any help :-)
I successfully published text/plain by adding a common HttpServlet to the project:
#WebServlet("/robots.txt")
public class RobotsServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("Text...\n");
}
}
Do it outside of Vaadin, register a filter before vaadin servlet and in case of robots.txt uri return your robots file. Or add some static resource serving servlet registered lets say to /static/* and bind your /robots.txt redirect with UrlRewrite.

Interceptor in #WebServlet not activated

We have a #WebServlet that's annotated with a custom interceptor annotation like this:
#WebServlet("/path")
#CustomInterceptor
public class InitialHtmlServlet extends HttpServlet
{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
}
}
We have the CustomInterceptor in the beans.xml in /WEB-INF and the interceptor works in other CDI-components. In this servlet, however, we cannot get it working.
We're running the latest JBoss EAP, which should be somewhat similar to JBoss 7.1.1. Is there something we should do different to get the interceptor to catch invocations on the servlet or is this not possible at all?
After some digging around I also found it somewhat confusing, that while being a good candidate for calling it a 'bean', servlet are exempt from interceptor mechanism.
It looks like various parts of JEE6 may or may not support interceptors at will :). Found some discussion here.

How to configure Tomcat to not encode the session id into the URL when HttpServletResponse.encodeURL() is invoked

Seems like a stupid question to which the answer would be "Don't use encodeURL()!" but I'm working with a codebase that uses netui anchor tags in the JSPs and I need to disable the writing of JSESSIONID into the URLs as it is a security risk.
In WebLogic, you can configure this by configuring url-rewriting-enabled in weblogic.xml (I know because I wrote that feature in the WebLogic server!). However, I can't find an equivalent config option for Tomcat.
Tomcat 6 supports the disableURLRewriting attribute that can be set to true in your Context element:
http://tomcat.apache.org/tomcat-6.0-doc/config/context.html#Common_Attributes
No setting comes to mind. But this is fairly easy to do by creating a first-entry Filter listening on the url-pattern of interest (maybe /* ?) and replaces the ServletResponse by a HttpServletResponseWrapper implementation where the encodeURL() returns the very same argument unmodified back.
Kickoff example:
public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException {
chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
public String encodeURL(String url) {
return url;
}
});
}
As found in https://fralef.me/tomcat-disable-jsessionid-in-url.html - There is a servlet spec feature to do this
<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>

Categories