SpringMVC学习笔记
1、MVC概念
- 模型 Model(JavaBean、DAO、Service)
- 视图 View(JSP)
- 控制器 Controller(Servlet)
2、Spring MVC 执行原理
- DispatcherServlet 表示前置控制器,是整个 SpringMVC 的控制中心。用户发出请求,DispatcherServlet 接收请求并拦截请求。
- 我们假设请求的url为 : http://localhost:8080/SpringMVC/hello
- 如上url拆分成三部分:
- http://localhost:8080 服务器域名
- SpringMVC 部署在服务器上的web站点(项目名)
- hello 表示控制器
- 通过分析,如上url表示为:请求位于服务器 localhost:8080 上的 SpringMVC 站点的 hello 控制器。
- HandlerMapping 为处理器映射。DispatcherServlet 调用 HandlerMapping;HandlerMapping 根据请求 url 查找 Handler。
- HandlerExecution 表示具体的 Handler ,其主要作用是根据url查找控制器,如上 url 被查找控制器为: hello。
- HandlerExecution 将解析后的信息传递给 DispatcherServlet,如解析控制器映射等。
- HandlerAdapter 表示处理器适配器,其按照特定的规则去执行 Handler。
- Handler 让具体的 Controller 执行。
- Controller 将具体的执行信息返回给 HandlerAdapter,如 ModelAndView。
- HandlerAdapter 将视图逻辑名或模型传递给 DispatcherServlet 。
- DispatcherServlet 调用视图解析器(ViewResolver)来解析 HandlerAdapter 传递的逻辑视图名。
- 视图解析器将解析的逻辑视图名传给 DispatcherServlet 。
- DispatcherServlet 根据视图解析器解析的视图结果,调用具体的视图。
- 最终视图呈现给用户。
3、创建 Spring MVC 项目
org.springframework
spring-webmvc
5.3.14
<?xml version="1.0" encoding="UTF-8"?>
springmvc servlet-name>
org.springframework.web.servlet.DispatcherServlet \
contextConfigLocation
classpath:springmvc-servlet.xml
1
springmvc
/
3.1 xml配置版(用于理解原理,一般不使用)
<?xml version="1.0" encoding="UTF-8"?>
3.2 注解版(一般用这个)
步骤如下:
- 新建一个 web 项目
- 导入相关 jar 包
- 编写 web.xml ,注册 DispatcherServlet
- 编写 SpringMVC 配置文件
- 接下来就是去创建对应的控制类,Controller
- 最后完善前端视图和 Controller 之间的对应
- 测试运行调试
使用 SpringMVC 必须配置的三大件:
处理器映射器、处理器适配器、视图解析器通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,而省去了大段的 xml 配置
<?xml version="1.0" encoding="UTF-8"?>
@Controller
@RequestMapping("/hello")
public class Hellocontroller {
// localhost:8080/hello/h1
@RequestMapping("/h1")
public String hello(Model model) {
//封装数据
model.addAttribute( s: "msg", o: "Hello,SpringMVCAnnotation! ");
return "hello"; //会被视图解析器处理,直接跳转到视图hello.jsp;
}
}
<%@page contentType="text/html;charset=UTF-8" language="java" %>
Title
${msg}
4、RESTful 风格
概念
- Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。
- 基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
功能
- 资源:互联网所有的事物都可以被抽象为资源.
- 资源操作:使用 POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
- 分别对应 添加、删除、修改、查询。
传统方式操作资源:通过不同的参数来实现不同的效果!方法单一,Post和 Get
http://127.0.0.1/item/queryltem.action?id=1查询,GEThttp://127.0.0.1/item/saveltem.action新增,POSThttp://127.0.0.1/item/updateltem.action更新,POSThttp://127.0.0.1/item/deleteltem.action?id=1删除,GET或POST
使用RESTful操作资源:可以通过不同的请求方式来实现不同的效果!请求地址一样,但是功能可以不同!
http://127.0.0.1/item/1查询,GEThttp://127.0.0.1/item新增,POSThttp://127.0.0.1/item更新,PUThttp://127.0.0.1/item/1删除,DELETE
原来的风格:
@Controller
public class RestFulController {
//原来的:http://localhost:8080/add?a=1&b=2
@RequestMapping("/add")
public String test1(int a,int b,Model model){
int res = a + b;
model.addAttribute( "msg" , "结果为" + res );
return "test";
}
}
RESTful风格:
@Controller
public class RestFulController {
//RestFul:http://localhost:8080]add/a/b
//示例请求:http://localhost:8080]add/1/2
@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";
}
}
5、@RequestMapping 方法级别的注解变体
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @PatchMapping
- 使用以上组合注解,可对请求的方法做出限制(使用哪种方法才能执行此段代码)
示例:
@Controller
public class RestFulController {
//@RequestMapping(path = "/add/{a}/{b}", method = RequestMethod.GET) 等价于
@GetMapping("/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute( "msg" , "结果为" + res );
return "test";
}
}
6、转发与重定向
通过SpringMVC来实现转发和重定向 — 有视图解析器
重定向,不需要视图解析器,本质就是重新请求一个新地方嘛,所以注意路径问题。
可以重定向到另外一个请求实现。
- 在重定向路径名前添加 redirect:
@Controller
public class ResultspringMVC2 {
@RequestMapping( "/rsm2/t1" )
public String test1() {
//转发
return "test"; //转发时,存在视图解析器的话,直接写视图名,无需后缀
}
@RequestMapping( "/rsm2/t2" )
public String test2() {
//重定向
return "redirect:/index.jsp" ; //重定向时,写好路径名
// return "redirect:hello.do" ; // hello.do为另一个请求
}
}
7、接收请求参数
7.1 参数为基本数据
重点:在方法参数前添加注解 @RequestParam
提交数据:http://localhost:8080/hello?username=wjd
处理方法︰
//@RequestParam( "username" ) : username提交的域的名称
@RequestMapping( "/hello" )
public String hello(@RequestParam( "username" ) String name) {
System.out.println( name ) ;
return "hello" ;
}
后台输出:wjd
7.2 参数为对象
提交数据:http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
处理方法︰
@RequestMapping( "/user" )
public String user ( User user ) {
System.out.println(user);
return "hello" ;
}
后台输出:User { id=1,name= 'kuangshen', age=15 }
说明:如果使用对象的话,前端传递的参数名和对象名必须一致,否则就是null。
8、数据回显
8.1 Model
@RequestMapping( "/ct2/hello" )
public String hello(@RequestParam( "username" ) String name, Model model){
//封装要显示到视图中的数据
//相当于req.setAttribute( "name", name);
model.addAttribute( "msg", name ) ;
System.out.println(name);
return "test";
}
8.2 ModelMap
@RequestMapping( "/ct2/hello" )
public String hello(ModelMap model){
model.addAttribute( "msg", name ) ;
return "test";
}
8.3 ModelAndView
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(){
//返回一个模型视图对象
ModelAndview mv = new ModelAndView();
mv.addObject ( "msg", "controllerTest1" );
mv.setViewName ( "test" );
return mv;
}
}
使用区别:
- Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于 Model 对象的操作和理解。
- ModelMap 继承了 LinkedHashMap ,除了实现了自身的一些方法,同样的继承 LinkedHashMap 的方法和特性。
- ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。
9、乱码问题
9.1 响应返回乱码
在 web.xml 中配置 Spring MVC 的乱码过滤器
encoding
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encoding
/*
-
上面这种过滤器,能够解决POST请求的乱码问题,对于GET请求,还是会乱码
-
实在不行用这种:
@RequestMapping(path = "/test", produces = "application/json; charset=utf-8")
9.2 JSON输出乱码
在 springmvc-servlet.xml 中配置 mvc:annotation-driven
10、常用注解
-
@Controller、@RequestMapping
@Controller public class TestController { @RequestMapping("/01") public String test() { return "已经进入了test方法"; } } -
@PathVariable(URL路径段作为参数)
@Controller public class RestFulController { @RequestMapping("/add/{a}/{b}") public String test1(@PathVariable String a, @PathVariable String b, Model model){ model.addAttribute( "msg" , "结果为" + a + b ); return "test"; } } -
@RequestParam(设置GET/POST请求参数名)
@RequestMapping( "/ct2/hello" ) public String hello(@RequestParam( "username" ) String name, Model model){ //封装要显示到视图中的数据 //相当于req.setAttribute( "name", name); model.addAttribute( "msg", name ) ; System.out.println(name); return "test"; } -
@ResponseBody
当某一方法String返回值不想经过视图解析器时,在方法名上方使用此注解
-
@RestController
当控制器中的所有方法均不想经过视图解析器时,使用此注解
@Controller public class TestController { @ResponseBody @RequestMapping("/01") public String test() { return "已经进入了test方法"; } } //等价于 @RestController public class TestController { @RequestMapping("/01") public String test() { return "已经进入了test方法"; } }
11、拦截器
在applicationContext.xml中添加配置
编写拦截器类
package config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
/*
return true; 执行下一个拦截器,放行
return false; 不执行下一个拦截器
*/
@Override
public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {
return HandlerInterceptor.super.preHandle( request, response, handler );
}
@Override
public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception {
HandlerInterceptor.super.postHandle( request, response, handler, modelAndView );
}
@Override
public void afterCompletion( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex ) throws Exception {
HandlerInterceptor.super.afterCompletion( request, response, handler, ex );
}
}
12、文件上传与下载
在applicationContext.xml中添加配置
编写文件控制器类
@RequestMapping( "/upload2" )
// @RequestParam("file")将 name=file 控件得到的文件封装成 CommonsMultipartFile 对象
// 批量上传 CommonsMultipartFile 则为数组即可
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpservletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath( "/upload" );
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipartFile的方法 transferTo() 直接写文件
file.transferTo(new File( realPath +"/"+ file.getOriginalFilename()));
return "redirect:/index.jsp";
}
13、SSM整合
13.1 依赖导入
junit
junit
4.12
mysql
mysql-connector-java
5.1.47
com.mchange
c3p0
0.9.5.5
javax.servlet
servlet-api
2.5
javax.servlet.jsp
jsp-api
2.2
javax.servlet
jstl
1.2
org.mybatis
mybatis
3.5.2
org.mybatis
mybatis-spring
2.0.2
org.springframework
spring-webmvc
5.1.9.RELEASE
org.springframework
spring-jdbc
5.1.9.RELEASE
13.2 静态资源导出问题
src/main/java
**/*.properties
**/*.xml
false
src/main/resources
**/*.properties
**/*.xml
false
13.3 各类配置文件
13.3.1 MyBatis配置文件
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
13.3.2 Spring配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
db.properties 必须加 jdbc. 这个前缀,不然报错
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8&useSSL=false
jdbc.username=root
jdbc.password=
spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
注意事项:
- 如果 Mapper.xml 与 Mapper.class 在同一个包下且同名,Spring 中 MapperScannerConfigurer 扫描 Mapper.class 的同时会自动扫描同名的 Mapper.xml 并装配到 Mapper.class 。
- 如果 Mapper.xml 与 Mapper.class 不在同一个包下或者不同名,就必须使用配置 mapperLocations 指定 mapper.xml 的位置。(如idea中 maven 默认不打包java文件夹下的xml文件,未在pom.xml中配置resource的情况下)
此时spring是通过识别mapper.xml中的
namespace的值来确定对应的Mapper.class的。
13.3.3 Spring MVC 配置文件
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>