3.3 添加MVC相关文件
添加mvc相关文件,文件结构如下:
①首先添加一个Controller:
package cn.flylolo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author FlyLolo * @date 2021/10/9 16:42 */ @RestController @RequestMapping("user") public class UserController { @GetMapping("") public String helloWorld(){ return "Hello World!"; } }
②在resources目录下新建springmvc.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <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: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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="cn.flylolo"/> <mvc:annotation-driven /> <mvc:default-servlet-handler /> </beans>
③webapp目录下新建WEB-INF文件夹,其中新建web.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置springmvc核心servlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.4 设置Artifacts
打开File->Project Struture设置,左侧切换到Artifacts,可以看到已经自动生成的两个Artifact,选择带"exploded"后缀的,做如下修改:
Name比较长,可以自行修改,不改也可以,本例改为flylolo-readcode
Output directory自动生成的路径有问题,去掉"exploded", 例如本例改为:F:\spring-framework\flylolo-readcode\build\libs\flylolo-readcode-6.0.0-SNAPSHOT.war。
最终结果如下图: