Announcement Announcement Module
Collapse
No announcement yet.
Having the jsp file in more than one resolvers Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Having the jsp file in more than one resolvers

    hai friends

    i want to organise the jsp file in different folders based on its functionality.I the example i found that there is only one is viewResolver where we set the path of the jsp.Can map many path/different locations of jsp files.

    Help pls.

    Thanks(Have a nice day)
    Aniesh U.K

  • #2
    Just make your own. I have a BasicViewController that does exactly what you need. If you have a view of /secure/product/addProduct.html if will load a JSP from /secure/product/addProduct.jsp

    Code:
    /*
     * MPSC-Spring - A library of common code to use with the Spring framework
     * Copyright (C) 2005 Matt Parker
     * 
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     * 
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */
    package uk.co.mpcontracting.modules.spring.controller;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import org.springframework.validation.Errors;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * A simple view controller implementation that calculates the concrete view from the request
     *
     * @author Matt Parker ([email protected])
     */
    public class BasicViewController extends AbstractViewController
    {
        private static Log log = LogFactory.getLog(BasicViewController.class);
        
        /**
         * Processes the view request
         *
         * @param request The request
         * @param response The response
         * @return The model and view
         * @throws Exception If there are any problems with the view request
         */
        protected ModelAndView process(HttpServletRequest request, HttpServletResponse response,
            Errors errors) throws Exception
        {
            return (getViewFromRequest(request));
        }    
    }
    Code:
    /*
     * MPSC-Spring - A library of common code to use with the Spring framework
     * Copyright (C) 2005 Matt Parker
     * 
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     * 
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     */
    package uk.co.mpcontracting.modules.spring.controller;
    
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    
    import org.springframework.validation.BindException;
    import org.springframework.validation.Errors;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    import uk.co.mpcontracting.modules.spring.model.ControlModel;
    import uk.co.mpcontracting.modules.spring.support.ErrorUtils;
    
    /**
     * An abstract Spring controller that deals with resolving views
     *
     * @author Matt Parker ([email protected])
     */
    public abstract class AbstractViewController implements Controller
    {
        private static Log log = LogFactory.getLog(AbstractViewController.class);
        
        private static final String DEFAULT_MESSAGE = "error.standard.defaultMessage";
        
        /**
         * A hook for a sub-class to process the view request
         *
         * @param request The request
         * @param response The response
         * @return The model and view
         * @throws Exception If there are any problems with the view request
         */
        protected abstract ModelAndView process(HttpServletRequest request, HttpServletResponse response, 
            Errors errors) throws Exception;
        
        private AbstractFormController associatedFormController;
        private String successView;
        private String failureView;
        
        /**
         * Sets the associated form controller. This allows a view to be associated with a form which in
         * turn allows a form backing object to be created for the view to enable the Spring bind tags
         * to function correctly
         *
         * @param associatedFormController The associated form controller
         */
        public void setAssociatedFormController(AbstractFormController associatedFormController)
        {
            this.associatedFormController = associatedFormController;
        }
        
        /**
         * Sets the success view
         *
         * @param successView The success view
         */
        public final void setSuccessView(String successView)
        {
            this.successView = successView;
        }
        
        /**
         * Retrieves the success view
         *
         * @return The success view
         */
        protected final String getSuccessView()
        {
            return (successView);
        }
        
        /**
         * Sets the failure view
         *
         * @param failureView The failure view
         */
        public final void setFailureView(String failureView)
        {
            this.failureView = failureView;
        }
        
        /**
         * Retrieves the failure view
         *
         * @return The failure view
         */
        protected final String getFailureView()
        {
            return (failureView);
        }
    
        /**
         * Creates a form backing object if required then passes control to the process method
         *
         * @param request The request
         * @param response The response
         * @return The returned model and view
         * @throws Exception If there are any problems with the view request
         */
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception
        {
            // Create a form backing object if we have an associated form
            if (associatedFormController != null)
            {
                associatedFormController.createFormBackingObject(request);
            }
            
            BindException errors = new BindException("*", "*");
            ModelAndView modelAndView = process(request, response, errors);
            
            if (errors.hasErrors())
            {
                modelAndView.addAllObjects(errors.getModel());
            }
            
            return (modelAndView);
        }
        
        /**
         * Creates a model and view from the success view and request
         *
         * @param request The request
         * @return The created model and view
         */
        protected ModelAndView getSuccessView(HttpServletRequest request)
        {
            return (getViewFromURI(request, successView));
        }
        
        /**
         * Creates a model and view from the failure view and request
         *
         * @param request The request
         * @return The created model and view
         */
        protected ModelAndView getFailureView(HttpServletRequest request)
        {
            return (getViewFromURI(request, failureView));
        }
        
        /**
         * Creates a model and view from the request and a given control model
         *
         * @param request The request
         * @param controlModel The control model
         * @return The created model and view
         * @throws Exception If the control model is unable to be stored in the view
         */
        protected ModelAndView getViewFromRequestAndModel(HttpServletRequest request, ControlModel controlModel)
            throws Exception
        {
            controlModel.storeControlModel(request);
    
            ModelAndView modelAndView = getViewFromRequest(request);
            
            if (controlModel != null)
            {
                Map internalMap = controlModel.getControlModelMap();
                
                if (internalMap != null)
                {
                    modelAndView.addAllObjects(controlModel.getControlModelMap());
                }
            }
            
            return (modelAndView);
        }
        
        /**
         * Creates a model and view from the request
         *
         * @param request The request
         * @return The created model and view
         */
        protected ModelAndView getViewFromRequest(HttpServletRequest request)
        {
            return (getViewFromURI(request, request.getRequestURI()));
        }
        
        /**
         * Converts a given URI into a model and view given a request context
         *
         * @param request The request
         * @param uri The given URI
         * @return The model and view
         */
        protected ModelAndView getViewFromURI(HttpServletRequest request, String uri)
        {
            String contextPath = request.getContextPath() + "/";
            
            int startIndex = uri.lastIndexOf(contextPath);
            
            if (startIndex == -1)
            {
                startIndex = 0;
            }
            else
            {
                startIndex += contextPath.length();
            }
            
            int endIndex;
            
            if (uri.indexOf(";") != -1)
            {
                endIndex = uri.indexOf(";");
            }
            else if (uri.indexOf("?") != -1)
            {
                endIndex = uri.indexOf("?");
            }
            else
            {
                endIndex = uri.length();
            }
            
            String fileName = uri.substring(startIndex, endIndex);
            
            if (fileName.indexOf(".") != -1)
            {
                fileName = fileName.substring(0, fileName.lastIndexOf("."));
            }
            
            if (log.isDebugEnabled())
            {
                log.debug("Request URI - " + uri + " - translated to - " + fileName);
            }
            
            return (new ModelAndView(fileName));
        }
        
        /**
         * Convenience method to add an error into the current errors collection
         *
         * @param errors The current errors collection
         * @param errorMessage The message or key to add to the errors collection
         * @param arguments Any arguments that need to be resolved and added into the error message
         */
        protected void addError(Errors errors, String errorMessage, Object[] arguments)
        {
            if (errorMessage != null)
            {
                ErrorUtils.addCustomError(errors, errorMessage, arguments);
            }
            else
            {
                ErrorUtils.addCustomError(errors, DEFAULT_MESSAGE, arguments);
            }
        }
        
        /**
         * Convenience method to add an error into the current errors collection
         *
         * @param errors The current errors collection
         * @param errorMessage The message or key to add to the errors collection
         * @param resolvableArguments Any resolvable arguments that need to be added into the error message
         */
        protected void addErrorWithResolvableArguments(Errors errors, String errorMessage, 
            String[] resolvableArguments)
        {
            if (errorMessage != null)
            {
                ErrorUtils.addCustomErrorWithResolvableArguments(errors, errorMessage, resolvableArguments);
            }
            else
            {
                ErrorUtils.addCustomErrorWithResolvableArguments(errors, DEFAULT_MESSAGE, resolvableArguments);
            }
        }
    }
    There's a lot of extra stuff in the AbstractViewController that you probably don't want, but I'm sure you can work out what you need.

    Comment


    • #3
      hai bob

      thanks 4 u r kind reply.U are saying that the only way to have many jsp source(form different folders) is to using the code given below.Is there no way that 1/2 viewResolver cannot be used in applicationCOntext.xml.Can't we configure this in applicationContext.xml file.

      Thanks(Have a nice day)
      Aniesh U.k

      Comment


      • #4
        I think you can only have one view resolver configured (though I may be wrong). Besides, the resolver is not where your problem lies...

        I got the impression from your first post that you're using the UrlFilenameViewController to subclass your views from. If you look in the code for that file you'll see the getFilenameFromRequestURI method which is what translates your view names to JSPs. You'll see that it strips the whole path from the view which is why you can only have one directory with JSPs if you then use the JstlView view resolver.

        All I've done is basically ignore the UrlFilenameViewController and create my own base view controller which does what I want. Compare the difference between the getViewFromURI method in my code and the getFilenameFromRequestURI method I mentioned above and you'll see what I'm doing differently. You can then implement this in your own base view controller and make all your views extend that.

        Bob

        Comment


        • #5
          To be clear, you can have as many view resolvers in a context as you want. By default, they will all be discovered, and they will be ordered (using the Ordered interface).

          The trick, however, is that InternalResourceViewResolver can be at the end of the chain ONLY. It's not able to simply say "Nope, i don't have what you're looking for, please keep trying".

          Comment


          • #6
            Hai senthladd

            Thanks for u r reply.I InternalViewResolver there is a property called <prefix> which maps to the path of the jsp files.I need to have 2/3 prefix i,e i want to jsp files from different location.Is it possible or have 2 InternalResourceViewResolver.

            Thanks for all for the great support

            Aniesh U.k

            Comment


            • #7
              no, you can only have one InternalResourceViewResolver. If you want multiple directories, set the prefix to the common root directory ann include the variable parts in the view name.

              ie: prefix = WEB-INF/jsp
              view = dir1/hello (maps to WEB-INF/jsp/dir1/hello.jsp)
              view = dir2/search (maps to WEB-INF/jsp/dir2/search.jsp)

              Regards,

              Comment


              • #8
                Hai all
                Thanks all for the reply.I was expection this.It should be like this right

                <bean id="viewResolver" class="org.springframework.web.servlet.view.Intern alResourceViewResolver">
                <property name="viewClass"><value>org.springframework.web.se rvlet.view.JstlView</value></property>
                <property name="prefix"><value>/WEB-INF/jsp/</value></property>
                <property name="suffix"><value>.jsp</value></property>
                <property name="view"><value>dir1/hello ></value></property>
                <property name="view"><value> dir2/search ></value></property>
                </bean>


                Correct me if it is wrong
                Thanks all
                Aniesh U.K
                Last edited by anieshuk; Oct 30th, 2005, 11:20 PM.

                Comment


                • #9
                  seriously, I think you need to have a read through the reference docs and the introductory material available from the main Spring site. Your post demonstrates a lack of understanding of some of the very basic concepts and in all fairness, you can't expect people to continue investing that level of assistance if you haven't made a genuine effort yourself.

                  Did you actually try that example code before you posted it? If so, what happened? If it didn't work, what was the error and how did you go about trying to track it down? That's pretty much the minimum you should be doing before posting.

                  The "view" I talked about in my previous post relates to the ModelAndView, not the ViewResolver.

                  Kind regards,

                  Comment


                  • #10
                    Hai davison

                    THanks for u r suggestion.As u suggested i will take all my effort.Thanks for correcting me(my approach was wrong).Thanks a lot.

                    Aniesh U.K

                    Comment

                    Working...
                    X