什么是SpringMVC |
一、SpringMVC的概述
Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。
MVC 设计概述:
早期的 MVC 模型Servlet + JSP + Java Bean 如图所示:
首先用户的请求会到达 Servlet,然后根据请求调用相应的 Java Bean,并把所有的显示结果交给 JSP 去完成,这样的模式我们就称为 MVC 模式。
- M 代表 模型(Model)
模型是什么呢? 模型就是数据,就是 dao,bean - V 代表 视图(View)
视图是什么呢? 就是网页, JSP,用来展示模型中的数据 - C 代表 控制器(controller)
控制器是什么? 控制器的作用就是把不同的数据(Model),显示在不同的视图(View)上,Servlet 扮演的就是这样的角色。
Spring MVC架构:
1、 用户发送请求至前端控制器DispatcherServlet,前端控制器收到请求后自己不进行处理,而是调用处理器映射器。
2、
DispatcherServlet收到请求后调用HandlerMapping处理器映射器。HandlerMapping将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、多个HandlerInterceptor拦截器)对象。3、
处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。4、 DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、 执行处理器(Controller,也叫后端控制器)。返回执行结果,封装在ModelAndView中
6、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器,
ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术;7、 ViewReslover解析后返回具体View
8、
DispatcherServlet对View进行渲染视图(即将对象模型的数据填充至视图中)。此处的Model实际是一个Map数据结构,因此很容易支持其他视图技术;9、 DispatcherServlet将结果响应给用户
回到顶部 |
Spring MVC【入门】 |
二、Spring MVC【入门】
第一步:在 IDEA 中使用maven新建 Spring MVC 项目
注意:不了解maven的点击这里查看
并且取名为 【hello】,点击【Finish】:
项目成功,项目结构:
注意:创建成功的项目目录结构所有缺失,我们需要手动创建完成。
第二步:pom.xml文件
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- servlet & jsp &jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--mysql驱动包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- 加入springmvc依赖包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.6.RELEASE</version>
</dependency>
</dependencies>
<build>
<resources>
<!-- 这个配置时告诉maven在做资源拷贝的时候(拷贝到target目录下)把src/main/java的properties和xml文件也都拷贝过去 -->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<!-- 将项目中的resources目录下的配置文件拷贝到taget目录下 如果不添加此节点resources目录下的配置文件都会被漏掉。-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
第三步:修改 web.xml
注意:idea默认web.xml头文件不支持el表达式,需改成下面这个头文件。
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--字符集处理-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<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>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--拦截所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
自此请求已交给Spring Web MVC框架处理,因此我们需要配置Spring的配置文件,默认DispatcherServlet会加载WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml配置文件。但也可以直接通过来指定配置文件
第四步:配置文件springmvc.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 静态资源映射 -->
<mvc:resources mapping="/js/**" location="/WEB-INF/js/" />
<mvc:resources mapping="/css/**" location="/WEB-INF/css/" />
<mvc:resources mapping="/fonts/**" location="/WEB-INF/fonts/" />
<mvc:resources mapping="/plugins/**" location="/WEB-INF/plugins/" />
<mvc:resources mapping="images/**" location="/WEB-INF/images/" />
<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--prefix和suffix:查找视图页面的前缀和后缀,比如传进来的逻辑视图名为hello,则该该jsp视图页面应该存放在“WEB-INF/hello.jsp”-->
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
第五步:简单Demo例子
1.实现控制器
//处理器必须实现Controller接口
public class UserController implements Controller {
public ModelAndView handleRequest(HttpServletRequest arg0, HttpServletResponse arg1) throws Exception {
ModelAndView mv = new ModelAndView();
//添加模型数据 可以是任意的POJO对象
mv.addObject("message", "Hello World!");
//设置逻辑视图名,视图解析器会根据该名字解析到具体的视图页面
mv.setViewName("hello");
return mv;
}
}
2.将处理器添加到springmvc.xml配置文件中
<bean name="/user" class="com.beixi.controller.UserController"></bean>
3.编写hello.jsp
<body>
<!--${message}:表示显示由UserController处理器传过来的模型数据。-->
${message}
</body>
4.进行访问 http://localhost:8080/user
回到顶部 |
Spring MVC注解式开发 |
三、Spring MVC注解式开发
简单的demo例子实现
1.在springmvc.xml配置文件中开启注解式驱动
<!--开启注解驱动-->
<context:component-scan base-package="com.beixi.*" />
<mvc:annotation-driven />
2.实现控制器
@Controller
@RequestMapping("/hello")//根路径
public class HelloController {
@RequestMapping(value="/index", method = {RequestMethod.GET})//子路径
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "Hello World!");
modelAndView.setViewName("index");
return modelAndView;
}
}
3.jsp页面
<body>
index.jsp
${message}
</body>
4.访问 : http://localhost:8080/hello/index
回到顶部 |
数据绑定 |
四、数据绑定
1.使用同名匹配规则
- login.jsp
<body>
<form action="/hello/param" role="form">
用户名:<input type="text" name="userName"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="提 交">
</form>
</body>
- 后台控制器方法
@RequestMapping("/param")
public ModelAndView getParam(String userName,String password) {
System.out.println(userName);
System.out.println(password);
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello World!");
mv.setViewName("hello");
return mv;
}
@RequestParam 注解细节:
该注解有三个变量:value、required、defaultvalue
value :指定 name 属性的名称是什么,value 属性都可以默认不写
required :是否必须要有该参数,可以设置为【true】或者【false】
defaultvalue :设置默认值
2.使用实体类模型传参
- User 模型
public class User {
String userName;
String password;
/* getter and setter */
}
- 后台控制器
@RequestMapping("/param")
public ModelAndView getParam(User user) {
System.out.println(user.getUserName());
System.out.println(user.getPassword());
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello World!");
mv.setViewName("hello");
return mv;
}
回到顶部 |
客户端跳转 |
五、客户端跳转
前面的所有 跳转都是服务端的默认转发,也就是 request.getRequestDispatcher(“地址”).forward(request, response);
@RequestMapping(value="/index", method = {RequestMethod.GET})
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", "Hello World!");
modelAndView.setViewName("index");//默认转发
return modelAndView;
}
@RequestMapping("/param")
public ModelAndView getParam(User user) {
System.out.println(user.getUserName());
System.out.println(user.getPassword());
ModelAndView mv = new ModelAndView();
mv.addObject("message", "Hello World!");
mv.setViewName("redirect:/hello/index");//重定向
return mv;
}
我们使用 redirect:/hello/index 是重定向。
也可以这样用:
@RequestMapping(value="/index", method = {RequestMethod.GET})
public String index(){
return "index";
}
@RequestMapping("/param")
public String getParam(User user) {
System.out.println(user.getUserName());
System.out.println(user.getPassword());
ModelAndView mv = new ModelAndView();
return "redirect:/hello/index";
}
从login.jsp跳转到/hello/param重定向到/hello/index地址。
回到顶部 |
AJAX&JSON |
六、AJAX&JSON
1.在pom.xml中配置json所需要的jar包
<!--JSON-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.4</version>
</dependency>
2.index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<h2>Hello World!</h2>
<input type="text" name="userName" id="userName">
<input type="text" name="password" id="password">
<input type="button" id="sub" value="Submit" />
<script type="text/javascript">
$().ready(
function() {
$("#sub").click(function(){
var dataJson = {
userName:$("#userName").val(),
password:$("#password").val()
};
$.ajax({
url:"/hello/json",
type:"post",
contentType:"application/json",//以json字符串形式传输
data:JSON.stringify(dataJson),//将json对象序列化成字符串,因为@ResponseBody徐亚接收字符串对象
dataType:"json",
success:function(data){//data为后端返回的json
alert(data.userName)
}
});
});
});
</script>
</body>
</html>
3.后台控制器
@RequestMapping("/json")
@ResponseBody /*数据载体*/ /* @RequestBod将ajax发出的请求写入 User 对象中*/
public User login(@RequestBody User user, HttpServletResponse response) {
System.out.println(""+user.getUserName());
return user;
}
注意:实体类属性字段一定和前端传递的属性名一致。
- @ResponseBody:
@Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文(ResponseBody)中,一般在异步获取数据时使用,通常是在使用 @RequestMapping 后,返回值通常解析为跳转路径,加上 @Responsebody 后返回结果不会被解析为跳转路径,而是直接写入HTTP 响应正文中。 - @RequestBody:
@RequestBody 注解则是将 HTTP 请求正文插入方法中,使用适合的 HttpMessageConverter 将请求体写入某个对象。
回到顶部 |
RESTful风格 |
七、RESTful风格
1.RESTful:中文释义为”表现层状态转换“,它不是一种标准,而是一种设计风格。它的主要作用是充分并正确利用HTTP协议的特性,规范资源获取的URI路径。通俗的讲,RESTful风格的设计允许将参数通过URL拼接传到服务端,目的是让URL看起来更简洁实用。并且对于不同的操作,要指定不同的HTTP方法(POST/GET/PUT/DELETE)。
- Restful : 表征状态状态转移。
传统 url : http://localhost:8080/usersys/delete?id=12
Restful 风格url : http://localhost:8080/usersys/12/delete;
Restful 风格的好处:数据更安全,简洁,效率更高,传递的数据更多。
3. Restful 使用
@RequestMapping("/test/{a}/{b}")
public String restfulTest(@PathVariable int a ,@PathVariable int b){
int sum=a+b;
System.out.println(""+sum);
return "hello";
}
@PathVariable注解,让方法参数的值对应绑定到一个URI模板变量上。
访问路径:http://localhost:8080/hello/test/2/3
RESTful风格Mapping请求常用的有以下几种👇 (一般在Spring Boot中使用)
@GetMapping 查询
@PostMapping 新增
@PutMapping 跟新
@DeleteMapping 删除