Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Spring, траблы маппинга URL'а


Автор: vns955 25.10.2009, 16:26
Всем здрям!
Есть простое приложение на MVC Spring (Spring 2.0, Apache Tomcat 6.0.20).
Кусок файла настройки MVC для приложения:

Код

        <bean id="urlMapAuthenticate"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="httpRequestInterceptor" />
            </list>
        </property>
        <property name="urlMap">
            <props>
                <prop key="/timesheetlist.htm">timesheetListController</prop>
                <prop key="/enterhours.htm">enterHoursController</prop>
            </props>
        </property>
    </bean>

    <bean id="httpRequestInterceptor"
        class="com.visualpatterns.timex.controller.HttpRequestInterceptor">
        <property name="signInPage">
            <value>signin.htm</value>
        </property>
        <property name="applicationSecurityManager">
            <ref bean="applicationSecurityManager" />
        </property>
    </bean>

    <bean name="timesheetListController"
        class="com.visualpatterns.timex.controller.TimesheetListController">
        <property name="timesheetManager">
            <ref bean="timesheetManager" />
        </property>
        <property name="applicationSecurityManager">
            <ref bean="applicationSecurityManager" />
        </property>
         <property name="timexJmxBean">
            <ref bean="timexJmxBean" />
        </property>
        <property name="successView">
            <value>timesheetlist</value>
        </property>
    </bean>

    <bean name="enterHoursController"
        class="com.visualpatterns.timex.controller.EnterHoursController">
        <property name="sessionForm">
            <value>true</value>
        </property>
        <property name="commandClass">
            <value>com.visualpatterns.timex.model.Timesheet</value>
        </property>
        <property name="formView">
            <value>enterhours</value>
        </property>
        <property name="successView">
            <value>redirect:timesheetlist.htm</value>
        </property>
        <property name="validator">
            <ref bean="enterHoursValidator" />
        </property>
        <property name="timesheetManager">
            <ref bean="timesheetManager" />
        </property>
        <property name="departmentManager">
            <ref bean="departmentManager" />
        </property>
        <property name="applicationSecurityManager">
            <ref bean="applicationSecurityManager" />
        </property>
    </bean>

Проблема в том, что не вызывается метод preHandle() класса HttpRequestInterceptor, кот. должен проверять залогинен ли сейчас юзер в системе или нет (если нет — то вызывать страницу авторизации SignIn). Не вызывается он только если я вбиваю в браузер строку /timesheetlist.htm, для /enterhours.htm — все Ок. Т.е. вызывается соответствующий сервлет для /timesheetlist.htm для последнего залогиненого юзера, хотя он сделал логаут (минуя вызов preHandle).
Приведу код для HttpRequestInterceptor, TimesheetListController (для просмотра данных), EnterHoursController (для ввода и записи новых данных):

HttpRequestInterceptor:

Код

public class HttpRequestInterceptor extends HandlerInterceptorAdapter
{
    private String signInPage;
    private ApplicationSecurityManager applicationSecurityManager;

    /**
     * Uses ApplicationSecurityManager to ensure user is logged in; if not,
     * then user is forwarded to the sign-in page.
     * @see ApplicationSecurityManager
     */
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception
    {
        System.out.println("HttpRequestInterceptor::preHandle()");
        Employee employee = (Employee) applicationSecurityManager
                .getEmployee(request);
        if (employee == null)
        {
            System.out.println("HttpRequestInterceptor::preHandle():  null");
            response.sendRedirect(this.signInPage);
            return false;
        }
        System.out.println("HttpRequestInterceptor::preHandle():  not null");

        return true;
    }

    public String getSignInPage()
    {
        return signInPage;
    }

    public void setSignInPage(String signInPage)
    {
        this.signInPage = signInPage;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }
}

TimesheetListController:

Код

public class TimesheetListController implements Controller
{
    private TimesheetManager timesheetManager;
    private ApplicationSecurityManager applicationSecurityManager;
    public static final String MAP_KEY = "timesheets";
    private String successView;
    private TimexJmxBean timexJmxBean;

    /**
     * Returns a list of Timesheet database objects in ModelAndView.
     * @see com.visualpatterns.timex.model.Timesheet
     */
    public ModelAndView handleRequest(
            HttpServletRequest request,
            HttpServletResponse response) throws Exception
    {
        Employee employee = (Employee) applicationSecurityManager
                .getEmployee(request);
        List timesheets = timesheetManager.getTimesheets(employee
                .getEmployeeId());
        timexJmxBean.setTimesheetsFetched(timexJmxBean.getTimesheetsFetched()
                + timesheets.size());
        return new ModelAndView(getSuccessView(), MAP_KEY, timesheets);
    }

