Контроллеры Mapping - PullRequest
       25

Контроллеры Mapping

0 голосов
/ 13 сентября 2018

Что не так? Мне написали два контроллера, но я не понимаю, что не так. Не знаю, как правильно настроить работу обоих контроллеров.

Тип отчета об исключении

Message Servlet.init() for servlet [mvc-dispatcher] threw exception

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

javax.servlet.ServletException: Servlet.init() for servlet [mvc-dispatcher] threw exception

rg.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'bookController' bean method 
public java.lang.String com.jackson.BookController.editBook(int,org.springframework.ui.Model)
to {[/edit/{id}],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'authorController' bean method
public java.lang.String com.jackson.AuthorController.editAuthor(int,org.springframework.ui.Model) mapped.


package com.jackson;


@Controller
public class AuthorController {
    private AuthorService  authorService;

    @Autowired(required = true)
    @Qualifier(value = "authorService")
    public void setBookService(AuthorService authorService) {
        this.authorService = authorService;
    }

    @RequestMapping
            (value = "authors", method = RequestMethod.GET)
    public String listAuthors(Model model){
        model.addAttribute("author", new Author());
        model.addAttribute("listAuthors", this.authorService.list());

        return "authors";
    }

    @RequestMapping
            (value = "authors/add", method = RequestMethod.POST)
    public String addAuthor(@ModelAttribute("author") Author author){
        if(author.getId() == 0){
            this.authorService.addAuthor(author);
        }else {
            this.authorService.updateAuthor(author);
        }

        return "redirect:/authors";
    }


    @RequestMapping("/remove/{id}")
    public String removeAuthor(@PathVariable("id") int id){
        this.authorService.removeAuthor(id);

        return "redirect:/authors";
    }

    @RequestMapping("/edit/{id}")
    public String editAuthor(@PathVariable("id") int id, Model model){
        model.addAttribute("author", this.authorService.getAuthorById(id));
        model.addAttribute("listBooks", this.authorService.list());

        return "authors";
    }

    @RequestMapping("authordata/{id}")
    public String authorData(@PathVariable("id") int id, Model model){
        model.addAttribute("author", this.authorService.getAuthorById(id));

        return "authordata";
    }
}

На мой взгляд, весь код работает правильно, но все еще понимает, что не так

package com.jackson;        
@RestController
public class BookController {

    private BookService bookService;

    @Autowired(required = true)
    @Qualifier(value = "bookService")
    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    @RequestMapping(value = "books", method = RequestMethod.GET)
    public String listBooks(Model model){
        model.addAttribute("book", new Book());
        model.addAttribute("listBooks", this.bookService.listBooks());

        return "books";
    }

    @RequestMapping(value = "/books/add", method = RequestMethod.POST)
    public String addBook(@ModelAttribute("book") Book book){
        if(book.getId() == 0){
            this.bookService.addBook(book);
        }else {
            this.bookService.updateBook(book);
        }

        return "redirect:/books";
    }

    @RequestMapping("/remove/{id}")
    public String removeBook(@PathVariable("id") int id){
        this.bookService.removeBook(id);

        return "redirect:/books";
    }

    @RequestMapping("edit/{id}")
    public String editBook(@PathVariable("id") int id, Model model){
        model.addAttribute("book", this.bookService.getBookById(id));
        model.addAttribute("listBooks", this.bookService.listBooks());

        return "books";
    }

    @RequestMapping("bookdata/{id}")
    public String bookData(@PathVariable("id") int id, Model model){
        model.addAttribute("book", this.bookService.getBookById(id));

        return "bookdata";
    }
}

По моему мнению, весь код работает правильно, но все еще понимает, что не так

mvc-dispacther-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.jackson"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

// конфигурация базы данных

    <!-- Hibernate 4 SessionFactory Bean definition -->
    <bean id="hibernate4AnnotatedSessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="annotatedClasses">
            <list>
                <value>com.jackson.Book</value>
                <value>com.jackson.Author</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!--BookDao and BookService beans-->
    <bean id="bookDao" class="com.jackson.BookDao">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>

    <bean id="bookService" class="com.jackson.BookService">
        <property name="bookDao" ref="bookDao"/>
    </bean>

    <bean id="authorDao" class="com.jackson.AuthorDao">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>

    <bean id="authorService" class="com.jackson.AuthorService">
        <property name="authorDao" ref="authorDao"/>
    </bean>

    <context:component-scan base-package="com.jackson"/>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory"/>
    </bean>

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>

</beans>


web.xml
<web-app version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>com.jackson.Book Manager</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Ответы [ 2 ]

0 голосов
/ 13 сентября 2018

У ваших контроллеров есть методы сопоставления конфликтов.Не объявляйте один и тот же метод отображения запросов на разных контроллерах.

0 голосов
/ 13 сентября 2018

BookController должен иметь @Controller вместо @ RestController.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...