1.配置
spring-servlet.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">
<!-- 自动扫描包-->
<context:component-scan base-package="com.ming.controller"/>
<!-- 让SpringMVC不处理静态资源 -->
<mvc:default-servlet-handler/>
<!-- 支持mvc注解驱动-->
<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.注解
2.1 controller
@Controller
public class HelloController {...}
@Controller:代表这个类会被spring接管
2.2 RequestMapping
@RequestMapping("/xxx"):真实访问地址(自定义)
1)放类上和方法上
例如:
@RequestMapping("/h1")
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){...}
}
真实访问地址:localhost:8080/项目名/h1/hello
注意:访问类中的所有方法都必须在前面加上“/h1”
2)放方法上
例如:
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model){...}
}
真实访问地址:localhost:8080/项目名/hello
2.3 PathVariable(Restful风格)
@PathVariable:让方法参数的值对应绑定到一个URI模板变量上。
例如:
@RequestMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res=a+b;
model.addAttribute("msg","结果为:"+res);
return "test";
}
结果:
2.4 PostMapping(Restful风格)
@ PostMapping:通过提交的方式来访问真实地址
例如:
@PostMapping("/add/{a}/{b}")
public String test2(@PathVariable String a, @PathVariable String b, Model model){
String res=a+b;
model.addAttribute("msg","结果为:"+res);
return "test";
}
a.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/SpringMVC_04_controller_war_exploded/add/1/2" method="post">
<input type="submit">
</form>
</body>
</html>
结果:
提交之后: