Configuring struts 2 to load on startup - java

My Struts 2 application currently loads resource when a request comes in for the resource(jsp,action). I what all resources needed, to be loaded once the application is first deployed unto the container to have fast response times. How can I accomplish this? [Note] I am using Tomcat as my Servlet Container.

Why don't you try to implement Filters... as Filter starts with the application once it loaded and it will probably be helpful in order to load the resources.
You can add up your code in init method as it will be initiated with the start of container.
public class TestFilter implements Filter
{
public void init( FilterConfig config ) throws ServletException
{
System.out.println( "PUBLIC Fileter Started." );
}
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
throws IOException, ServletException
{
//DO NOTHING
}
}
And do add an entry in web.xml
<filter>
<filter-name>TestFilter</filter-name>
<filter-class>com.filter.TestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

Related

Use #WebFilter from another library without web.xml

I have a webfilter shared between all my webapps.
#WebFilter(urlPatterns="/*")
public class ApiOriginFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
... do something
}
}
Let's say ApiOriginFilter belongs to package org.commons.
Now my webapp.ear imports a common library with ApiOriginFilter.
To make the filter work properly, I had to include it into web.xml, because it seems that if filter belongs to another library it's not enabled by default.
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>org.commons.filter.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Is there any way to make it work without declaring in web.xml ?

How to restrict users to go certain page before login in Spring MVC?

I am making simple web app project in maven spring mvc with hibernate .I have set all controllers and all work fine .Now I am gonna make restriction for users who haven't logged in .I don't wanna let them to go inside before logging in.And also After they log out ,they should be thrown out.How can I do this ?
You can use a Servlet filter. This is an object that can intercept HTTP requests targeted at your web application.
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content, as illustrated in the diagram below.
In order to create a servlet filter you must implement the javax.servlet.Filter interface.
public class SimpleServletFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
}
public void destroy() {
}
}
When a HTTP request arrives at your web application which the filter intercepts, the filter can inspect the request URI, the request parameters and the request headers, and based on that decide if it wants to block or forward the request to the target servlet, JSP etc.
It is the doFilter() method that does the interception. Here is a sample implementation:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
throws IOException, ServletException {
String myParam = request.getParameter("myParam");
if(!"blockTheRequest".equals(myParam)){
filterChain.doFilter(request, response);
}
}
Notice how the doFilter() method checks a request parameter, myParam, to see if it equals the string "blockTheRequest". If not, the request is forwarded to the target of the request, by calling the filterChain.doFilter() method. If this method is not called, the request is not forwarded, but just blocked.
The servlet filter above just ignores the request if the request parameter myParam equals "blockTheRequest". You can also write a different response back to the browser. Just use the ServletResponse object to do so, just like you would inside a servlet.
You need to configure the servlet filter in the web.xml file of your web application, before it works. Here is how you do that:
<filter>
<filter-name>myFilter</filter-name>
<filter-class>servlets.SimpleServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>*.simple</url-pattern>
</filter-mapping>
With this configuration all requests with URL's ending in .simple will be intercepted by the servlet filter. All others will be left untouched.

Why live AppEngine is not calling my servlet filter?

