day-06spring - mvc

1. SpringMVC学习
1.1 JSON结构
1.1.1 什么是JSON
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它使得人们很容易的进行阅读和编写。同时也方便了机器进行解析和生成。它是基于 JavaScript Programming Language , Standard ECMA-262 3rd Edition - December 1999 的一个子集。 JSON采用完全独立于程序语言的文本格式,但是也使用了类C语言的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。
根源: 网络传输协议http/https,本质传输的数据都是字符串/字节信息. 协议与系统无关. 所以采用JSON的方式将数据按照特定的顺序进行排列. JSON中的特殊的数据结构,可以很好的解析字符串.

1.1.2 JSON的格式
1.1.2.1 对象格式
对象(object) 是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。
在这里插入图片描述

 {"id": "100","name":"tomcat","age":18,"sex":"男"}

1.1.2.2 对象格式

数组(array) 是值(value)的有序集合。一个数组以“[”(左中括号)开始,“]”(右中括号)结束。值之间使用“,”(逗号)分隔。

在这里插入图片描述

 [1,2,3,4,"张三","李四"]

1.1.2.3 嵌套格式

值(value) 可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。在这里插入图片描述

 [1,2,true,false,{"id":100,"name":"tomcat"},[{arrays: [[],[],[]]},5,6]]

1.2 SpringMVC 用法学习

1.2.1 关于SpringMVC 对象返回说明

/**
     * 要求:返回User对象
     * URL: http://localhost:8080/getUserById?id=100
     * 返回值: User对象
     * 知识点: 对象转化为json时,调用对象的get方法获取属性和属性值
     *        获取getxxx(),之后去除get 然后首字母小写 当做key,
     *        方法的返回值当做value
     */
    @RequestMapping("/getUserById")
    public User getUserById(int id){
        User user = new User();
        user.setId(id);
        user.setName("测试数据");
        user.setSex("男");
        user.setAge(18);
        return user;
    }

1.2.2 关于SpringMVC 对象返回说明

 /**
     * SpringMVC动态参数接收 同名提交问题 多个参数使用,号进行分隔
     * 爱好: 口 打篮球  口 踢足球  口 乒乓球
     * URL传递:http://localhost:8080/hobby?names=打篮球,踢足球,乒乓球
     * 返回值: 返回爱好的list集合
     * 知识点: 如果springmvc遇到同名提交参数,并且中间使用","号分隔
     *        则可以自动转化为数组.
     */
    @RequestMapping("/hobby")
    public List<String> hobby(String[] names){

        //数组如何转化为List集合
        return  Arrays.asList(names);
    }

1.3 RestFul结构(难点)
1.3.1 传入GET请求业务说明
需求说明: 向后端服务器传递多个参数, name=tomcat, age=18,sex=男
URL地址: http://localhost:8080/getUser?name=tomcat&age=18&sex=男
该方法能否优化? 能否降低字节数量

1.3.2 RestFul参数拼接
语法: 省略key,将value使用/的方式进行分隔.并且位置固定.
URL地址: http://localhost:8080/getUser/tomcat/18/男

1.3.3 RestFul参数接收
 

/**
     * 需求: 使用restFul结构接收参数
     * URL: http://localhost:8080/user/tomcat/18/男
     * 参数:  name/age/sex
     * 返回值: User对象
     * 难点知识: 如果获取url路径中的参数!!!
     * restFul参数接收的语法:
     *      1.参数使用{}进行包裹,并且指定属性名称
     *      2.使用注解@PathVariable进行参数接收
     *      3.restFul要求请求的路径不能出现动词
     * 优化: 如果restFul的属性名称与对象的属性名称一致,则可以利用对象接收
     */
    @RequestMapping("/user/{name}/{age}/{sex}")
    public User getUser(User user){

        return user;
    }

   /* public User getUser(@PathVariable String name,
                        @PathVariable int age,
                        @PathVariable String sex){
        User user = new User();
        user.setName(name);
        user.setAge(age);
        user.setSex(sex);
        return user;
    }*/

1.3.4 RestFul请求路径的通用写法
例子:
1. http://localhost:8080/getUserById?id=100
2. http://localhost:8080/deleteUserById?id=100
3. http://localhost:8080/updateUserById?id=100&name=tomcat
4. http://localhost:8080/insertUser POST 提交

问题: 上述的操作 意图特别的明显. 对后期操作会带来不安全的风险.

优化: restFul风格的请求名称的要求,不能出现动词

http://localhost:8080/userById?id=100 类型: GET 查询业务逻辑
http://localhost:8080/userById?id=100 类型: Delete 删除业务逻辑
http://localhost:8080/userById?id=100&name=tomcat 类型: PUT 更新业务逻辑
http://localhost:8080/user 类型: POST 新增业务逻辑

在这里插入图片描述

1.3.5 请求类型的种类

请求类型一共8种, 常用的4种 GET/POST/PUT/DELETE

 在这里插入图片描述

 

2 前后端调用

2.1 入门案例

2.1.1 编辑前端页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Axios入门案例</title>
	</head>
	<body>
		<!-- 1.导入js文件 -->
		<script src="js/axios.js"></script>
		
		<!-- 2.编辑JS代码 -->
		<script>
			//url地址: http://localhost:8080/findUser
			let url1 = "http://localhost:8080/axios/findUser"
			//语法: axios.get(url地址,传递的参数)
			axios.get(url1)
				 .then(function(promise){
					console.log(promise.data)
				 })
		</script>
		<h1>学习Axios的ajax调用</h1>
	</body>
</html>

2.1.2 编辑后端Controller

@RestController // @Controller + @ResponseBody
@CrossOrigin    // 允许跨域访问
@RequestMapping("/axios")   //将公共的部分抽取
public class AxiosController {

