无法范围春控制器请求时,一个组件的作用域确定为会议(Cannot scope Spring cont

2019-09-21 01:09发布

我想跟着导游在这个网站正常范围我的豆子的春天web应用程序:

http://richardchesterwood.blogspot.com/2011/03/using-sessions-in-spring-mvc-including.html

我试图按照方法3,这基本上意味着我要我的范围组件类的会议,因此,我不得不范围我控制器类的请求。 我有控制器把我的JSP页面,因此可以使用。

当我尝试这样做,虽然我的web应用程序已建立的问题,当我尝试去网页它给了我一个503 service_unavailable错误。

生成错误是:

重度:上下文初始化失败org.springframework.beans.factory.BeanCreationException:错误创建名称为豆'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0:豆的初始化失败; 嵌套的例外是java.lang.IllegalStateException:不能映射处理程序“currentWeekController”到URL路径[/时间跟踪]:已经有处理程序“scopedTarget.currentWeekController”映射。

以下是相关类和JSP页面。 如果你有什么事请你只问!

CurrentWeekController控制器类:

package controllers;

import javax.servlet.http.HttpServletRequest;

import models.CurrentWeek;
import models.ModelMap;
import models.User;

import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * this is the controller for current week, it lets you change the current week
 * and get values from the current week
 * 
 * @author CorayThan
 * 
 */
@Controller
@Scope("Request")
public class CurrentWeekController {

    private static final int MONDAY = 1;
    private static final int TUESDAY = 2;
    private static final int WEDNESDAY = 3;
    private static final int THURSDAY = 4;
    private static final int FRIDAY = 5;
    private static final int SATURDAY = 6;
    private static final int SUNDAY = 7;

    @Autowired
    private User user;

    @Autowired
    private CurrentWeek currentWeek;

    @Autowired
    private ModelMap hashmap;

    /**
     * @return the user
     */
    public User getUser() {
        return user;
    }

    /**
     * @param user
     *            the user to set
     */
    public void setUser(User user) {
        this.user = user;
    }

    /**
     * @return the currentWeek checks to make sure the week isn't null and its
     *         monday isn't null and fixes them if they are
     */
    public CurrentWeek getCurrentWeek() {
        if (currentWeek == null) {
            this.createNewCurrentWeek();
        }
        if (currentWeek.getMonday() == null) {
            this.createCurrentWeek(MutableDateTime.now());
        }
        return currentWeek;
    }

    /**
     * @param currentWeek
     *            the currentWeek to set
     */
    public void setCurrentWeek(CurrentWeek currentWeek) {
        this.currentWeek = currentWeek;
    }

    /**
     * @return the hashmap
     */
    public ModelMap getHashmap() {
        return hashmap;
    }

    /**
     * @param hashmap
     *            the hashmap to set
     */
    public void setHashmap(ModelMap hashmap) {
        this.hashmap = hashmap;
    }

    /**
     * no arg constructor
     */
    public CurrentWeekController() {

    }

    /**
     * this is a post method called when a button is clicked on the time
     * tracking jsp page. It reloads the page with a different week
     * 
     * @param pageWeek
     * @param request
     * @return
     */

    @RequestMapping(value = "TimeTracking")
    public ModelAndView changeTheWeek(HttpServletRequest request) {
        String whichWayWeek = request.getParameter("changeWeek");

        if ("Previous Week".equals(whichWayWeek)) {
            this.subtractOneWeek();
        }
        if ("Next Week".equals(whichWayWeek)) {
            this.addOneWeek();
        }

        return new ModelAndView("redirect:/jsp-pages/TimeTracking.jsp",
                hashmap.makeHashMap());
    }

    /**
     * This creates a current week object by setting that week's monday to the
     * proper monday for that week using whatever date you give it
     * 
     * 
     * @param calendar
     * @return
     */
    public CurrentWeek createCurrentWeek(MutableDateTime theCurrentDate) {

        int day = checkForNull(theCurrentDate);

        switch (day) {

        case SUNDAY:
            theCurrentDate.addDays(-6);
            currentWeek.setMonday(theCurrentDate);
            break;
        case SATURDAY:
            theCurrentDate.addDays(-5);
            currentWeek.setMonday(theCurrentDate);
            break;
        case FRIDAY:
            theCurrentDate.addDays(-4);
            currentWeek.setMonday(theCurrentDate);
            break;
        case THURSDAY:
            theCurrentDate.addDays(-3);
            currentWeek.setMonday(theCurrentDate);
            break;
        case WEDNESDAY:
            theCurrentDate.addDays(-2);
            currentWeek.setMonday(theCurrentDate);
            break;
        case TUESDAY:
            theCurrentDate.addDays(-1);
            currentWeek.setMonday(theCurrentDate);
            break;
        case MONDAY:

            currentWeek.setMonday(theCurrentDate);
            break;
        default:
            this.setCurrentWeek(null);
            break;

        }
        return this.getCurrentWeek();

    }

    /**
     * @param theCurrentDate
     * @return
     * makes sure the current date isn't null, and returns an int equal to 
     * the day of the week it is in joda time
     */
    private int checkForNull(MutableDateTime theCurrentDate) {
        int day = 0;
        if (theCurrentDate != null) {
            day = theCurrentDate.getDayOfWeek();
        }
        return day;
    }

    /**
     * makes a new current week set to the real current week
     * 
     * @return
     */

    public CurrentWeek createNewCurrentWeek() {
        MutableDateTime dateTime = MutableDateTime.now();
        CurrentWeek currentWeek = new CurrentWeek();
        this.setCurrentWeek(currentWeek);

        return createCurrentWeek(dateTime);
    }

    /**
     * subtracts one week from a currentweek
     * 
     * 
     * @return
     */
    public void subtractOneWeek() {

        MutableDateTime newMonday = (MutableDateTime) this.getCurrentWeek()
                .getMonday().clone();
        newMonday.addDays(-7);

        this.setCurrentWeek(createCurrentWeek(newMonday));

    }

    /**
     * adds one week to a currentweek
     * 
     * @param currentWeek
     * @return
     */
    public void addOneWeek() {

        MutableDateTime newMonday = (MutableDateTime) this.getCurrentWeek()
                .getMonday().clone();
        newMonday.addDays(7);

        this.setCurrentWeek(createCurrentWeek(newMonday));
    }

    /**
     * TODO: make this method into a method that accepts a current week and
     * checks if you can add a week to it without going entirely into the future
     * 
     * @param currentWeek
     * @return
     */
    public CurrentWeek checkIfCurrentWeekIsEntirelyInFuture() {
        return this.getCurrentWeek();

    }

    /**
     * returns the first day of the week as a formatted date time
     * 
     * @return
     */

    public String firstDayOfThisWeek() {

        MutableDateTime firstDay = this.getCurrentWeek().getSunday();

        DateTimeFormatter dateFormatter = DateTimeFormat
                .forPattern("MM/dd/yyyy");

        return dateFormatter.print(firstDay);
    }

    /**
     * returns the last day of this week as a formatted date time
     * 
     * @return
     */

    public String lastDayOfThisWeek() {

        MutableDateTime lastDay = this.getCurrentWeek().getSaturday();

        DateTimeFormatter dateFormatter = DateTimeFormat
                .forPattern("MM/dd/yyyy");

        return dateFormatter.print(lastDay);
    }

}

这里是CurrentWeek组件类。

package models;

import org.joda.time.MutableDateTime;
import org.springframework.stereotype.Component;

/**
 * this is a class that holds the current week for views
 * 
 * @author CorayThan
 * 
 */
@Component
// @Scope ("Session")
public class CurrentWeek {

    private MutableDateTime monday;

    /**
     * default constructor
     */
    public CurrentWeek() {

    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getSunday() {
        MutableDateTime sunday = (MutableDateTime) monday.clone();
        sunday.addDays(-1);
        return sunday;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getMonday() {
        return monday;
    }

    /**
     * @param saturdayTime
     *            pass a MutableDateTime to set this date of the CurrentWeek
     *            object to the correct date for that week
     */
    public void setMonday(MutableDateTime saturdayTime) {
        this.monday = saturdayTime;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getTuesday() {
        MutableDateTime tuesday = (MutableDateTime) monday.clone();
        tuesday.addDays(1);
        return tuesday;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getWednesday() {
        MutableDateTime wednesday = (MutableDateTime) monday.clone();
        wednesday.addDays(2);
        return wednesday;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getThursday() {
        MutableDateTime thursday = (MutableDateTime) monday.clone();
        thursday.addDays(3);
        return thursday;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getFriday() {
        MutableDateTime friday = (MutableDateTime) monday.clone();
        friday.addDays(4);
        return friday;
    }

    /**
     * @return a MutableDateTime which is of the correct date for this specific
     *         day
     */
    public MutableDateTime getSaturday() {
        MutableDateTime saturday = (MutableDateTime) monday.clone();
        saturday.addDays(5);
        return saturday;
    }

}

最后引用CurrentWeekController JSP文件:

<%@page contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@page import="daos.*"%>
<%@page import="controllers.*"%>
<%@page import="models.*"%>

<jsp:useBean id="userDao" class="daos.UserDao" scope="request" />

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<jsp:useBean id="timeTrackingControl"
    class="controllers.TimeTrackingController" scope="request" />
<jsp:useBean id="currentWeek" class="controllers.CurrentWeekController"
    scope="request" />
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Time Tracking Page</title>
<script type="text/javascript" src= "../javascriptpages/timeTracking.js"></script>
<link rel="stylesheet" type="text/css" href="csspages/global.css" />

<style type="text/css"></style>
</head>

<body>

    <div>
        <h1>User Time Tracking Page</h1>

    </div>
    <div id="content">

    <form method="POST" action="../TimeTracking.html">
            <span> <input name="changeWeek" type="submit" value="Previous Week"/> Hours for the week of
                <%=currentWeek.firstDayOfThisWeek()%> until <%=currentWeek.lastDayOfThisWeek()%>
                <input name="changeWeek" type="submit" value="Next Week"/>
            </span>
    </form>


            <table border="1">
                <tr>
                    <th>Sunday</th>
                    <th>Monday</th>
                    <th>Tuesday</th>
                    <th>Wednesday</th>
                    <th>Thursday</th>
                    <th>Friday</th>
                    <th>Saturday</th>
                </tr>
                <tr>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getSunday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getMonday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getTuesday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getWednesday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getThursday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getFriday())%></td>
                    <td><%=timeTrackingControl.totalWorkTimeForOneDate(currentWeek.getCurrentWeek().getSaturday())%></td>
                </tr>
            </table>

            <input type="button" value="<%=timeTrackingControl.displayClockButton()%>"
                onClick="clockInOrOutReloadPage()">

    </div>

</body>
</html>

Answer 1:

控制器应该是应用在Spring MVC作用域(你不需要明确范围他们因为这是默认值)。

任何请求级别的数据应该使用模型的属性来完成:

@ModelAttribute("foo")
public Foo createFoo(@RequestParam("bar") int bar) {
   return new Foo(bar);
}


@RequestMapping(...)
public ModelAndView baz(HttpServletRequest req, HttpServletResponse response,
    @ModelAttribute("foo") Foo foo) {
   ...
}

Spring将(通过您的“createFoo”)方法自动创建“foo”的实例,并把它在要求范围之内。 然后,在你的映射方法注释的方法参数,它会自动拉,从请求范围,并把它传递给你的方法。

如果你想有一个模型属性存储在session范围内,添加此批注控制器类:

@SessionAttributes({"foo"})

这意味着你不应该在你的控制器本身的任何状态下,只有在模型属性(无论是在请求或会话范围),并应注入该州进入你的映射方法调用。



Answer 2:

检查此链接https://jira.springsource.org/browse/SPR-5697它始终是最好在控制器级别和方法级别requestmapping属性添加requestmapping属性,如果在使用了相同requestmapping的属性值另一个控制器则可能显示此错误。 为了避免在控制器级别这个附加requestmapping属性。

@Controller
@SessionAttributes("command"(
@RequestMapping(value="CurrentWeek")

@RequestMapping(value="TimeTracking.html" method="RequesstMethod.POST)
public ModelAndView processForm(....){
}


Answer 3:

为控制器默认范围是单件。 除非你有一个很好的理由去改变它,不要做它。 辛格尔顿正常工作与组件作用域会议



文章来源: Cannot scope Spring controller as request when a component is scoped as session