Spring MVC
简介 +运行
1. Spring Web MVCSpring Web MVC是基于Servlet API构建的原始Web框架,并且从一开始就已包含在Spring框架中。正式名称“ Spring Web MVC”来自其源模块(spring-webmvc)的名称,但它通常被称为“ Spring MVC”。ssm : mybatis + Spring + SpringMVC MVC 三层架构:JavaSE:JavaWeb:框架:MVC : 模型(dao service) 视图(jsp) 控制器(Servlet) 是一种软件设计规范是将业务逻辑 , 数据访问 , 显示 分离的方法来组织代码MVC 不是一种设计模式 MVC 是一种架构模式;前端 数据传输 实体类
运行原理图
流程图
实线由SpringMVC 实现 虚线由开发者实现
简单分析流程
1.DispatcherServlet 表示前置控制器 是整个SPringMVC 的控制中心.用户发出请求,DispatcherServlet接受请求并拦截请求.
假设我们的请求url为:http//localhost:8080/SpringMVC/hello
如上url 拆分成三部分
http//localhost:8080 服务其域名
SpringMVC部署在服务其上的web站点
hello表示控制器
通过分析,若URL表示为:请求位于服务器localhost:8080的SPringMVC站点的hello控制器
制苦。
2. HandlerMapping为处理器映射。DispatcherServlat调用
HandlerMapping, HandlerMapping根据请求url查找Handler.
3. HandlerExecution表示具体的Handler,其主要作用是根据ur|查找控制器,如. 上url被查找控制器
为: hello.
4. HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。
5. HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler。
6. Handler让目休的Controller执行。
7. Controller将具体的执行信息返回给HandlerAda pter,如ModelAndView.
8. HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet.
9. DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图
10.视图解析器将解析的逻辑视图名传给DispatcherServlet.
Servlet
maven 依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
编码格式
//解决数据传递造成的乱码
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
resp.setCharacterEncoding("utf-8");
Conterller 控制器
mvc 三大配件
处理映射器 处理适配器 视图解析器
1.配置web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:[servlet].xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- / 匹配所有请求 : 不包括(jsp)-->
<!-- /* 匹配所有的请求 : 包括jsp-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.配置Spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--处理器映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--处理器适配-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--视图解析器:DIspcherServlet给他的ModelView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<!--hello-->
<bean id="/hello" class="sl.contorller.HelloContorller"/>
</beans>
3.创建 Contorller
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloContorller implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//MOdeandView 模式和视图
ModelAndView mv = new ModelAndView();
//f封装对象 ,放在ModelAndView 中 MOedl
mv.addObject("msg","HelloSpringMVC");
//f封装需要跳转的视图,放在ModelAndView 中
mv.setViewName("hello");
return mv;
}
}
4.注意点
如果项目 运行失败时
检查 项目结构 是否有 lib 没有则新建 在把 jar包存入lib包下
检索配置文件
(.xml .properties)
<!---过滤文件-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resource</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
注解开发MVC
1.配置web.xml
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--关联一个springmvc的配置文件:[servlet].xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--启动级别1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- / 匹配所有请求 : 不包括(jsp)-->
<!-- /* 匹配所有的请求 : 包括jsp-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2.配置spring
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--自动扫描包,让指定包下的注解生效 ,用IOC容器管理 -->
<context:component-scan base-package="com.sl.contorller"/>
<!--让Spring 不处理静态资源 .css .js ...-->
<mvc:default-servlet-handler />
<!--
支持mvc注解驱动
在spring中- -般 采用@Reques tMapping注解来完成映射关系
要想使@RequestMapping注解生效
必须向上下文中注册Defaul tAnnotationHandlerMapping
和一- TAnnotationMe thodHandlerAdapter实例
这两个实例分别在类级别和方法级别处理。
而jannotation-driven配置帮助我们自动完成上述两个实例的注入。
-->
<mvc:annotation-driven />
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3.使用注解
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/*代表 这类会被Spring 接管,被这个注解的类,重 的所有方法 如果返回的时String ,
并且 有具体页面可以选择,那么就ibei视图解析器 解析:
*/
@Controller
public class HelloContorller {
@RequestMapping
public String hello(Model model){
//封装数据
model.addAttribute("msg","HelloSpringMVCAnnotation");
//视图的名称
return "hello"; //会被视图解析器处理
}
}
实现接口 MVC开发
(不建议使用)
1.实现contorller
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//实现类Contorller 接口的类 ,说明这就是一个控制器
public class HelloContorller2 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//创建视图模型
ModelAndView mv = new ModelAndView();
//传递数据
mv.addObject("msg","holloMVC");
//跳转视图
mv.setViewName("hello");
return mv;
}
}
2. web配置同上
3.spring配置
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<!--前缀-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--后缀-->
<property name="suffix" value=".jsp"/>
</bean>
<bean id="/hello" class="com.sl.contorller.HelloContorller2"/>
</beans>
注解
@Component 组件
@Service service
@Contorller 控制器 contorller
@Repository dao
@ResponseBody 请求不会走视图解析器,直接返回字符串
@RestController 类下的所有方法请求不会走视图解析器,只会返回字符串
Restful
RestFul风格
概念
Restful就是一个资 源定位及资源操作的风格。不是标准也个是协议,只是一种风格。 基十这个风,
格设计的软件可以更简洁,更有层次,更易于实现级仔等机制。
功能
●资源:与联网所有的宇物都可以被抽象为资源
,资源操作:使用POST、 DELETE、 PUT、GET,使用不同乃法刈资源进行操作。
■分别对应添加、删除。修改、查询。.
传统方式操作资源:通过不同的参数来实现不同的效果!方法单一, post 和get
, http://127.0.0.1/item/queryltem.action?id=1 查询,GET
, http://127.0.0.1/item/saveltem.action新增POST
。htt://127.0.0.1/item/updateltem.action更新,POST
●http://127.0.0.1/item/deleteltem.action?id=1 删除. GET或POST
使用RESTful操作资源:可以通过不同的请求方 式来实现不同的效果!如下:请求地址一样,但
是功能可以不同!
●http://127.0.0.1/item/1查询,GET
, http://127.0.0.1/item新增,POST
, http://127.0.0.1/item中新,PUT
●http://127.0.0.1/item/1 叫除,DELETE
@PathVariable
注解传递参数
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RestfulContorller {
//Restful 风格
//传值add/1/2
// @RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
//等同于 @getMapping;
@GetMapping(value = "/add/{a}/{b}")
public String test1(int a, int b , Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
}
@RequestMapping ();
@RequestMapping (value=””,method =RequestMethod.GET);
value : url
请求的url
value ="/add/{a}/{b}"
method :
// 可以限定参数传递的方式
RequestMethod.GET 等同于@GetMapping
RequestMethod.DELETE = @DelectMapping
RequestMethod.PSOT = @PostMapping
RequestMethod.PUT = @PutMapping
RequestMethod.PATCH = @PatchMapping
数据处理
@GetMapping("/t1")
public String teest1(@RequestParam("username") String name, Model model){
//接收前端参数
System.out.println("接受的前端参数为"+name);
//将返回的结果传递为给前端 MOdel
model.addAttribute("msg",name);
//视图跳转
return "hello";
}
//前端接受的是一个对象
/*
1.按收站带用户传递的参教。刘断参教的名字。但设古字直按在力法上可以直按使用
2.假设传递的是一- 个对象User.匹配User对象中的字段名:如:果名字一至则OK, 否则。四配不到
*/
@GetMapping("/t2")
public String test2(User user){
System.out.println(user);
return "hello";
}
@GetMapping("/3")
public String test3(Model model){
return "hello";
}
乱码问题
在web.xml中配置
<!--配置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>
JSON
什么是JSON?
●JSON(JavaScript Object Notation. JS对象标记)是种轻品级的数据交换格式。月前使用特别
广泛。
木繁制
●采用完全独立于编程语言的文本格式来行储和表示数据。
●简洁和活晰的层次结构使得JSON成为哩想的数据交换语言。
●易于人阅读和编写,同时也易于机器解析和生成,并有效地拢升网络传输效率。
在JavaScript语言中,一切都是对象。因此,任何JavaScript支持的类型都可以通过JSON来
表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:
.对象表示为健估对,数据由迎号分隔
●花括号保存对象
■方括号保存数组.
.Q
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,
键/值对组合中的键名写在前面并用双引号“包裹,使用冒号:分隔,然后紧接着值:
很多人搞不清楚JSON和JavaScript对象的关系,甚至连谁是谁都不清楚。其实,可以这么理
解:
● JSON足JavaScript对象的字符申表示法,它使用义本表示一个JS对象的信息,本质是一个字
符串。
var ohj = {a: 'He11o"。b: 'world'l; //这是一个时象,计意犍名也是可以使用引号包裹的
var json = '{"a"; "Hello", "b”: "world"}'; //这匙一个JSOH 宁符串,本项是一个字符中
JSON和JavaScript对象互转
●要实现从JSON字符串转换为JavaScript对象。使用JSON.parse()方法:
war obj - IsoN,parse('{"a": "e11o", "b": "World"]');
//结果是{a: 'Hello', b: "Norld'}
●要实现从JavaScript对象转换为JSON字符串,使用JSON.stringify0方法:
var json = JsoN.stringify({a: "He1lo'. b: 'world'});
/1结果是'{"a": "Hello", “b”: "World"}'
json 乱码配置
<!--JSON乱码配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"/>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
Jackson
工具类
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtil {
public static String getJson(Object o,String dateFaomat){
ObjectMapper mapper = new ObjectMapper();
//不使用 时间戳的方式 ,用 ObjectMapper的方式
mapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,false);
//自定义日期函数
SimpleDateFormat sdf = new SimpleDateFormat(dateFaomat);
mapper.setDateFormat(sdf);
String str = null;
try {
str = mapper.writeValueAsString(o);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return str;
}
public static String getJson(Object o){
return getJson(o,"yyyy-MM-DD hh:mm:ss");
}
}
jackson maven
<dependency> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
FastJson
FastJson maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
FastJson 三个主要的类
JSONObject代表json对象
JSONObject实现了Map接口,猜想JSONObject底层操作是由Map实现的。
JSONObject对应json对象,通过各种形式的get0方法可以获取json对象中的数据,也可利
用诸如size(),isEmpty(0等方法获取“键:值"对的个数和判断是否为空。其本质是通过实现
Map接口并调用接口中的方法完成的。
[JSONArray代表json刈象数组]
内部是有List援I 1中的方法來完成操作的。
[JSON代表JSONObject和JSONArray的转化]
JSON类源码分析与使用
●仔细观察这些方法,主要是实现json对象,json对象数组, javabean对象, json字符串之间
的相互转化。
实例
//*******Java对象转ISON字 符******
String str1 = JSON.toJSONString(userList);
string str2 = JSON.toJsonString( user1) ;
//("n*章遍JSON字符串转Java对 象****);
User jp_ user1=JSON.porseobject(str2,User.class); ,
//("*** Java对象转J50N对象***);
JSONobject json0bject1 = (JSONObject) JSON.toJSOW(user2);
//("****. JSON对象转Java对 象*****):
User to_java_user = JSON.toJavaObject(json0bject1, User. class);
AJAX
html 山寨 异步
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe页面ajax</title>
</head>
<body>
<div>
<h3>请输入地址</h3>
<p>
<input type="text" id="url" value="">
<input type="button" value="提交" onclick="go()">
</p>
</div>
<div>
<iframe id="iframe1" src="" style="width: 100%;height: 500px" >
</iframe>
</div>
</body>
<script type="text/javascript">
function go() {
var url = document.getElementById("url").value;
document.getElementById("iframe1").src=url;
}
</script>
</html>
java script 正版 Ajax
jQuery .ajax(...)
部分参数:
url:请求地址.
type:请求方式,GET、 POST (1. 9.0之后用method)
headers:请求头
data:要发送的数据
contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form- urlencod
async:是否异步
timeout:设置请求超时时间(毫秒)
beforeSend:发送请求前执行的函数(全局)
complete:完成之后执行的回调函数(全局)
success:成功之后执行的回调函数(全局)
error:失败之后执行的回调函数(全局)
accepts:通过请求头发送给服务器,告诉服务器当前客户端课接受的数据类型
dataType:将服务器端返回的数据转换成指定类型.
"xml": 将服务器端返回的内容转换成xml格式
"text":将服务器端返回的内容转换成普通文本格式
"html":将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签
"script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格i
"json":将服务器端返回的内容转换成相应的JavaScript对象
"jsonp": JSONP 格式使用JSONP 形式调用函数时,如"myurl?callback=?" jQuery将自动
文件上传 ,下载
前端设置
multipart/form-data 设置文件上传
<form action="${pageContext.request.contextPath}/file/upload" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" name="upload"/>
</form>
springmvc 配置
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--请求的编码格式,-->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件大小的上限,单位为字节(10485760=10M)-->
<property name="maxInMemorySize" value="10485760"/>
<property name="maxUploadSize" value="40960"/>
</bean>
controller
上传文件
@Controller
@RequestMapping("/file")
public class fileController {
//上传文件 @RequestParam("file")将 name = "file" 的文件封装成 CommonsMultipartFile 对象
@RequestMapping("/upload")
public String upload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名字 file.getOriginalFilename();
String uploadFileName = file.getOriginalFilename();
//如果文件名为空,直接返回到首页
if ("".equals(uploadFileName)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名为"+uploadFileName);
//上传路径保存设置 UUID保证文件上传唯一
String path = request.getServletContext().getRealPath("/upload");
//如果路劲不存在 那么创建一个
File realPath = new File(path);
if (!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件地值"+realPath);
InputStream is = file.getInputStream(); //文件出入流
OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); // 文件输出流
//读写输出
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
/*
*采用 file.Transto ,来保存上传的文件
*/
@RequestMapping("/upload2")
public String upload2(@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 的方法直接写文件
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:/index.jsp";
}
}