I have a servlet filter written for my app engine project.
It is being called from the local development machine.
But it is not called when I put the code in Google App Engine live server.
Can anybody explain why?
This is how it is mapped in web.xml
<filter>
<filter-name>ErrorHandlerFilter</filter-name>
<filter-class>com.fms.advocacy.filters.ErrorHandlerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ErrorHandlerFilter</filter-name>
<url-pattern>/_ah/api/*</url-pattern>
</filter-mapping>
And this is the filter.
public class ErrorHandlerFilter implements Filter {
private static final Logger log = Logger.getLogger(ErrorHandlerFilter.class.getName());
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.warning("Entered ErrorHandlerFilter!!");
}
}
PS: I am using Google Cloud Endpoint for coding my APIs
The issue was with the <url-pattern>/_ah/api/*</url-pattern>.
In server the url is changed to <url-pattern>/_ah/spi/*</url-pattern>
Now it is working.

Tomcat - how to get http 500 instead of 404 when application wasn't deployed correctly?

We have several REST applications using Spring MVC. Time to time some application after deploy don’t start. When our Javascript client tries access resource url, it gets 404 status code. Therefore it assumes, that resource doesn’t exist. More appropriate for us would be http status 500 returned in Tomcat response. Is possible change this default Tomcat behavior?
I've found similar problem with JBoss (uses embedded Tomcat) but no answer:
https://serverfault.com/questions/367986/mod-jk-fails-to-detect-error-state-because-jboss-gives-404-not-500
HTTP proxy
If you have some sort of a proxy in front of your Tomcat server (like apache or nginx), I believe it can be configured to translate 404 into a different status code and error page. If you don't have any proxy or want the solution to remain self-contained:
Custom Spring loader and servlet filter
Since you are using Spring, I guess you are bootstrapping it using ContextLoaderListener in web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
This class is responsible for bootstrapping Spring and this is the step that in most cases causes the application startup to fail. Simply extend that class and swallow any exception so it never reaches the servlet container, hence Tomcat won't think your application deployment failed:
public class FailSafeLoaderListener extends ContextLoaderListener {
private static final Logger log = LoggerFactory.getLogger(FailSafeLoaderListener.class);
#Override
public void contextInitialized(ServletContextEvent event) {
try {
super.contextInitialized(event);
} catch (Exception e) {
log.error("", e);
event.getServletContext().setAttribute("deployException", e);
}
}
}
Code is pretty simple - if Spring initialization fails, log the exception and store it globally in the ServletContext. The new loader must replace the old one in web.xml:
<listener>
<listener-class>com.blogspot.nurkiewicz.download.FailSafeLoaderListener</listener-class>
</listener>
Now all you have to do is to read that attribute from servlet context in a global filter and reject all requests if application failed to start Spring:
public class FailSafeFilter implements Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {}
#Override
public void destroy() {}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Exception deployException = (Exception) request.getServletContext().getAttribute("deployException");
if (deployException == null) {
chain.doFilter(request, response);
} else {
((HttpServletResponse) response).sendError(500, deployException.toString());
}
}
}
Map this filter to all requests (or maybe only controllers?):
<filter-mapping>
<filter-name>failSafeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The solution might not be exactly what you want, but I am giving you a general, working example.
Yes it is possible with some change.
What we do :
write a servlet that do something like:
if (req.getContextPath().isEmpty()){
resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
put jar containing this class into tomcat lib.
change conf/web.xml to add the servlet and map it to *.404
set global error 404 to /404.404.
<error-page>
<error-code>404</error-code>
<location>/404.404</location>
</error-page>
your servlet will be called both with root application and with all deployed application.

Force Specific Response Header for JSF webapplication on Glassfish

We have a Java EE 6 web application with JSF 2.0 running on Glassfish 3.1.
There we encountered a strange bug: the Mime type of the response header send by Glassfish to the client depends on the order of the allowed Mime types in the request header send by the Browser. So in some cases (depending on the browser), the Mime type of the response is wrong, resulting in a broken html page.
But it would take pretty long to explain that thing. So to workaround this problem we now want to do just one thing:
Force the response header type for the whole web-application to "text/html".
Currently, we do that with a Servlet Filter configured in the Web.xml:
#WebFilter("/BaseFilter")
public class BaseFilter implements Filter {
public BaseFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
configuration in web.xml:
<filter>
<filter-name>BaseFilter</filter-name>
<filter-class>com.company.web.filter.BaseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>BaseFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- these patterns should match cached resources -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
So my question is, is there a better way to enforce a specific response header, especially by just configuring it instead of implementing a ServletFilter?
Is there a Glassfish option to do that?
You can specify it in the default template by the contentType attribute of the <f:view>.
<f:view contentType="text/html">

Categories