    @RequestMapping("/findUser")
    public String findUser(){

        return "查询用户成功!!!";
    }
}

2.1.3 关于promise对象说明

说明: axios 发送Ajax请求时,获取的服务器端数据,通过promise对象进行封装 格式如下. 一般通过data属性获取返回值结果在这里插入图片描述

 

2.1.4 关于谷歌浏览器常见功能

1.network在这里插入图片描述

 2. 根据报错提示 快速定位报错信息在这里插入图片描述

 

2.2 Axios-Get

2.2.1 参数拼接写法

  1. 页面JS
    			/**
    			 * 2.参数拼接  	
    			 * 需求: 根据Id查询User数据.
    			 */ 
    			let id2  = 100;
    			let url2 = "http://localhost:8080/axios/findUserById?id="+id2
    			axios.get(url2)
    				 .then(promise => {
    					 console.log(promise.data)
    				 })
    

  2. 编辑AxiosController
    /**
         * 需求: 根据Id查询用户信息
         * URL: http://localhost:8080/axios/findUserById?id=100
         * 参数: id=100
         * 返回值: User对象
         */
        @GetMapping("/findUserById")
        public User findUserById(Integer id){
            User user = new User();
            user.setId(id);
            user.setName("测试数据");
            user.setAge(18);
            user.setSex("女");
            return user;
        }
    

    在这里插入图片描述

    2.2.2 传递对象的写法

  3. 编辑页面JS
    /**
    			 * 需求3: 查询name="疫情快结束" age=1
    			 * URL: http://localhost:8080/axios/findUserByNA?name=xxx&age=1	
    			 * 关键字: params 对象标识符
    			 * 返回值: User对象
    			 */
    			let user3 = {name:"西安加油", age:1}
    			let url3 = "http://localhost:8080/axios/findUserByNA"
    			axios.get(url3,{params: user3})
    				 .then(promise => {
    					 console.log(promise.data)
    				 })
    

  4. 编辑AxiosController
     /**
         * 业务需求: 动态接收参数
         * URL地址: http://localhost:8080/axios/findUserByNA?name=xx&age=1
         * 参数: name=xx&age=1
         * 返回值: 返回User对象
         */
        @GetMapping("/findUserByNA")
        public User findUserByNA(User user){
            user.setId(3);
            user.setSex("男");
            return user;
        }
    

  5.  在这里插入图片描述

     

    2.2.3 restFul结构实现数据传参

  6. 编辑前端JS
    /**
    			 * 需求: 利用restFul 传递name/age
    			 * 前端知识点:  模板字符串
    			 * 语法:  反引号 `` 
    			 * 作用:
    			 * 		1. 可以保证字符串的语法结构
    			 * 		2. 可以动态的获取对象中的数据
    			 * 
    			 */
    			let user4 = {name: "南孚电池",age: 8 }
    			//let url4 = "http://localhost:8080/axios/user/"+user4.name+"/"+user4.age
    			let url4 = `http://localhost:8080/axios/user/${user4.name}/${user4.age}`
    			
    			axios.get(url4)
    				.then(promise => {
    					console.log(promise.data)
    				})
    			
    			let html =  `<div>
    							<p>第一</p>
    							<p>第二</p>
    							<p>第三</p>
    						 </div>`
    

  7. 编辑AxiosController
     /**
         * 动态接收前端restFul结构
         * URL: http://localhost:8080/axios/user/xxx/8
         * 参数:  name/age
         * 返回值: User对象返回
         */
        @GetMapping("/user/{name}/{age}")
        public User findUserNA(User user){
            user.setId(101);
            user.setSex("男");
            return user;
        }
    

    在这里插入图片描述

     

    2.3 简化Axios调用

    语法: axios.defaults.baseURL = “http://localhost:8080/axios”

    	/* 简化Axios调用 设定公共的请求的前缀 如果已经有http://协议则不拼接前缀   */
    	axios.defaults.baseURL = "http://localhost:8080/axios"
    	let url5 = `/user/${user4.name}/${user4.age}`
    	axios.get(url5)
    		.then(promise => {
    			console.log(promise.data)
    		})			  
    

    @Configuration 标识当前类是配置类
    @ComponentScan 包扫描注解 扫描注解
    @Bean 标识该方法的返回值交给Spring容器管理
    @Scope 控制多例和单例
    @Lazy 懒加载
    @PostConstruct 初始化方法
    @PreDestroy 销毁方法
    @Component 将当前类未来的对象交给容器管理
    @Autowired 按照类型进行注入
    @Qualifier 按照名称进行注入
    @Repository 标识持久层注解
    @Service 标识Service层
    @Controller 标识Controller层
    @Value 为属性赋值 @Value("${key}")
    @PropertySource 加载指定路径的配置文件properties
    @Aspect 标识当前类是一个切面类
    @Pointcut 用于定义切入点表达式 表达式写法4种
    @EnableAspectJAutoProxy 让AOP的注解有效果
    @Before AOP-前置通知
    @AfterReturning AOP-后置通知
    @AfterThrowing AOP-异常通知
    @After AOP-最终通知
    @Around AOP-环绕通知
    @Order(1) //可以利用order关键字 实现AOP的排序 数字越小越先执行.
    @ResponseBody 将返回的数据转化为JSON串, 如果是字符串本身 原数据返回
    @RequestMapping("/hello") 实现浏览器的请求路径与方法的映射
    @PathVariable restFul结构,接收参数的注解.
    @GetMapping("") 只能接收GET请求类型
    @DeleteMapping("") 只能接收DELETE请求类型
    @PostMapping("") 只能接收POST请求类型
    @PutMapping("") 只能接收PUT请求类型
    @RestController 表示Controller类,同时要求返回值为JSON
    @CrossOrigin 允许跨域访问
     

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值