SpringMVC学习(二)——注解
出处:PC的个人Blog
1. 主要注解
@Controller
@RequestMapping
@PostMapping
@GetMapping
@PathVariable
1.1 @Controller
@Controller的使用需要进行包扫描
<context:component-scan base-package="com.peng.controller"/>
再次进行相对应的控制类
@Controller
@RequestMapping("/r")
public class HelloController {
@RequestMapping("/hello")
public String hello(Model model) {
// 封装数据
model.addAttribute("msg", "Hello,SpringMVC");
return "test"; // 被视图解析处理
}
}
- 可以使用类@RequestMapping和方法@RequestMapping组合一起
- 类中的方法可以是多个,映射不同的@RequestMapping
1.2 RestFull风格讲解
对于域名后缀斜杠后面不使用 ? 或者 &这些符号,要与PathVariable 协同,可以使用相同url 对应不同的提交方法,同时简洁高效,个人认为安全可以隐藏参数
使用
@PostMapping
@GetMapping
区分
-
@PathVariable 函数参数变量路径
-
get请求
// 原来的风格 : http://localhost:8080/add?a=1&b=2 // RestFul :http://localhost:8080/add1/a/b @RequestMapping("/add") public String test1(int a, int b, Model model) { int res = a + b; model.addAttribute("msg", "结果为" + res); return "test"; } @RequestMapping("/add1/{a}/{b}") public String test2(@PathVariable int a,@PathVariable int b, Model model) { int res = a + b; model.addAttribute("msg", "结果为" + res); return "test"; }
-
// 网络请求方法 public enum RequestMethod { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; }
-
指定域名方法,get post等
@RequestMapping(value = "/hello", method = RequestMethod.GET)
2. ServletAPI
- HttpServletRequest 和 HttpServletResponse 进行转发和重定向
@Controller
public class ModelTest1 {
@RequestMapping("/m1/t1")
public String test(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
System.out.println(session.getId());
return "test";
}
}
3. SpringMVC 进行重定向和转发
-
视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!-- 前缀后缀设置 类似sql中mybatis中的设置--> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>
3.1 无需视图解析器
重定向 : 跳转地址栏url是会改变的
跳转不会改变地址栏的地址
@Controller
public class ModelTest2 {
@RequestMapping("/m2/t1")
public String test1(Model model) {
//转发
model.addAttribute("msg", "good");
return "forward:/WEB-INF/jsp/test.jsp";
}
@RequestMapping("/m2/t2")
public String test2(Model model) {
//重定向
model.addAttribute("msg", "good");
return "redirect:/index.jsp";
}
}
- 访问 http://localhost:8080/m2/t2 重定向地址为 http://localhost:8080/index.jsp?msg=good
3.2 有视图解析器
对于转发的情况可以少使用前缀和后缀
@Controller
public class ModelTest2 {
@RequestMapping("/m2/t1")
public String test1(Model model) {
//转发
model.addAttribute("msg", "good");
return "test";
}
@RequestMapping("/m2/t2")
public String test2(Model model) {
//重定向
model.addAttribute("msg", "good");
return "redirect:/index.jsp";
}
}