1、spring 配置文件配置
<?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
https://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">
<!-- 指定要扫描的包,指定后包下的注解就会生效 -->
<context:component-scan base-package="com.study.controller"/>
<!-- 让srpingmvc 过滤一些资源,如 .JS .CSS .HTML文件,防止所有都走视图解析器 -->
<mvc:default-servlet-handler/>
<!-- 开启后默认帮助我们开启适配器和映射器,我们就不用自己配了 -->
<mvc:annotation-driven/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
2、controller 类书写
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","注解开发mvc");
// return 的字符串就是视图名,视图解析器会根据返回的视图名拼接
return "hello";
}
}
3、相关注解的作用
- @Controller:注册bean到spring容器中,并且声明自己是一个控制器类
- @RequestMapping:用于映射url到控制器类或一个特定的处理方法,可用于类和方法上,如果在类上,类中所有的方法都以该路径作为父路径
4、使用restful接口参数时候
- @PathVariable 用于接收rul上的参数
@RequestMapping(value = "/hello/{id}")
public String hello(@PathVariable int id, Model model){
model.addAttribute("msg","hello mvc!"+id);
return "hello";
}