大概思路
前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<a href="http://localhost:8080/car/get">点击跳转</a>
</body>
</html>
RunApp代码:
package cn.tedu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//自动配置了包扫描:默认从启动类所在的包开始
public class RunApp {
public static void main(String[] args) {
SpringApplication.run(RunApp.class);
}
}
PoJo代码:
package cn.tedu.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data//自动生成get set toString...
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)//开启链式编程
public class Car {
private String name;
private String color;
private Double price;
}
SpringMVC代码:(控制层)
package cn.tedu.controller;
import cn.tedu.pojo.Car;
import cn.tedu.service.CarServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("car")
public class CarConstructor {
@Autowired//di--想调用service层的代码
private CarServiceImpl c1;
@RequestMapping("get")
public Object get(){
return c1.get();//把结果给浏览器返回
}
}
Spring代码:(业务层)
package cn.tedu.service;
import cn.tedu.pojo.Car;
//定义接口
public interface CarService {
//接口中的方法都是抽象方法,都是public
Car get();//获取汽车数据
}
package cn.tedu.service;
import cn.tedu.pojo.Car;
import org.springframework.stereotype.Component;
@Component
public class CarServiceImpl implements CarService{
@Override
public Car get() {
Car c=new Car();
c.setName("保时捷").setColor("红色").setPrice(641000.0);
return c;
}
}