    public TimesheetManager getTimesheetManager()
    {
        return timesheetManager;
    }

    public void setTimesheetManager(TimesheetManager timesheetManager)
    {
        this.timesheetManager = timesheetManager;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }

    public String getSuccessView()
    {
        return successView;
    }

    public void setSuccessView(String successView)
    {
        this.successView = successView;
    }

    public TimexJmxBean getTimexJmxBean()
    {
        return timexJmxBean;
    }

    public void setTimexJmxBean(TimexJmxBean timexJmxBean)
    {
        this.timexJmxBean = timexJmxBean;
    }
}

EnterHoursController:

Код

public class EnterHoursController extends SimpleFormController
{
    private TimesheetManager timesheetManager = null;
    private DepartmentManager departmentManager = null;
    private ApplicationSecurityManager applicationSecurityManager;
    public static final String TID = "tid";

    /**
     * Returns a new instance of Timesheet object if "tid" HTTP parameter is
     * specified; other returns instance of object in database matching the
     * value of the "tid" parameter.
     * @see Timesheet
     */
    protected Object formBackingObject(HttpServletRequest request)
    {
        if (request.getParameter(TID) != null
                && request.getParameter(TID).trim().length() > 0)
            return timesheetManager.getTimesheet(Integer.parseInt(request
                    .getParameter(TID)), false);

        Timesheet timesheet = new Timesheet();
        Employee employee = (Employee) applicationSecurityManager
                .getEmployee(request);
        timesheet.setEmployeeId(employee.getEmployeeId());
        timesheet.setStatusCode("P");
        timesheet.setPeriodEndingDate(DateUtil.getCurrentPeriodEndingDate());
        return timesheet;
    }

    /**
     * Registers the MinutesPropertyEditor
     */
    protected void initBinder(
            HttpServletRequest request,
            ServletRequestDataBinder binder) throws Exception
    {
        binder.registerCustomEditor(int.class, new MinutesPropertyEditor());
    }

    /**
     * Returns Hashmap containing a list of all Department databse records
     * @see com.visualpatterns.timex.model.Department
     */
    protected Map referenceData(HttpServletRequest request) throws Exception
    {
        HashMap model = new HashMap();
        model.put("departments", departmentManager.getDepartments());

        return model;
    }

    /**
     * Saves Timesheet command object using 
     * timesheetManager.saveTimesheet(timesheet);
     * @see TimesheetManager
     */
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
    {
        Timesheet timesheet = (Timesheet) command;
        timesheetManager.saveTimesheet(timesheet);
        request.getSession().setAttribute(
                "message",
                getMessageSourceAccessor().getMessage(
                        "message.enterhours.savesuccess"));
        return new ModelAndView(getSuccessView());
    }

    public TimesheetManager getTimesheetManager()
    {
        return timesheetManager;
    }

    public void setTimesheetManager(TimesheetManager timesheetManager)
    {
        this.timesheetManager = timesheetManager;
    }

    public DepartmentManager getDepartmentManager()
    {
        return departmentManager;
    }

    public void setDepartmentManager(DepartmentManager departmentManager)
    {
        this.departmentManager = departmentManager;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }
}

Пожскажите плз в чем тут дело.
Заранее спасибо.
 

Автор: vns955 25.10.2009, 16:48
Могу также добавить, что если после ввода урла /timesheetlist.htm в браузер не нажимать ввод а нажать обновить - то заветный метод вызывается и далее всё как надо. То же просходит если браузер закрыть, а затем запустить заново. Такое впечатление что этот урл хранится в кеше. Но почему тогда с /enterhours.htm всё нормально? В чем разница? :(

Автор: vns955 26.10.2009, 15:42
К моему большому удивлению только сейчас обнаружил что на Opera все работает (до этого работал с IE 6.0)! Где-же глюк?  Куда копать?

Автор: vns955 27.10.2009, 01:10
Попробовал вообще вырубить Tomcat — и эта страница грузится из кеша. Где это прописано что её надо сохранять в кеше? В сервлете или JSP? Как прописать явно чтоб она там не сохранялась? И почему только так происходит на IE6?

Автор: magicfly 27.10.2009, 01:22
http://www.jguru.com/faq/view.jsp?EID=377

Автор: vns955 27.10.2009, 14:50
Спасибо  smile 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)