在Spring Rest中,我有一个RestController公开这个方法:
@RestController
@RequestMapping("/controllerPath")
public class MyController{
@RequestMapping(method = RequestMethod.POST)
public void create(@RequestParameter("myParam") Map<String, String> myMap) {
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
我想有这样的方法进行测试,使用MockMVC从春:
// Initialize the map
Map<String, String> myMap = init();
// JSONify the map
ObjectMapper mapper = new ObjectMapper();
String jsonMap = mapper.writeValueAsString(myMap);
// Perform the REST call
mockMvc.perform(post("/controllerPath")
.param("myParam", jsonMap)
.andExpect(status().isOk());
Run Code Online (Sandbox Code Playgroud)
问题是我得到500 HTTP错误代码.我很确定这是因为我使用Map作为我的控制器的参数(我尝试将其更改为String并且它可以工作).
问题是:如何在我的RestController中使用Map参数,并使用MockMVC正确测试?
谢谢你的帮助.
我正在尝试使用Spring Boot实现简单的演示MVC应用程序,但在执行应用程序时出现404错误.uri是` http:// localhost:8080 / ',它显示名为circle的表中的所有行.
Maven Java项目:
Application.java
package com.nomad.dubbed.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
CircleController.java
package com.nomad.dubbed.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.nomad.dubbed.dao.CircleService;
import com.nomad.dubbed.model.Circle;
@RestController
@RequestMapping("/")
public class CircleController {
@Autowired
private CircleService circleService;
@RequestMapping(method=RequestMethod.GET)
public List<Circle> getAll() {
return circleService.getAll();
}
}
Run Code Online (Sandbox Code Playgroud)
CircleRepository.java
package com.nomad.dubbed.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.nomad.dubbed.model.Circle; …Run Code Online (Sandbox Code Playgroud) 我有一个Spring控制器注释,@RestController它返回JSON.我还有一个带有@ControllerAdvice与@ExceptionHandler一些自定义异常相关的s 注释的类.我正在使用Tomcat来提供这个RESTful API.我希望有任何非自定义异常,例如来自第三方库或NullPointerException的异常被捕获并返回状态500 - 内部服务器错误为JSON,带有消息而不是显示错误的HTML页面.
如果我@ExceptionHandler(Exception.class)在控制器建议中使用它,它将接管所有Spring异常,如MissingPathVariableException.class,这是不理想的.我已经尝试过扩展Spring的ResponseEntityExceptionHandler,但是这个类没有用@ResponseBody注释,所以不返回JSON.
java json exception-handling spring-mvc spring-restcontroller
我只是在想,为休息服务创建PATH映射的最佳做法是什么.假设我们有以下路径:
/users POST
/users/1 PATCH, GET
/users/1/contacts GET, POST
/users/1/contacts/1 GET, PATCH
Run Code Online (Sandbox Code Playgroud)
问题是 - 创建控制器的最佳实践是什么.例如,我们有UserController,我们在技术上可以放置所有这些映射.或者 - 我们应该创建单独的控制器(UserController,ContactsController).如果我们把所有东西放在下面,请在下面的UserController中.
@RequestMapping("users")
@RestController
public class UserController {
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> createUser() {}
@RequestMapping(method = RequestMethod.GET)
public User getUser() {}
@RequestMapping(value = "{id}/contacts", method = RequestMethod.GET)
public List<Contact> getContacts() {}
@RequestMapping(value = "{id}/contacts", method = RequestMethod.POST)
public ResponseEntity<Void> createContact() {}
.....
}
Run Code Online (Sandbox Code Playgroud)
如果我们创建单独的控制器,那么应该如何组织路径呢?可能这是一个愚蠢的问题,但如果有人可以分享经验,我会很高兴.
我无法直接获取JSONObject,此代码有效:
RestTemplate restTemplate = new RestTemplate();
String str = restTemplate.getForObject("http://127.0.0.1:8888/books", String.class);
JSONObject bookList = new JSONObject(str);
Run Code Online (Sandbox Code Playgroud)
但是这段代码没有:
JSONObject bookList = restTemplate.getForObject("http://127.0.0.1:8888/books", JSONObject.class);
Run Code Online (Sandbox Code Playgroud)
可能是什么问题呢?它没有给出错误,但最后我有一个空的JSONObject.
我的pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>library-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>LibraryClient</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies>
<build> …Run Code Online (Sandbox Code Playgroud) 我想部署一个Spring-Boot application具有Service访问JpaRepository它连接到PostgreSQL DB在系统运行时JPA和Hibernate中,指的连接属性src/main/resources/application.properties
当我在Tomcat上部署构建的.WAR时,应用程序无法启动错误日志中给出的错误.
有人可以帮忙解决这个错误的含义吗?
注意:我已经注意到了麻烦点MyServiceImpl和MyRequestBody类,但我没有得到该错误的确切原因,因为我是新来的Spring框架.
我的Spring Boot Starter项目中相关类的定义如下:
Spring Boot应用程序
@SpringBootApplication
@ComponentScan(<root package name under which all subpackages containing relevant classes >)
public class MySpringBootApplication extends SpringBootServletInitializer {
Run Code Online (Sandbox Code Playgroud)
我的Spring-Boot RestController类(自动装配MyService类实例)
@RestController
public class MyController {
@Autowired
MyService myService;
Run Code Online (Sandbox Code Playgroud)
我的服务界面(我没有提供任何@Service注释)
public interface MyService {
//all service method definitions
}
Run Code Online (Sandbox Code Playgroud)
Spring ServiceImpl类,具有在PostgreSQL DB上运行的自动装配存储库实例
@Service("myService")
public class MyServiceImpl implements MyService {
@Autowired
private MyRepository …Run Code Online (Sandbox Code Playgroud) spring spring-data spring-data-jpa spring-boot spring-restcontroller
我有一个数据类,如下所示:
public class Person {
private String name;
private Long code;
// corresponding getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我想编写两个Web服务,提供两个不同的JSON表示形式的Person.例如,其中一个提供{"name":"foo"}但另一个提供{"name":"foo", "code":"123"}.
作为一个更复杂的场景,假设Person有一个引用属性,例如address.地址也有自己的属性,我希望我的两个Web服务都考虑这个属性,但每个属性都以自己的方式执行.
我的SpringMVC视图应该如何?
请注意,我是SpringMVC的新手.请在答案旁边给我一个示例代码.
更新1:几天后,所有答案都促使我解决控制器中的问题或通过注释数据类.但我希望在视图中执行此操作,而不再使用java代码.我可以在JSP文件或百万美元模板甚至.properties文件中执行此操作吗?
更新2:我找到了json-taglib.但不知何故,它被排除在新的升级之外.有没有类似的解决方案?
假设我们有以下类:
public abstract class Investment {
private String investmentType;
// getters & setters
}
public class Equity extends Investment {
}
public class Bond extends Investment {
}
public class InvestmentFactory {
public static Investment getTypeFromString(String investmentType) {
Investment investment = null;
if ("Bond".equals(investmentType)) {
investment = new Bond();
} else if ("Equity".equals(investmentType)) {
investment = new Equity();
} else {
// throw exception
}
return investment;
}
}
Run Code Online (Sandbox Code Playgroud)
以下内容@RestController:
@RestController
public class InvestmentsRestController {
private InvestmentRepository investmentRepository; …Run Code Online (Sandbox Code Playgroud) 我有复杂的@RestController方法,如下所示:
@PostMapping("{id}")
@PreAuthorize("hasRole('ADMIN')")
@Transactional
public Response handleRequest(@PathVariable("id") long id, @RequestBody @Valid Request request) {
return service.handleRequest(id, request);
}
Run Code Online (Sandbox Code Playgroud)
我们的请求处理非常慢,因此我们想检查在特定的请求处理任务上花费了多少时间。不幸的是,很多事情都是在我的方法之外完成的,例如:
有没有办法简单地测量所有这些部分?也许是一组接收跟踪消息的记录器,以便我可以在每一步结束时提取时间戳?
我现在看到的唯一方法是更改该方法以接受HttpServletRequest和HttpServletResponse并在方法主体中执行这些部分。但是那样一来,我将失去很多Spring Boot的好处。
代码约定说控制器中没有逻辑。所有这些都应在服务层中处理。我的问题尤其是关于返回ResponseEntity的问题。
应该在RestController还是在Service层中处理?
我尝试了两种方式。我认为RestController是返回ResponseEntity的合适位置。因为我们在RestController中使用映射。
另一方面,我们知道控制器不应包含任何逻辑。
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return ResponseEntity.ok(employeeService.findEmployeeById(id);
}
Run Code Online (Sandbox Code Playgroud)
要么
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(@PathVariable Long id) {
return employeeService.findEmployeeById(id);
}
Run Code Online (Sandbox Code Playgroud)
我的另一个担心是用于异常处理的ControllerAdvice。最好使用哪种方式?
感谢您的进步。
java ×6
spring ×6
spring-boot ×5
spring-mvc ×4
spring-rest ×3
json ×2
dictionary ×1
maven ×1
mockmvc ×1
profiling ×1
resttemplate ×1
spring-data ×1