Is it possible to use AOP for web app licence validation? - java

At present I have a Spring MVC web application, which uses ServletFilter to filter each HTTP request and check whether the user has really purchased the licence by checking and validating the licence file content.
I have mapped the filter in both spring xml file as well as web.xml appropriately. As I have access to HttpServletRequest and HttpServletResponse in the filter, I am able to redirect the user to error page if the validation fails.
So, now as the title suggests is it possible to do the same thing using Spring AOP? How can Spring AOP be configured to get access to the request and response objects created by the container to redirect the user?

How can Spring AOP be configured to get access to the request and
response objects created by the container to redirect the user?
You won't be able to get the same exact behavior as servlet Filters. A Filter operates around the target Servlet by passing in the ServletRequest and ServletResponse objects. In that sense, you can get similar behavior since AOP advice can operate around the joinpoint and intercept arguments that get passed around.
However, the AOP advice can't magically have access to the request and response. It either needs to advise a method that receives them or get them from some ThreadLocal or other container. For example, Spring has RequestContextHolder which you can use to get the HttpServletRequest. But it doesn't have anything to give you the HttpServletResponse (not technically true, but it's not reliable). You could write something similar that does.
Once the advice has access to the objects, it can simply invoke HttpServletResponse#sendRedirect(..) or forward() or whatever.

The best way to implement this would be using exceptions. That way the check and the handling can be different in different situation, e.g. web application vs. normal application.
Your check could be added to particular joinpoints using aop. In case it finds something amiss, it would throw a InvalidLicenseException (extends RuntimeException). Now there are several ways in which you can redirect a request to an error page when an exception is thrown. You could add this to your web.xml :
<error-page><exception-type>InvalidLicenseException</exception-type><location>/license-error.jsp</location></error-page>
Since you're using spring, you could also use annotations. Read this

You can do it out with AOP Advises,
Advice: Advices are actions taken for a particular join point. In
terms of programming, they are methods that gets executed when a
certain join point with matching pointcut is reached in the
application. You can think of Advices as Struts2 interceptors or
Servlet Filters.
So you can configure an advice to take care of validation . you can also configure them to execute at a particular point (i.e) where it needs to be executed .
But remember scope of AOP remains only for method invocation and it doesn't provide response as servlet filters does.
Learn More ..
Simple example here to start with.

Related

Difference between handling errors in web.xml and spring mvc config file

I have an Spring MVC web application, that has a org.springframework.web.servlet.handler.HandlerExceptionResolver that catches all exceptions and maps them to corresponding pre-defined error views and http status code. This HandlerExceptionResolver is defined in webmvc-config.xml file under src/main/webapp/WEB-INF.
Now, my client insists that I need to also map http status codes and exceptions in my web.xml file, which I am failing to understand because I don't see in what case my Spring MVC app would fail to catch an error, that would need to be handled by web.xml.
With that being said, this led me to the question of what is the fundamental difference between catching errors in web.xml and my custom spring mvc config file.
Can anyone help? Many thanks!
You could add a generic error handler for java.lang.Exception in the web.xml, just in case that anything escapes Spring MVC error handling mechanism. For example, you misconfigure something in the Spring MVC infrastructure itself, so Spring error handlers don't even get a chance to handle the error.
However, you should not re-map http status codes in the web.xml, because then the container will intercept all the generated error responses returned from Spring MVC and replace them with results generated by the error handlers defined in the web.xml. Of course, you could take care that the error handlers invoke the same logic as Spring ones, so that returned error responses are the same, but obviously that's quite an unnecessary work.
I would say that you should discuss this with your client in more detail and explain them the concepts and best practices related to Front Controller pattern.
Both mechanisms works. However the HandlerExceptionResolver is more flexible than the standard web.xml mappings in web.xml. The HandlerExceptionResolver provides you with a programmatic approach to handling exceptions as compared to the error mappings in web.xml.
For example you can override a provided implementation or implement a custom HandlerExceptionResolver with custom logic e.g sending an email to a system administrator before forwarding to your view.
Another advantage is that your handler exception resolver is a Spring bean which can have access to all services in your application context.
However you have to ensure that your HandlerExceptionResolver maps all possible exception.If you have an entry for Throwable then this should be sufficient.
Your client is just being cautious in case your HandlerExceptionResolver misses some exceptions. If its properly setup the web.xml mappings becomes redudant

Remove HTTP Response headers in Java

Is there a way to remove HTTP response headers like Server and X-Powered-By?
My application is using a Weblogic server. I'm programming in Java using the Spring MVC framework and Hibernate, and using JSP for views.
Depends on where the headers are added. If inside your app, you can use a Spring MVC Interceptor to remove them after your controller calls. If outside your app, you might be able to try a Java EE filter configured in web.xml (the example is security, but the approach will also work for your use case). If its added after that, you may want to look at your web front end (Apache, IIS, what-have-you) to configure a filter there.
UPDATE
This answer describes an approach for removing specific headers, as the HttpServletResponse interface does not allow for header removal explicitly. You will need some trial and error to determine what portion of your stack is adding the header.
If you set concrete responseHeader to null it will be removed / not seen in response headers.

Exact Meaning of Struts Interceptor

Can anyone tell me, what is exact meaning of INTERCEPTOR in Struts 2 Framework?
Could you please give me some simple example with Struts interceptor?
Thanks IN Advance!
Think of what the Interceptors is to Struts as Filters is to Servlets. When you request a Struts Action, The Struts Framework sends a request to the called action, but before the action is executed, the invocation can be interpreted by interceptors. Once the're done, the request is passed (as servlet calls it, filtered) to the action.
The reason for interceptors is, you want to do some pre-conditional / post-conditional checking to be sent to the action / returned by the action. A simple example will be File upload. When you send a file to an action in Struts, you can have an interceptor that is used as a pre-condition validator (e.g, the file size must be 5210 bytes exactly = 5MB). If successful, it filters the request to the action (that was called).
I've never used Struts 2 but there's a Wiki on Interceptors at Apache site.
Well Why Interceptors or whats there relevancy in Struts2..These are a part of moduler approach where you have some predefined modules as per the need and you can plug them or unplug them as per your need.
Struts2 is a web frame work and in order to process the request it has to undergo certain steps which are common for every request process cycle so Struts2 develoers have created these module which are indentiifed as common module which every request in web application needs
like when you submit the data we need to conver the data to appropriate form this is struts is being done by the Interceptors if some validation is needed how to do it is being done by interceptors they are somethig which are like modules or plugin plug which ever you want to use and unplug them which you don't do..
in shorter terem these Interceptors is doing all necessary work for you so that you can concentrate on ur business logic

Spring 2.5 managed servlets: howto?

Correct me if anything is wrong.
As I understand, all Spring functionality, namely DI works when beans are got thru
Spring Context, ie getBean() method.
Otherwise, none can work, even if my method is marked #Transactional and I will
create the owning class with a new operator, no transaction management will be provided.
I use Tomcat 6 as a servlet container.
So, my question is: how to make Servlet methods managed by Spring framework.
The issue here is that I use a framework, and its servlets extend the functionality of
basic java Servlets, so they have more methods. Still, web.xml is present in an app as usual.
The thing is that I do not control the servlets creation flow, I can only override a few methods
of each servlet, the flow is basically written down in some xml file, but I control this process
using a graphical gui.
So, basically, I only add some code to a few methods of each Servlet.
How to make those methods managed by Spring framework? The basic thing I need to do is
making these methods transactional (#Transactional).
comment to Bozho:
#Bozho Let's see. In these servlets' methods I work with framework capabilities, let's say special variables that are got and saved in the current session. And what is needed, is looping through those framework-based collections while saving some values in a database. What you suggest is introducing a new very complex object, so that it could be passed to a service layer. (Service layer will not know anything about framework, its classes and objects kept in current Session! First, we "wrap" framework based collections to such a object, so copy everything into it. Then, again, the Service layer method should either save changes in a database or, worse case, return a new complex object so that Servlet framework method could update framework variables depending on the result of Service layer method execution. It is a workaround but do you think it is a good idea?
You can also define your servlets directly in the Spring application context. You'll need a "proxy" servlet registered in web.xml and delegating to the servlet instance which is configured as bean in the applicationContext.xml. Proxy servlet is configured with the name of the target servlet bean, it discovers this bean via WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(...) and delegates all the processing to the target servlet. In this case an instance of your servlet is completely managed by Spring.
I'd suggest restructuring your code - making servlet methods transactional is not a good thing to do. Put the transactional logic in a separate, service class, and either
obtain these spring-managed classes by WebApplicationContextUtils.getRequiredWebApplicationContext().getBean(..) or
in your servlet init() method obtain the ApplicationContext with the above method and call appCtx.getAutowireCapableBeanFactory().autowireBean(this). This way you can inject the transactional classes in your servlet as if it was spring-managed.
Now, you can do all this, but it is definitely not a beautiful way to go. I'd suggest using Spring MVC or any other MVC framework (which support spring integration of its components)
If this is all not possible, as a last resort I think you can use #Configurable (on your servlets) with a <context:load-time-weaver/>.
You should take a look how Spring proxy filters:
http://grepcode.com/file/repository.springsource.com/org.springframework/org.springframework.web/3.0.2/org/springframework/web/filter/DelegatingFilterProxy.java
In theory you could easily make the same sort of proxy for servlets and DispatcherServlet is sort of a proxy.

Does Acegi/Spring security support getUserPrincipal()?

I need to interface an existing application with Acegi/Spring security.
In order to get started I am looking for one simple piece of information: in this context, will HttpServletRequest.getUserPrincipal() called from my application properly return the username obtained through Spring (as opposed to using Spring-specific objects)? I have Googled conflicting information on this.
I assume that if Acegi is implemented with filters, it is able to overload the Servlet API's getUserPrincipal(), right?
Subsidiary question: if this is not the case by default, is there any way to turn it on?
Thanks,
-Erik
As previous user has answer, spring security support the getUserPrincipal and isUserInRole. Here is how spring security does it.
When you configure spring, it can load the following filters:
http://static.springframework.org/spring-security/site/reference/html/ns-config.html#filter-stack
As part of the standard filter configuration the SecurityContextHolderAwareRequestFilter filter is loaded.
Examining the filter # https://fisheye.springsource.org/browse/spring-security/tags/spring-security-parent-2.0.4/core/src/main/java/org/springframework/security/wrapper/SecurityContextHolderAwareRequestFilter.java?r=2514
You can see it wraps and changes the HttpServletRequest object to the SecurityContextHolderAwareRequestWrapper class which extends HttpServletRequestWrapper which implements HttpServletRequest and feed it back to the standard Servlet Filter doFilter chain. Since spring security filter should be configured as the first filter, all subsequent classes will see the SecurityContextHolderAwareRequestWrapper instead. This includes JSP pages or Servlets behind this filter.
When you make a call to isUserInRole or getUserPrincipal from the JSP page, Servlet or any framework behind this filter, it is calling the HttpServletRequest implementation from Spring Security.
If you use the security filter, yes it does. I believe this is the default behavior.
Exactly which class you're getting back depends on your configuration, but they all implement the Principal interface by way of Spring's own org.springframework.security.Authentication interface which extends it.
I've used request.getUserPrincipal() and request.isUserInRole() in a Spring application and it works seamlessly, even within JSPs.
I do believe that Spring Security stores this information in the SecurityContext and not in the request though. You could easily write a FilterSecurityInterceptor that can be configured to add this info to the request also.

Categories

Resources