SpringMVC(二)
Restful 风格
Restful风格就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制
功能:
- 资源:互联网所有的事物都可以被抽象为资源
- 资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
- 分别对应 添加、删除、修改、查找。
**传统方式操作资源:**通过不同的参数来实现不同的效果!方法单一,post和get
**使用RESTful操作资源:**可以通过不同的请求方式来实现不同的效果!方法:GET、POST、PUT、DELETE。
传统风格:http://127.0.0.1/item/queryltem.action?id=1
restful风格:http://127.0.0.1/item/1
优点
- 简洁
- 高效
- 安全
例:在变量前加@PathVariable
@Controller
public class RestfulController {
//
@RequestMapping("/add/{a}/{b}")
public String text1(@PathVariable int a,@PathVariable int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为:" + res);
return "hello";
}
}
重定向和转发
SpringMVC:结果跳转方式:
ModelAndView
设置ModelAndView对象,根据view的名称,和视图解析器跳到指定页面
页面:{视图解析器前缀+viewName+{视图解析器后缀}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
可以实现HttpServlet来实现转发和重定向的设置
也可以使用Springmvc的方式设置:
@Controller
public class RestfulController {
@RequestMapping("/add/{a}/{b}")
public String text1(@PathVariable int a,@PathVariable int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为:" + res);
return "redirect:/hello";
}
@PostMapping("/add/{a}/{b}")
public String text2(@PathVariable int a,@PathVariable int b, Model model) {
int res = a + b;
model.addAttribute("msg", "结果为:" + res);
return "forwrd:/index.jsp";
}
}
接收请求参数及数据回显
处理提交数据
-
提交的域名称和处理方法的参数名一致
提交数据:http://localhost:8080/hello?name=kuang
处理方法:
@RequestMapping("/hello") public String hello(String name){ System.out.println(name); return "hello"; } //后台输出: kuang
-
提交域名称和处理方法的参数名不一致
提交数据:http://localhost:8080/hello?username=kuang
处理方法:
1. @RequestMapping("/hello") public String hello( @RequesParam("username") String name){ System.out.println(name); return "hello"; } //后台输出: kuang
-
提交的是一个对象
要求提交的表单域和对象的属性名一致,参数使用对象即可
数据显示到前端的三种方式:
- ModleAndView
- ModleMap
- Modle
乱码问题
过滤器解决乱码:写一个过滤器chain.doFilter 实现Filter接口重写三个方法
重点讲解
在web.xml中SpringMVC的过滤器
<!--乱码问题:SpringMVC过滤器解决-->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>