Micronaut Servlet support: discovery of classic HttpServlet implementations - servlets

I followed the micronaut-servlet guide using Jetty Server and everything worked as expected (micronaut 2.0.0.M3, micronaut-servlet 1.0.0.M3).
However, for our Proof-of-Concept we need to migrate several classic HttpServlet (v3.1) based implementations to micronaut. Example:
#WebServlet(name = "Hello",
urlPatterns = {"/hello/*"},
initParams = {#WebInitParam(name = "name", value = "World")})
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().format("<h1>Hello %s!</h1><p>session=%s</p>",
getInitParameter("name"), request.getSession(true).getId()
).flush();
}
}
However, this is not picked up by Micronaut. Is this not supported? If not, what is the best way to migrate this to idiomatic micronaut?

Related

How to add headers to requests ignored by Spring Security

My configuration of Spring Security is
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**"); // #3
}
Taken from here.
The documentation for ignorig says
Allows adding RequestMatcher instances that should that Spring Security should ignore. ... Typically the requests that are registered should be that of only static resources.
I would like to add some headers to files served from resources.
E.g.: Strict-Transport-Security: max-age=31536000, X-Content-Type-Options: nosniff.
How I can do it?
One solution it to change it to
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/resources/**").permitAll()
.and()
.antMatcher("/resources/**").headers().cacheControl()
}
Example how to allow cache control headers PLUS ALL DEFAULT SPRING SECURITY HEADERS.
I have struggled with the same problem. When I ignore specific requests in WebSecurity, the headers were gone.
I fixed the missing headers, by applying a filter on each request that adds my headers.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(securityHeaderFilter, BasicAuthenticationFilter.class)
...
}
The filter code looks like this. The important thing to note here, is that the Filter must be declared as a #Component. When you miss the #Component annotation, the filter will be ignored.
#Component
public class SecurityHeaderFilter implements Filter {
#Override
public void init(FilterConfig fc) throws ServletException {
// Do nothing
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader(
"custom-header1", "header-value1");
httpServletResponse.setHeader(
"custom-header2", "header-value2");
chain.doFilter(request, response);
}
#Override
public void destroy() {
// Do nothing
}
}
I have used the following solution:
#Bean
public FilterRegistrationBean setHeaders() {
HstsHeaderWriter hstsHeaderWriter = new HstsHeaderWriter(31536000, true);
XContentTypeOptionsHeaderWriter xContentTypeOptionsHeaderWriter = new XContentTypeOptionsHeaderWriter();
List<HeaderWriter> headerWriters = new ArrayList<>();
headerWriters.add(hstsHeaderWriter);
headerWriters.add(xContentTypeOptionsHeaderWriter);
HeaderWriterFilter headerWriterFilter = new HeaderWriterFilter(headerWriters);
FilterRegistrationBean bean = new FilterRegistrationBean(headerWriterFilter);
bean.setOrder(1);
return bean;
}
The above bean will add a filter globally on all the resources(even the ignoring ones). You can checkout the various implementations of org.springframework.security.web.header.HeaderWriter.java for the different kinds of security headers and add them all to HeaderWriterFilter.java.

How can i display a view with annotations

Normally i used to display my views in javaee with the "normal" kind of servlet like this :
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.getServletContext().getRequestDispatcher("/WEB-INF/views/myview.jsp").forward(request, response);
}
But i'm on a project where there is only annotation everywhere and i don't understand how can i display some view this way ...
#RequestScoped
#Path("/user")
#Produces("application/json")
public class UserController extends Controller{
#Path("v1/{pseudo}")
#GET
public String getUser(#PathParam("pseudo") String pseudo){
...
Can someone help me ?
Thx
Sorry my google searsh was bad and i found my finnaly answer :
#Path("/documentation")
public class DocumentationController extends HttpServlet{
#GET
public void getHome(#Context HttpServletRequest request,
#Context HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/test.jsp")
.forward(request, response);
}
}
thx for the response anyway

Get client operating system name

I am trying to get the operating system name of a client in a servlet using the following code:
public class SomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userAgentString = request.getHeader("User-Agent");
UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
OperatingSystem os = userAgent.getOperatingSystem();
}
}
I am getting an error UserAgent cannot be resolved to a type. How can i solve this?

Wildcard path mapping /A/* should return 404 when path info is absent like /A

I am new in Servlets. I am trying to map a URL using the wildcard (*), but it's not working the way i expected.
Here is my servlet class.
#WebServlet(urlPatterns = {"/A/*"})
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("Working...");
}
}
The above servlet is working for both example.com/A and example.com/A/car.
I want to work the servlet only for the the second option which is example.com/A/whatEver. How can i do that ?
In simple: I just want to work the servlet if there's anything after example.com/A.
Any help will greatly appreciated.
Just invoke HttpServletResponse#sendError() with SC_NOT_FOUND (404) when HttpServletRequest#getPathInfo() is null or empty or equals to /.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pathInfo = request.getPathInfo();
if (pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/")) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
// ... (continue)
}

Is it ok to make all methods called from a servlet doGet() static to avoid synchronization?

I have a servlet which performs various business logic. I want to avoid synchronisation like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
synchronized (MyServlet.class) {
various();
calls();
and_logic(_req, _resp);
}
}
by making all called methods static and enforcing it like this:
#Override
protected void doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
_doGet(_req, _resp);
}
private static void _doGet(final HttpServletRequest _req, final HttpServletResponse _resp) throws ServletException, IOException {
various();
calls();
and_logic(_req, _resp);
}
I won't use any static variables and all my method calls are assumed to be thread-safe. Are there any non-obvious drawbacks?
I won't use any static variables and all my method calls are assumed to be thread-safe.
Under these conditions neither you don't need synchronization nor static methods. Just use instance methods of a servlet or some other service class.

Resources