简体   繁体   中英

How to validate a request to a JSP page in Struts2

A request to an Action can be validated using the Interceptors. Also, Direct request to a JSP page can be avoided using an empty action declaration. It is something like this;

<action name="home" >
        <result>home.jsp</result>
</action>  

I want to validate this calling to the JSP page. As I feel that a simple approach can be adding an Action ( ActionSupport ) with an Interceptor which checks the action name( and do some validation using session etc). But I've a doubt that whether it reduces the performance,because that action class doesn't do anything and just execute its execute() only(useless task...), and where there should be an empty Action .(BUT: as I ve read some docs on Struts2, it is said that even though we don't add an Action calss,the framework itself adds and action class which returns "success" therefore,adding an action class or not ourselves, doesn't affect newly )

Any way, I d like to know what your best approaches are to validate or authorized access to some JSP pages.( number of pages can be many.. not only to one jsp page)

Added: Example:
Lets say that, there are some restricted pages where all users can't have access,for example user's account page can be visited only to logged in users.There can be more such type of pages. If a request comes to a such page,the user has to be validated.Then, if the request comes through a empty/anonymous action (as explained in above code snip -only action name-no real class) how to validate such requests to JSP pages? Should an action class be used for this?

If your attention is to secure some part of your application so as only Authenticated as well authorize use can access that part, than you have two option

  1. Use an interceptor based authentication
  2. User a security API like Spring -security

Interceptor based authentication is quite easy. here is an example how to do this, but such authentication is not recommended for a production based and real life application since its really a very simple case.

if you are looking for a complete authentication system, i suggest you to look at Spring security.Its quite easy and configurable, all you need to tell the underlying spring mechanism which all areas and under secure tag and Spring security will intercept them before your action get called and only successful and authorize action will get called by spring security.

//This is for authorization

package com.kogent.action;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.apache.struts2.dispatcher.ng.ExecuteOperations;
import org.apache.struts2.dispatcher.ng.InitOperations;
import org.apache.struts2.dispatcher.ng.PrepareOperations;
import org.apache.struts2.dispatcher.ng.filter.FilterHostConfig;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

public class SessionController extends StrutsPrepareAndExecuteFilter {
    protected PrepareOperations prepare;
    protected ExecuteOperations execute;
    protected List<Pattern> excludedPatterns = null;

public void init(FilterConfig filterConfig) throws ServletException {
    InitOperations init = new InitOperations();
    try {
        FilterHostConfig config = new FilterHostConfig(filterConfig);
        init.initLogging(config);
        Dispatcher dispatcher = init.initDispatcher(config);
        init.initStaticContentLoader(config, dispatcher);

        prepare = new PrepareOperations(filterConfig.getServletContext(),
                dispatcher);
        execute = new ExecuteOperations(filterConfig.getServletContext(),
                dispatcher);
        this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

        postInit(dispatcher, filterConfig);
    } finally {
        init.cleanup();
    }

}

/**
 * Callback for post initialization
 */
protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig) {
}

public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try {
        prepare.setEncodingAndLocale(request, response);
        prepare.createActionContext(request, response);
        prepare.assignDispatcherToThread();
        if (excludedPatterns != null
                && prepare.isUrlExcluded(request, excludedPatterns)) {
            chain.doFilter(request, response);
        } else {
            request = prepare.wrapRequest(request);
            ActionMapping mapping = prepare.findActionMapping(request,
                    response, true);
            if (mapping == null) {
                boolean handled = execute.executeStaticResourceRequest(
                        request, response);
                if (!handled) {
                    chain.doFilter(request, response);
                }
            } else {
                //here you have to identify the whether the user have access to requested resource or not 
                //allow him if he was access.
                //if(someCondition)
                execute.executeAction(request, response, mapping);
                //else{
                //redirect the user how do you want it to be.
                ActionMapping modfiedActionMapping = new ActionMapping();
                modfiedActionMapping.setName("someActionName");
                modfiedActionMapping.setNamespace("someNameSpace");
                execute.executeAction(request, response, modfiedActionMapping);

            //}

            }
        }
    } finally {
        prepare.cleanupRequest(request);
    }
}

public void destroy() {
    prepare.cleanupDispatcher();
}

}

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>Point to your customized filter</filter-class>
</filter>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM