【问题标题】:Is there a way to know which full URL the Spring controller is going to map?有没有办法知道 Spring 控制器将映射哪个完整 URL?
【发布时间】:2016-11-07 06:31:18
【问题描述】:

我有一个 Spring 控制器,

@Controller
@RequestMapping(value = "/employee")
public class EmployeeController {

@Autowired
private EmployeeService employeeService;

/**
 * returns all the employees in the datastore.
 * 
 * @return list of all employees.
 */
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody String getAllEmployees() {
    return convertObjectListToJSONArray(this.employeeService.listEmployees());
}

/**
 * adds an employee in the data-store.
 * 
 * @param employee
 *            employee to add in the data-store.
 * @return request status.
 */
@ResponseStatus(value = HttpStatus.CREATED)
@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public ResponseEntity<?> addEmployee(UriComponentsBuilder uriCBuilder, @RequestBody Employee employee) {
    Employee e = this.employeeService.getEmployeeById(employee.getId());
    if(null != e) {
        throw new EmployeeConflictException(); 
    }
    this.employeeService.addEmployee(employee);
    UriComponents uriComponents = uriCBuilder.path("/cmpe281Pratik021/rest/employee/{id}")
            .buildAndExpand(employee.getId());
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(uriComponents.toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

但是,当我点击 http://localhost:8080/employee 时,它会给出错误 404。 有没有办法打印到这个 Spring 控制器将被映射的完整 url?

【问题讨论】:

  • 您点击的 URL 中似乎缺少您的上下文。 localhost:8080/<Context-Name>/employee
  • 您是如何部署此应用程序的?它是一个 .war 文件吗?还是春季启动?如果是 .war,您还需要 contextPath(.war 的名称)。 http://localhost:8080/&lt;name of war&gt;/employee

标签: spring spring-mvc spring-web


【解决方案1】:

有没有办法打印到这个 Spring 控制器所在的完整 url 会被映射吗?

您可以启用以下日志记录属性:

log4j.category.org.springframework.web=INFO

现在,如果您重新启动 Tomcat(或任何服务器),那么在启动期间,当 Spring 容器初始化 DispactherServletHandlerMapping 时,它将打印所有识别的映射(来自各种 Controller 类)到日志中,以便您可以实际验证 Controller 类将提供哪些映射。

P.S.:此日志只是列出/记录所有控制器映射,这将有助于调试/解决问题

【讨论】:

  • 我要试试这个。希望它能解决问题。
  • 它会帮助你列出所有的映射,这将有助于解决问题
  • 如何启用这个属性?
  • 您的服务器中有 log4j 属性吗?
  • 日志显示 - 2016-11-07T10:20:07.422957+00:00 app[web.1]: 2016-11-07 10:20:07 INFO RequestMappingHandlerMapping:543 - Mapped "{[/employee],methods=[GET]}" onto public java.lang.String edu.pratiksanglikar.cmpe281.hw3.extracredit.controllers.EmployeeController.getAllEmployees() 但请求 http://localhost:8080/employees 正在返回 HTTP 404。有什么输入吗?相关源文件可以找到here
猜你喜欢
  • 2010-12-23
  • 2015-11-21
  • 2021-11-08
  • 1970-01-01
  • 2019-03-28
  • 2020-01-16
  • 2012-10-25
  • 2022-12-11
  • 2011-04-23
相关资源
最近更新 更多