我有一个简单的Spring Boot Web应用程序.我正在尝试从服务器接收一些数据.Controller返回一个集合,但浏览器接收空JSON - 大括号的数量等于来自服务器的对象数,但其内容为空.
@RestController
public class EmployeeController {
@Autowired
private EmployeeManagerImpl employeeManagerImpl;
@RequestMapping(path="/employees", method = RequestMethod.GET)
public Iterable<Employee> getAllEmployees() {
Iterable<Employee> employeesIterable = employeeManagerImpl.getAllEmployees();
return employeesIterable;
}
}
Run Code Online (Sandbox Code Playgroud)
该方法触发,浏览器显示:
在控制台中没有更多.有任何想法吗?
编辑:Employee.java
@Entity
public class Employee implements Serializable{
private static final long serialVersionUID = -1723798766434132067L;
@Id
@Getter @Setter
@GeneratedValue
private Long id;
@Getter @Setter
@Column(name = "first_name")
private String firstName;
@Getter @Setter
@Column(name = "last_name")
private String lastName;
@Getter @Setter
private BigDecimal salary;
public Employee(){
}
}
Run Code Online (Sandbox Code Playgroud) 我使用spring boot web starter创建了restfull web应用程序,效果很好.我可以通过网址访问它.
但是我需要创建可以在后端计算和存储一些值的控制台命令.我希望能够手动或通过bash脚本运行控制台命令.
我找不到任何关于如何在spring boot web应用程序中集成spring-shell项目的文档.
在spring boot starter https://start.spring.io/中也没有选择spring-shell依赖的选项
1)webapp和console需要是两个独立的应用程序吗?我需要单独部署它们吗?
2)是否可以在同一个应用程序中部署Web应用程序并运行控制台命令?
3)在shell和Web应用程序之间共享公共代码(模型,服务,实体,业务逻辑)的最佳方法是什么?
有人可以帮忙吗?
我是Spring的新手,并试图用RestTemplate做一个休息请求.Java代码应该像下面的curl命令一样:
curl --data "name=feature&color=#5843AD" --header "PRIVATE-TOKEN: xyz" "https://someserver.com/api/v3/projects/1/labels"
Run Code Online (Sandbox Code Playgroud)
但是服务器用一个拒绝RestTemplate 400 Bad Request
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("PRIVATE-TOKEN", "xyz");
HttpEntity<String> entity = new HttpEntity<String>("name=feature&color=#5843AD", headers);
ResponseEntity<LabelCreationResponse> response = restTemplate.exchange("https://someserver.com/api/v3/projects/1/labels", HttpMethod.POST, entity, LabelCreationResponse.class);
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
我想通过在普通控制器上启用Spring Boot中的异步控制器来分析我可能看到的改进
所以这是我的测试代码.一个API返回Callable,另一个API是普通控制器API.两个API都阻止了10个模拟长时间运行的任务
@RequestMapping(value="/api/1",method=RequestMethod.GET)
public List<String> questions() throws InterruptedException{
Thread.sleep(10000);
return Arrays.asList("Question1","Question2");
}
@RequestMapping(value="/api/2",method=RequestMethod.GET)
public Callable<List<String>> questionsAsync(){
return () -> {
Thread.sleep(10000);
return Arrays.asList("Question2","Question2");
};
}
Run Code Online (Sandbox Code Playgroud)
我用这个配置设置了嵌入式tomcat,即只有一个tomcat处理线程:
server.tomcat.max-threads=1
logging.level.org.springframework=debug
Run Code Online (Sandbox Code Playgroud)
对/ api/1的期望 因为只有一个tomcat线程,所以在10secs之后处理这个处理将不会受理另一个请求
结果: 满足期望
/ api/2的期望 因为我们立即返回一个可调用的,所以单个tomcat线程应该可以自由处理另一个请求.Callable将在内部启动一个新线程.因此,如果您点击相同的API,它也应该被接受.
结果: 这没有发生,直到可调用完全执行,没有进一步的请求被接受.
问题 为什么/ api/2表现不如预期?
我在 spring boot 应用程序中得到了以下 @RestController :
@Data
@RestController
public class Hello {
@Autowired
private ResturantExpensesRepo repo;
@RequestMapping(value = "/expenses/restaurants",method = RequestMethod.POST,consumes =MediaType.APPLICATION_JSON_VALUE ,
headers = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void hello(@RequestBody ResturantExpenseDto dto)
{
Logger logger = LoggerFactory.getLogger("a");
logger.info("got a request");
ResturantExpenseEntity resturantExpenseEntity = new ResturantExpenseEntity();
resturantExpenseEntity.setDate(new Date(System.currentTimeMillis()));
resturantExpenseEntity.setName(dto.getName());
resturantExpenseEntity.setExpense(dto.getExpense());
repo.save(resturantExpenseEntity);
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试从 restClient/RestedClient(mozila 的两个插件)发送请求时,我收到以下错误:
{ "timestamp": 1512129442019, "status": 415, "error": "Unsupported Media Type", "message": "Content type 'text/plain;charset=UTF-8' not supported", "path": " /费用/餐厅”}
这个错误指出终点不支持 Json 内容,但我确实把
消费 =MediaType.APPLICATION_JSON_VALUE
@RequestMapping注解内
我错过了什么?
我正在使用Spring Boot和Web依赖创建一个简单的休息控制器.我试图将JSON主体反序列化为只有3个字段的测试POJO,但是当我尝试发出POST请求时,服务器响应500错误,我在控制台中得到的错误是:
.w.s.m.s.DefaultHandlerExceptionResolver : Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.util.LinkedHashMap
Run Code Online (Sandbox Code Playgroud)
我写的所有代码如下:
EmailApplication.java:
package com.test.email.app;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = { "com.test.email" })
public class EmailApplication {
public static void main(String[] args) {
SpringApplication.run(EmailApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("----- You're up and running with test-email-app! -----");
};
}
}
Run Code Online (Sandbox Code Playgroud)
EmailController.java:
package com.test.email.controller;
import …Run Code Online (Sandbox Code Playgroud) 我有json一些带有一些字段的简单消息,并希望使用它将其映射到java对象spring-web.
问题:我的目标类字段的命名与int json响应的命名方式不同.我怎么能无论如何将它们映射到对象而不必重命名java中的字段?
是否有可以放在这里的注释?
{
"message":"ok"
}
public class JsonEntity {
//how to map the "message" json to this property?
private String value;
}
RestTemplate rest = new RestTemplate();
rest.getForObject(url, JsonEntity.class);
Run Code Online (Sandbox Code Playgroud) 在我修改了一个RESTful Web服务示例以从api.stackexchange.com 调用来自id的用户之后,我得到了JsonParseException:
com.fasterxml.jackson.core.JsonParseException: Illegal character ((CTRL-CHAR, code 31)): only regular white space (\r, \n, \t) is allowed between tokens
响应来自api.stackexchange.comgzip压缩.
如何在Spring-Web RestTemplate中添加对gzip压缩响应的支持?
我正在使用Spring boot parent ver.1.3.1.RELEASE因此Spring-Web4.2.4-RELEASE
这是我调整后的例子:
User.java
package stackexchange.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonNaming(LowerCaseWithUnderscoresStrategy.class)
public class User {
// Properties made public in order to shorten the example
public int userId;
public String displayName;
public int reputation;
@Override
public String toString() {
return "user{" …Run Code Online (Sandbox Code Playgroud) 我一直试图弄清楚弹簧表单提交的最佳实践是什么,以及实现这一目标的最小样板是什么.
我认为以下是最佳实践特征
model.clear())之间的URL中到目前为止,我已经想出了这个.
@Controller
@RequestMapping("/")
public class MyModelController {
@ModelAttribute("myModel")
public MyModel myModel() {
return new MyModel();
}
@GetMapping
public String showPage() {
return "thepage";
}
@PostMapping
public String doAction(
@Valid @ModelAttribute("myModel") MyModel myModel,
BindingResult bindingResult,
Map<String, Object> model,
RedirectAttributes redirectAttrs) throws Exception {
model.clear();
if (bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.myModel", bindingResult);
redirectAttrs.addFlashAttribute("myModel", myModel);
} else {
// service logic
}
return "redirect:/thepage";
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法用更少的样板代码来做到这一点,或者这是实现这一目标所需的最少代码量?
来自Node的背景,在春季启动中相当于console.log()?
例如,我想通过以下方法在控制台中查看作业信息。
@RequestMapping(value = "jobposts/create", method = RequestMethod.POST)
public Job create(@RequestBody Job job){
System.out.println(job);
return jobRepository.saveAndFlush(job);
}
Run Code Online (Sandbox Code Playgroud)
System.out.println(); 我知道如何用Java做到这一点,但是它似乎没有出现在控制台中。使用IntelliJ。
spring ×10
spring-web ×10
java ×7
spring-boot ×6
json ×2
spring-mvc ×2
boilerplate ×1
jackson ×1
resttemplate ×1
spring-shell ×1
utf-8 ×1