Eclipse Springboot入门(二)——外部web访问接口
当在测试类里面测试通过以后便可以写控制类进行外部web访问
控制controller模块(UserList.java)
package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
@RestController
@RequestMapping("/user")
public class UserList {
@Autowired
private UserMapper userMapper;
@GetMapping("/get")
public List<User> findAll() {
List<User> users = userMapper.selectList(null);
return users;
}
}
在application.yml中将服务器端口设置为8181
运行启动类
外部web进行测试,
附.前后端进行连接中的问题(跨域问题)
在springboot中的解决方法
创建一个config模块
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfig implements WebMvcConfigurer{
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}