Вопрос

Я хотел бы преобразовать этот SimpleFormController для использования поддержки аннотаций, представленной в Spring MVC 2.5.

Джава

public class PriceIncreaseFormController extends SimpleFormController {

    ProductManager productManager = new ProductManager();

    @Override
    public ModelAndView onSubmit(Object command)
            throws ServletException {

        int increase = ((PriceIncrease) command).getPercentage();
        productManager.increasePrice(increase);

        return new ModelAndView(new RedirectView(getSuccessView()));
    }

    @Override
    protected Object formBackingObject(HttpServletRequest request)
            throws ServletException {
        PriceIncrease priceIncrease = new PriceIncrease();
        priceIncrease.setPercentage(20);
        return priceIncrease;
    }

}

Весенняя конфигурация

<!-- Include basic annotation support -->
<context:annotation-config/>        

<!-- Comma-separated list of packages to search for annotated controllers. Append '.*' to search all sub-packages -->
<context:component-scan base-package="springapp.web"/>  

<!-- Enables use of annotations on controller methods to map URLs to methods and request params to method arguments  -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController">
    <property name="sessionForm" value="true"/>
    <property name="commandName" value="priceIncrease"/>
    <property name="commandClass" value="springapp.service.PriceIncrease"/>
    <property name="validator">
        <bean class="springapp.service.PriceIncreaseValidator"/>
    </property>
    <property name="formView" value="priceincrease"/>
    <property name="successView" value="hello.htm"/>
    <property name="productManager" ref="productManager"/>
</bean>

По сути, я хотел бы заменить всю конфигурацию XML для /priceincrease.htm bean-компонент с аннотациями внутри класса Java.Возможно ли это, и если да, то какие соответствующие аннотации мне следует использовать?

Спасибо, Дон

Это было полезно?

Решение

Это будет выглядеть примерно так, как показано ниже, хотя будет ли оно работать так, как есть, немного зависит от вашей конфигурации (преобразователь представлений и т. д.).Я также должен отметить, что существует около восьми миллиардов допустимых способов написать эту вещь.См. документацию Spring, 13.11.4 «Поддерживаемые аргументы метода обработчика и типы возвращаемых значений» для обзора безумия.Также обратите внимание, что вы можете автоматически подключить валидатор.

@Controller
@RequestMapping("/priceincrease.htm")
public class PriceIncreaseFormController {

    ProductManager productManager;

    @Autowired
    public PriceIncreaseFormController(ProductManager productManager) {
        this.productManager = productManager;
    }

    // note: this method does not have to be called onSubmit
    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(@ModelAttribute("priceIncrease") PriceIncrease priceIncrease, BindingResult result, SessionStatus status {

        new PriceIncreaseValidator().validate(priceIncrease, result);
        if (result.hasErrors()) {
            return "priceincrease";
        }
        else {
            int increase = priceIncrease.getPercentage();
            productManager.increasePrice(increase);
            status.setComplete();
            return "redirect:hello.htm";
        }
    }

    // note: this method does not have to be called setupForm
    @RequestMapping(method = RequestMethod.GET)    
    public String setupForm(Model model) {
        PriceIncrease priceIncrease = new PriceIncrease();
        priceIncrease.setPercentage(20);
        model.addAttribute("priceIncrease", priceIncrease);
        return "priceincrease";
    }

}

Другие советы

Кто-то завершил этот проект с помощью недавнего MVC, и он находится на github, так что вы можете увидеть, как все классы изменились по сравнению с руководством Spring.

Связь: Контроллер формы PriceIncrease

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top