栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring MVC 01:json解析、参数传递、配置文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring MVC 01:json解析、参数传递、配置文件

一、Spring MVC实现JSON解析
	@RequestMapping("t1")//不写参数默认使用value属性
	@ResponseBody//在spring mvc中用了此句,自动把请求当成json处理!
	public User test1(){
		return new User("淳淳",18);
	}

 @ResponseBody//在spring mvc中用了此句,自动把请求当成json处理!

点击如图停掉之前的服务  

 User类是自己定义的实体(写完所需的属性后,直接使用软件自动生成有参构造、无参构造、getset方法、重写tostring)

访问网址:120.0.0.1:8080/t1

二、Spring MVC实现参数传递

(如何传参并解析)

1.简单传参(传简单的参数-如8个基本数据类型)
	@RequestMapping("t2")
	@ResponseBody//http://127.0.0.1:8080/t2?name=tom&age=20
	public String test2(String name,int age){
		return "Request参数是name="+name+",age="+age;
	}

http://127.0.0.1:8080/t2?name=tom&age=20

网址?参数1的名字=设定的参数1&参数2的名字=设定的参数2&...

2.复杂传参(传个集合或者数据,比如页面上有复选框时)
	@RequestMapping("t3")
	@ResponseBody//http://127.0.0.1:8080/t3?hobby=eat&hobby=sleep&hobby=dadoudou
	public String test3(String[] hobby){
		return "Request参数是:"+Arrays.toString(hobby);
	}

http://127.0.0.1:8080/t3?hobby=eat&hobby=sleep&hobby=dadoudou

网址?数组名=值1&数组名=值2&数组名=值3&.....

3.实体传参(传个实体)
	@RequestMapping("t4")
	@ResponseBody
	public User test3(User user){
		return user;
	}

http://127.0.0.1:8080/t4?name=cc&age=18

实体属性1=值1&实体属性2=值2&实体属性3=值3&...

三、如何给类加路径(方便一级区分)

直接在类前加:

//给类加路径:相当于加了一层目录http://127.0.0.1:8080/test/t1
@RequestMapping("test")

package demo.boot.controller;

import java.util.Arrays;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import demo.boot.entity.User;

@Controller

//给类加路径:相当于加了一层目录http://127.0.0.1:8080/test/t1
@RequestMapping("test")
public class DemoController {
	@RequestMapping(value="hello",method=RequestMethod.GET)
	@ResponseBody
	public String chun(){
		return "淳淳要努力";
	}
	
	
	@RequestMapping("t1")
	@ResponseBody
	public User test1(){
		return new User("淳淳",18);
	}
	//三种传参方式
	
	@RequestMapping("t2")
	@ResponseBody//http://127.0.0.1:8080/t2?name=tom&age=20
	public String test2(String name,int age){
		return "Request参数是name="+name+",age="+age;
	}
	
	
	@RequestMapping("t3")
	@ResponseBody//http://127.0.0.1:8080/t3?hobby=eat&hobby=sleep&hobby=dadoudou
	public String test3(String[] hobby){
		return "Request参数是:"+Arrays.toString(hobby);
	}
	
	
	@RequestMapping("t4")
	@ResponseBody
	public User test3(User user){
		return user;
	}
}
四、springboot配置端口号

数据库、改端口号等配置放在src/main/resources里

 右键-》new-》other-》搜索file-》next

文件名为application.properties-》finish

 将端口号改为8090

server.port=8090 

 

http://127.0.0.1:8090/test/t1打开

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/351714.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号