一、Spring MVC实现JSON解析
/**
* json响应,记得先停掉之前的运行,不然会端口占用
* @return
*/
@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个基本数据类型)
/**
* 如何接收传参并响应,请求传参
* @return
*/
@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 "淳淳要努力";
}
/**
* json响应,记得先停掉之前的运行,不然会端口占用
* @return
*/
@RequestMapping("t1")
@ResponseBody
public User test1(){
return new User("淳淳",18);
}
//三种传参方式
/**
* 如何接收传参并响应
* @return
*/
@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打开