我想学习一些关于Spring的知识。我试图配置它,但有些东西我不能得到,因为看起来Spring似乎无法识别我的控制器。
这是我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>dispatcher</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
这个是servlet
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="it.mexpenses.controller" />
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="1" />
</bean>
</beans>
控制器:
package it.mexpenses.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class LoginController {
@GetMapping("/login")
public ModelAndView login() {
User user = loginService.login(username, password);
return new ModelAndView("welcome", "currentUser", null);
}
}
答案 0 :(得分:1)
在典型的spring MVC应用程序中,您会发现有两个spring配置文件,一个配置应用程序上下文的文件,通常以Spring上下文侦听器启动。
UITextView
Spring MVC配置文件通常以Spring调度程序servlet开头。例如。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
我强烈建议对Spring配置使用注释。它让生活更轻松,更现代......
您还可以使用春季启动生成项目,让您的生活更轻松:https://start.spring.io/
参考:Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?