提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、SpringMVC是什么?
1、基于 MVC 架构,功能分工明确。解决页面代码和后台代码的分离。
2、简单易用。SpringMVC 也是轻量级的,jar 很小。不依赖的特定的接口和类就可以开发一个注解的
SpringMVC 项目。
3、作 为 Spring 框 架 一 部 分 , 能 够 使 用Spring的IoC和AOP 。 方 便 整 合MyBatis,Hiberate,JPA等
其他框架。
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
二、SpringMVC
2.1 入门案例
1. 在web.xml文件中配置SpringMVC和Spring启动时需要的配置文件
<!-- 配置Spring,当项目运行时会查找这些配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置SpringMVC的中央控制器-->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 让SpringMVC读取你的配置文件,若不设置默认去WEB-INF下查找 -servlet 结尾的文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
2. SpringMVC 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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd ">
<context:component-scan base-package="com.mk.study.controller"/>
<!-- 开启SpringMVC注解驱动-->
<mvc:annotation-driven/>
<!-- 配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
3. 控制层
@Controller
public class TeamController {
@Autowired
private TeamService service;
@RequestMapping("/hello.do")
public ModelAndView add(){
System.out.println("TeamController --- add");
service.add();
ModelAndView modelAndView = new ModelAndView();
//给前端页面发送数据
modelAndView.addObject("teamName","张三");
// 经过InternalResourceViewResolver视图解析器转换成物理资源路径,变成/success.jsp
modelAndView.setViewName("success");
return modelAndView;
}
}
2.2 SpringMVC三大组件
1. HandlerMapping处理器映射器:建立地址与方法的映射。
HandlerMapping负责根据用户请求url找到Handler即(Controller)处理器,
springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
springmvc默认的映射处理器是BeanNameUrlHandlerMapping
2. HandlerAdapter处理器适配器:根据请求地址调用方法。
3. ViewResolver 视图解析器:处理ModelAndView数据和视图。
ViewResolver通过HandlerAdapter对处理器进行执行,
2.3 SpringMVC工作流程
2.4 url-pattern解析
1. 当我们在web.xml中配置了url-pattern的解析路径为 / 时,我们的静态资源也会被SpringMVC的中央调度器DispaterServlet解析,会出现静态资源找不到的问题,
2. 当我们把url-pattern 改成 *.do / *.action 时,只有我们的请求是 xxx.do/xxx.action时才会被中央调度器DispaterServlet解析,我们的静态资源就会默认的Servlet解析,静态资源就会被加载到浏览器,我用的服务器是Tomcat,所以默认的Servlet是DefaultServlet,
2.5 静态资源的处理
1. 当 url-pattern解析路径为/ 时,也想找到静态资源,那么我们在SpringMVC配置文件中,加入
<mvc:default-servlet-handler/> 中央调度器DispaterServlet就不会解析静态资源
2. 解决静态资源的第二种方式
<mvc:resources mapping="/images/**" location="/images/"/>
location:指location指定的目录不要拦截,直接请求
mapping:值在resources文件下的所有文件(**代表所有文件)
2.6 请求参数的接收
处理器方法可以包含以下四类参数,这些参数会在系统调用时由系统自动赋值.所以我们可以在方法内直接使用。以下是这四类参数: |
---|
HttpServletRequest |
HttpServletResponse |
HttpSession |
请求中所携带的请求参数 |
2.6.1 参数的接收1
1. 前台页面
<h1>提交参数1</h1>
<form action="/param/p1" method="post">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="submit">提交</button>
</form>
2. 控制器
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/p1")
public ModelAndView param1(Integer id,String name,String location){
System.out.println(id);
System.out.println(name);
System.out.println(location);
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
}
注意: 前端页面发送请求的name值 必须和控制器方法的形参值保持一致,否则获取不到值
2.6.2 使用对象接收参数
1. 前台页面
<h1>提交参数2,使用对象接收</h1>
<form action="/param/p1" method="post">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="submit">提交</button>
</form>
2. 对象
public class Team {
public int id;
private String name;
private String location;
public Team(int id, String name, String location) {
this.id = id;
this.name = name;
this.location = location;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
'}';
}
}
3. 控制器
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/p2")
public ModelAndView param2(Team team){
System.out.println(team);
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
}
注意:当前端传的值是一个Team对象,匹配前端传的值与Team的属性字段是否匹配,若匹配就会赋值,不匹配为null
2.6.3 请求参数与接收参数名称不一致
1. 前台页面
<h1>提交参数3,参数不一致</h1>
<form action="/param/p3" method="post">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="submit">提交</button>
</form>
2. 控制器
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/p3")
public ModelAndView param3(@RequestParam(value = "id",required = false) Integer teamId, String name, String location){
System.out.println(teamId);
System.out.println(name);
System.out.println(location);
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
}
注意: 当请求参数与接收参数不匹配时,使用@RequestParam(value="请求参数名称",,required = false)注解进行矫正
required :
true: 表示请求参数是必须的,若跟 @RequestParam的请求参数还不一致,报错400
false: 表示请求参数不是必须的,若跟 @RequestParam的请求参数还不一致,后台接收该参数为null
2.6.4 使用HttpServletRequest 获取参数
1. 前台页面
<h1>提交参数3,参数不一致</h1>
<form action="/param/p4" method="post">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="submit">提交</button>
</form>
2. 控制器
@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/p4")
public ModelAndView param4(HttpServletRequest request){
System.out.println(request.getParameter("id"));
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
}
注意:原生Servlet方式获取
2.6.5 使用URL发送参数如何获取
1. url带参
http://localhost:8080/p5/1001/zhangsan/beijing 当参数是这种参数时控制器如何获取参数
2. 控制器
@RequestMapping("/p5/{id}/{name}/{location}")
public ModelAndView param5(@PathVariable("id") Integer id,
@PathVariable("name") String name,
@PathVariable("location") String location){
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
2.6.6 如何接受日期参数
1. 前台页面
<h1>提交参数6,日期参数</h1>
<form action="/param/p6" method="post">
id:<input type="text" name="id"><br>
姓名:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
日期:<input type="text" name="createTime">
<button type="submit">提交</button>
</form>
2. bean对象
public class Team {
public int id;
private String name;
private String location;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date time;
public Team(int id, String name, String location, Date time) {
this.id = id;
this.name = name;
this.location = location;
this.time = time;
}
@Override
public String toString() {
return "Team{" +
"id=" + id +
", name='" + name + '\'' +
", location='" + location + '\'' +
", time=" + time +
'}';
}
}
3. 控制器
@RequestMapping("/p6")
public ModelAndView param6(Team team){
System.out.println(team);
ModelAndView modelAndView = new ModelAndView("success");
return modelAndView;
}
2.7 解决中文乱码
<!-- 配置中午乱码过滤器-->
<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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
2.8 Controller返回值
2.8.1 Controller返回值-ModelAndView
@RequestMapping(value = "/hello.do")
public ModelAndView add(){
System.out.println("TeamController --- add");
service.add();
ModelAndView modelAndView = new ModelAndView();
//给前端页面发送数据
modelAndView.addObject("teamName","张三");
// 经过InternalResourceViewResolver视图解析器转换成物理资源路径,变成/success.jsp
modelAndView.setViewName("success");
return modelAndView;
}
2.8.2 Controller返回值-String
@RequestMapping(value = "/str.do")
public String add2(HttpServletRequest request){
request.getParameter("要获取的参数");
//发送给页面的数据
request.setAttribute("key","value");
// 经过InternalResourceViewResolver视图解析器转换成物理资源路径,变成/success.jsp
return "success";
}
2.8.3 返回自定义类型数据/对象/json数据
1. 导入依赖
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
2. 在方法上加上 @ResponseBody 注解
3. 测试
@RequestMapping("/p7")
@ResponseBody
public Integer retType1(){
return 666;
}
@RequestMapping("/p8")
@ResponseBody
public Team retType2(){
Team team = new Team();
team.setId(1);
team.setName("张三");
team.setLocation("北京");
return team;
}
注意:返回对象类型 Integer Double List Map返回的不是地址,而是数据返回
2.8.4 返回给前台时间数据
1. 在bean实体类对象中日期属性上 加上 @JsonFormat(pattern = "yyyy-MM-dd")
private Date time; 即可
2. 返回给前台的数据就是 xxxx-xx-xx 而不是时间戳
2.9 异常处理
1. 使用异常处理器 注解 @ExceptionHandler(value ={异常类.class}) 接收处理异常
2. 控制器抛出异常
@RequestMapping("/e1/{id}/{name}")
public ModelAndView ex(@PathVariable("id") int id,@PathVariable("name") String name) throws TeamException {
if(id>100){
throw new TeamIdException("id值不能大于100");
}
if("test".equals(name)){
throw new TeamIdException("name不能为test");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("success");
return modelAndView;
}
3. 自定义方法接收处理异常
@ExceptionHandler(value ={TeamException.class,Exception.class})
public ModelAndView ex2(Exception ex){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",ex.getMessage());
if(ex instanceof TeamException){
modelAndView.setViewName("IdError");
}else{
modelAndView.setViewName("error");
}
return modelAndView;
}
2.9.1 定义 全局异常
1. 当我们的异常较多时,我们可以定义一个 全局异常
2. 配合 注解 @ControllerAdvice ,当有任何异常处理时,可以在全局异常类中定义处理异常的方法
//全局异常 必须使用 @ControllerAdvice
@ControllerAdvice
public class GlobalException {
@ExceptionHandler(value =TeamException.class)
public ModelAndView ex2(Exception ex){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg",ex.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
2.10 拦截器
拦截与放行请求
1. 自定义拦截器
public class MyInterceptor implements HandlerInterceptor {
//执行时间:控制器方法执行之前,在ModelAndView返回之前
//使用场景:登录验证...
//返回值 true:继续执行控制器方法,表示放行。
// false:不会执行控制器方法,表示拦截。
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
return true;
}
//执行时间:控制器方法执行之后,在ModelAndView返回之前,有机会修改返回值和跳转页面
//使用场景:日志记录,记录登录的ip 时间...
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");
}
//执行时间:控制器方法执行之后,在ModelAndView返回之后,不能修改返回值
//使用场景:全局资源的一些操作
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
}
}
2. 在SpringMVC配置文件中设置拦截路径
<mvc:interceptors>
<!-- 一个mvc:interceptor表示一个拦截器 ,可以配置多个拦截器-->
<mvc:interceptor>
<!-- 拦截路径-->
<mvc:mapping path="/**"/>
<!-- 当拦截路径后执行该拦截器-->
<bean class="com.mk.study.interceptor.MyInterceptor" id="myInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
3.
2.10.1 拦截器执行流程
2.11 RestFul风格
2.11.1 Rest概念
REST(英文:Representational State Transfer,简称REST,意思:表述性状态转换,描述了一个架构
样式的网络系统,比如web应用)。
它是一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件,它主要用于客
户端和服务端交互类的软件。基于这个风格设计的软件可以更简介,更有层次,更易于实现缓存等机
制。
它本身并没有什么使用性,其核心价值在于如何设计出符合REST风格的网络接口。
2.11.2 RestFul概念
REST指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是RESTful。
RESTful的特性:
资源(Resources):互联网所有的事物都可以被抽象为资源 。它可以是一段文本、一张图片、一首歌
曲、一种服务,总之就是一个具体的存在。可以用一个URI(统一资源定位符)指向它,每种资源对应
一个特性的URI。要获取这个资源,访问它的URI就可以,因此URI即为每一个资源的独一无二的识别
符。
表现层(Representation):把资源具体呈现出来的形式,叫做它的表现层(Representation)。比如,文
本可以用txt格式表现,也可以用HTML格式、XML格式、JSON格式表现,甚至可以采用二进制格式。
状态转换(State Transfer):每发出一个请求,就代表了客户端和服务器的一次交互过程。HTTP协议,
是一个无状态协议,即所有的状态都保存在服务器端。因此,如果客户端想要操作服务器,必须通过某
种手段,让服务器端发生“状态转换”(State Transfer)。而这种转换是建立在表现层之上的,所以就是“表
现层状态转换”。
具体来说就是HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。他们分别对应
四种基本操作:GET用来获取资源,POST用来新建资源,PUT用来更新资源,DELETE用来删除资源。
2.11.3 API设计
动词+宾语
RESTful 的核心思想就是客户端的用户发出的数据操作指令都是"动词 + 宾语"的结构。例如GET
/expresses 这个命令,GET是动词,/expresses 是宾语。
动词通常就是五种 HTTP 方法,对应 CRUD 操作。
GET:读取(Read)
POST:新建(Create)
PUT:更新(Update)
PATCH:更新(Update),通常是部分更新
DELETE:删除(Delete)
2.11.4 URL设计
1. 以下这些URL都是不推荐的,因为带上了动词,不是推荐写法。
/getAllExpresses
/getExpress
/createExpress
/deleteAllExpress
2. 避免多级URL
GET /team/1001/player/1005 不推荐
GET /team/1001?player=1005 推荐
GET /expresses/statu 不推荐
GET /expresses?statu=false 推荐
3.
2.12 Restful增删改查
2.12.1 增
1. 前台代码
<form action="" id="form">
id:<input type="text" id="id" name="id"><br>
名称:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="button" id="putAll">put查询所有</button>
<button type="button" id="postOne">post添加</button>
<button type="button" id="putOne">put更新</button>
<button type="button" id="deleteDel">del删除</button>
<p id="show"></p>
</form>
$("#postOne").click(function () {
alert($("#form").serialize());
$.ajax({
type:"post",
url:"/team",
data:$("#form").serialize(),
success:function (data) {
$("#show").html(data);
}
})
});
2. 后台代码
@RequestMapping(value = "/team",method = RequestMethod.POST)
@ResponseBody
public String add(Team team){
System.out.println(team);
list.add(team);
return "201";
}
2.12.2 删
1. 前台代码
<form action="" id="form">
id:<input type="text" id="id" name="id"><br>
名称:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="button" id="putAll">put查询所有</button>
<button type="button" id="postOne">post添加</button>
<button type="button" id="putOne">put更新</button>
<button type="button" id="deleteDel">del删除</button>
<p id="show"></p>
</form>
2. 后台代码
@RequestMapping(value = "/team/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String del(@PathVariable("id") int id){
for (Team team1:list) {
if(team1.getId() == id){
list.remove(team1);
return "200";
}
}
return "500";
}
2.12.3 改
1. 前台代码
<form action="" id="form">
id:<input type="text" id="id" name="id"><br>
名称:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="button" id="putAll">put查询所有</button>
<button type="button" id="postOne">post添加</button>
<button type="button" id="putOne">put更新</button>
<button type="button" id="deleteDel">del删除</button>
<p id="show"></p>
</form>
$("#putOne").click(function () {
$.ajax({
type:"post",
url:"/team/"+$("#id").val(),
data:$("#form").serialize()+"&_method=put",
dataType:"json",
success:function (data) {
alert(data);
}
})
});
2. 后台代码
@RequestMapping(value = "/team/{id}",method = RequestMethod.PUT)
@ResponseBody
public String update(@PathVariable("id") int id, Team team){
System.out.println(team);
for (Team team1:list) {
if(team1.getId() == id){
team1.setName(team.getName());
team1.setLocation(team.getLocation());
return "200";
}
}
return "500";
}
2.12.4 查
1. 前台代码
<form action="" id="form">
id:<input type="text" id="id" name="id"><br>
名称:<input type="text" name="name"><br>
所在地:<input type="text" name="location"><br>
<button type="button" id="putAll">put查询所有</button>
<button type="button" id="postOne">post添加</button>
<button type="button" id="putOne">put更新</button>
<button type="button" id="deleteDel">del删除</button>
<p id="show"></p>
</form>
<script>
$(function () {
$("#putAll").click(function () {
$.ajax({
type:"GET",
url:"/teams",
data:"",
dataType:"json",
success:function (data) {
var str="";
for (var i=0;i<data.length;i++){
var obj=data[i];
str+=obj.id+"---"+obj.name+"---"+obj.location;
}
$("#show").html(str);
}
})
});
})
</script>
2. 后台代码
@RequestMapping("/teams")
@ResponseBody
public List<Team> all(){
return list;
}
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。