一、Spring MVC的介绍
1.servlet的缺点
接收参数:一个servlet只能接收一个请求
(springMVC就是对servlet的优化升级)
2.MVC设计模式的介绍
M(model):模型层
数据模型:pojo
业务模型:service、mapper
v(view):视图层
jsp或html,负责和用户交互
c(controller):控制层
servlet和controller负责接受请求和跳转
调用关系!v---->c---->m
mvc和三层架构的关系:都是把代码进行分层,且三层架构分层时没有页面参与
3.什么是springMVC?
springmvc是spring框架的一个模块,是基于mvc设计模式的web框架,本质上相当于servlet
二、springMVC的入门案例
1.pom.xml(添加依赖)
spring-context(spring的ioc)
spring-webmvc(spring的mvc)
servlet-api(servlet依赖)
jsp-api(jsp依赖)
2.index.jsp
<a ="/hello">hello</ a>
3.controler
@Controller //ioc
public class HelloController{
//Map<"/hello", hello()>
@RequestMapping("/hello")
public ModelAndView hello(){
ModelAndView mv = new ModelAndView();
//request.setAttribute("msg", "师姐你好");
mv.addObject("msg", "师姐你好");
mv.setViewName("success");
return;
}
}
4.spring.xml
1)配置springmvc要扫描的包
<context:component-scan base-package="com.by.controller"></context:component-scan>
2)配置视图解析器
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--jsp的目录-->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!--jsp的扩展名-->
<property name="suffix" value=".jsp"></property>
</bean>
3)开启spingmvc注解支持
<!--
开启springmvc的注解:自动注册HandlerMapping与HandlerAdapter两个bean
HandlerMapping:根据请求url从Map获得Method对象->hello()
HandlerAdapter:调用Method对象->hello()
-->
<mvc:annotation-driven></mvc:annotation-driven>
5.web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<!--DispatcherServlet:①负责接受请求 ②负责调用HandlerMapping和HandlerAdapter-->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--tomcat启动时就加载DispatcherServlet,DispatcherServlet就会加载springmvc.xml-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--/:只能拦截路径,能拦截路径和页面-->
<url-pattern>/</url-pattern>
</servlet-mapping>
三、springMVC的核心组件
DispatchServlet(前端控制器):接受请求,调用其他组件
HandlerMapping(处理器映射器):查找method
HandlerAdapter(处理器适配器):调用method
ViewResolver(视图解析器):解析jsp的具体路径
View(视图渲染):把数据填充到request
四、RequestMapping注解
1.value属性:设置url 窄化路径
<a href="/一级路径/二级路径">
@RequestMapping("/一级路径")
public class AccountController{
@RequestMapping("/二级路径") //Map<"/一级路径/二级路径", findAccount()>
public ModelAndView findAccount(){
......
}
}
2.method属性(请求方式)
- @RequestMapping(value=“/请求路径”, method=RequestMethod.Get|Post|Delete|Put)
- @GetMapping(“/请求路径”)
- @PostMapping(“/请求路径”)
- @DeleteMapping(“/请求路径”)
- @PutMapping(“/请求路径”)
五、controller方法的返回值
1.返回ModelAndView
public ModelAndView findAccount(){
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "师姐你好");
mv.setViewName("success");
return mv;
}
2.返回字符串
2.1 返回视图名称
public String findAccount(Model model){
//request.setAttribure("msg", "师姐你好");
model.addAttribute("msg", "师姐你好");
return "success";
}
2.2 重定向(①两次请求 ②数据丢失)
//response.setStatus(302); //在响应头中添加302状态码,告诉浏览器需要进行重定向
//response.setHeader("Location", "/account/findAccount4");//在响应头中添加Location,指定重定向的位置
//response.sendRedirect("/account/findAccount4");
return "redirect:/account/findAccount4";
2.3 请求转发(①一次请求 ②数据不丢失)
//request.getDispatch("/account/findAccount4").forward(request, response);
return "forward:/account/findAccount4";
六、接收参数
1. 基本类型(少量数据)
<a href="/account/findAccount?name=zs&age=18">
public String findAccount(String name, Integer age){
}
2.pojo类型(对象类型–>多数据量)
<form action="/account/findAccount" method="post">
账户名称:<input type="text" name="name"><br/>
账户金额:<input type="text" name="money"><br/>
<input type="submit" value="提 交">
</form>
public String findAccount(Account account){
}
3.restful(占位符类型)
<a href="/account/findAccount/zs/18">
@RequestMapping(/account/findAccount/{name}/{age}})
public String findAccount(@PathVariable String name, @PathVariable Integer age){
}
4.日期类型的参数
4.1 创建日期转换器
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String str) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
4.2配置日期转换器
<mvc:annotation-driven conversion-service="cs"></mvc:annotation-driven>
<!--配置转换器工厂-->
<bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.by.converter.DateConverter"></bean>
</set>
</property>
</bean>
5. json数据
参数:'{"id":1,"name":"张二狗","money":999.0}'
接收json和返回json:
@ResponseBody
public AjaxResult findAccount(@RequestBody Account account){
}
@ResponseBody
public AjaxResult findAccount(@RequestBody Map map){
}
@ResponseBody
public Map findAccount(@RequestBody Map map){
}
注: @ResponseBody把数据传回json | @RequestBody拿到json里的数据
@RequestBody:json—>pojo
@ResponseBody:pojo—>json
结论:使用次数多则用pojo,使用次数少用Map
6. 中文乱码
6.1post
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern> / *</url-pattern>
</filter-mapping>
6.2 get
new String(str.getBytes("ISO-8859-1"), "UTF-8")
7. servlet API接收参数
public String findAccount13(HttpServletRequest request) throws Exception {
String name = request.getParameter("name");
}
七、数据传递
1. ModelAndView
public ModelAndView findAccount14() throws Exception {
ModelAndView mv = new ModelAndView();
mv.addObject("msg", "师姐你好");
mv.setViewName("success");
return mv;
}
2.Model
public String findAccount15(Model model) throws Exception {
model.addAttribute("msg", "师姐你好");
return "success";
}
3. Servlet API
public String findAccount16(HttpServletRequest request) throws Exception {
request.setAttribute("msg", "师姐你好");
return "success";
}