基本使用
在web.xml中配置SpringMVC提供的前端控制器DispatcherServlet
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param> <!--配置Spring全局配置文件的位置,当该类被加载时会自动创建IOC容器-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup> <!--让SpringIOC容器预加载-->
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern> <!--让Spring的前端控制器拦截所有请求-->
</servlet-mapping>
<!--
Tomcat默认有一个servlet是用于处理静态资源的,默认是匹配路径 / ,所以优先级最低,
也可以覆盖此配置达到排除静态资源的目的
-->
<!--<servlet-mapping>-->
<!-- <servlet-name>default</servlet-name>-->
<!-- <url-pattern>/static/*</url-pattern>-->
<!--</servlet-mapping>-->
再在Spring全局配置文件applicationContext.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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--
首先添加 xmlns:mvc="http://www.springframework.org/schema/mvc" 约束文件
再在 xsi:schemaLocation属性后增加 http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
之后使用下面标签才能有代码提示
-->
<context:component-scan base-package="com"/> <!--开启IOC注解扫描-->
<mvc:annotation-driven/> <!--开启SpringMVC注解开发模式-->
<mvc:default-servlet-handler/> <!--在使用DispatcherServlet前端控制器拦截时,将静态资源排除在外-->
<!-- <mvc:resources mapping="/static/**" location="/static/"/> -->
<!--resources标签也可以指定静态资源,以/static路径开头的,可访问/webapp/static目录-->
</beans>
在类中使用注解,具体如下
package com;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller //交由spring容器管理该类对象
public class Main {
@RequestMapping(value = "/test", method = RequestMethod.GET) //定义请求映射,若不指定请求方法则任意请求都可以
@ResponseBody //该方法的返回值直接返回
public String test() {
return "Hello world";
}
}

Comments NOTHING