1.导入jar包
2.在web.xml中配置前端控制器DispatcherServlet
2.1 如果不配置<init-param>,则默认找/WEB-INF/<servlet-name>-servlet.xml.配置<init-param>是为了改变默认加载的配置文件名称和路径
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 配置前端控制器 --> <servlet> <servlet-name>jqk</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>jqk</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3.在src下新建springmvc.xml
3.1 引入xmlns:mvc命名空间(可以在spring帮助文档的/spring-framework-4.1.6.RELEASE-dist/spring-framework-4.1.6.RELEASE/docs/spring-framework-reference/htmlsingle中搜索)
<?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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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="com.bjsxt.controller"></context:component-scan> <!-- 注解驱动 --> <!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandler Mapping --> <!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerA dapter --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源 --> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> </beans>
4.编写控制器类
@Controller public class DemoController { @RequestMapping("demo") public String demo(){ System.out.println("执行 demo"); return "main.jsp"; } @RequestMapping("demo2") public String demo2(){ System.out.println("demo2"); return "main1.jsp"; } }
原文地址:https://www.cnblogs.com/stitchZsx/p/9853320.html
时间: 2024-11-13 06:49:06