Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在控制器JavaSpring中获得不同的方法_Java_Spring_Rest - Fatal编程技术网

如何在控制器JavaSpring中获得不同的方法

如何在控制器JavaSpring中获得不同的方法,java,spring,rest,Java,Spring,Rest,我正试图通过REST web服务将数据从数据库检索到移动应用程序。我已经成功地创建了一些基本函数,但是当我尝试添加函数时,我遇到了问题。例如,我希望能够通过Id和姓名找到“客户”。当我有两个Get方法时,一个是“/{id}”,另一个是“/{name}”,应用程序不知道该使用什么。如何按名称搜索? 这是来自web服务的控制器 package com.example; import org.springframework.beans.factory.annotation.Autowired; i

我正试图通过REST web服务将数据从数据库检索到移动应用程序。我已经成功地创建了一些基本函数,但是当我尝试添加函数时,我遇到了问题。例如,我希望能够通过Id和姓名找到“客户”。当我有两个Get方法时,一个是“/{id}”,另一个是“/{name}”,应用程序不知道该使用什么。如何按名称搜索? 这是来自web服务的控制器

package com.example;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/customers")
public class CustomerController {
private CustomerRepository repository;

@Autowired
public CustomerController(CustomerRepository repository) {
    this.repository = repository;
}

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
public ResponseEntity<Customer> get(@PathVariable("name") String name) {
    Customer customer = repository.findByName(name);
    if (null == customer) {
        return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Customer>(customer, HttpStatus.OK);
}

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<Customer> get(@PathVariable("id") Long id) {
    Customer customer = repository.findOne(id);
    if (null == customer) {
        return new ResponseEntity<Customer>(HttpStatus.NOT_FOUND);
    }
    return new ResponseEntity<Customer>(customer, HttpStatus.OK);*
}

@RequestMapping(value = "/new", method = RequestMethod.POST)
public ResponseEntity<Customer> update(@RequestBody Customer customer) {
    repository.save(customer);
    return get(customer.getName());
}

@RequestMapping
public List<Customer> all() {
    return repository.findAll();
}
}
package.com.example;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.http.HttpStatus;
导入org.springframework.http.ResponseEntity;
导入org.springframework.web.bind.annotation.*;
导入java.util.List;
@RestController
@请求映射(“/customers”)
公共类客户控制器{
私有客户存储库;
@自动连线
公共CustomerController(CustomerRepository存储库){
this.repository=存储库;
}
@RequestMapping(value=“/{name}”,method=RequestMethod.GET)
public ResponseEntity get(@PathVariable(“name”)字符串名){
Customer=repository.findByName(名称);
if(null==客户){
返回新的ResponseEntity(未找到HttpStatus.NOT_);
}
返回新的响应状态(客户,HttpStatus.OK);
}
@RequestMapping(value=“/{id}”,method=RequestMethod.GET)
public ResponseEntity get(@PathVariable(“id”)Long id){
Customer=repository.findOne(id);
if(null==客户){
返回新的ResponseEntity(未找到HttpStatus.NOT_);
}
返回新的响应状态(客户,HttpStatus.OK)*
}
@RequestMapping(value=“/new”,method=RequestMethod.POST)
公共响应属性更新(@RequestBody-Customer){
保存(客户);
返回get(customer.getName());
}
@请求映射
公共列表全部(){
返回repository.findAll();
}
}
这是来自android应用程序的服务

package com.ermehtar.poppins;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.PATCH;
import retrofit2.http.POST;
import retrofit2.http.Path;

public interface CustomerService {
@GET("customers")
Call<List<Customer>> all();

@GET("customers/{id}")
Call<Customer> getUser(@Path("id") Long id);

@GET("customers/{name}")
Call<Customer> getUser(@Path("name") String name);

@POST("customers/new")
Call<Customer> create(@Body Customer customer);
}
package com.ermehtar.poppins;
导入java.util.List;
2.电话;;
导入文件2.http.Body;
导入文件2.http.GET;
导入2.http.PATCH;
导入文件2.http.POST;
导入2.http.Path;
公共接口客户服务{
@获取(“客户”)
调用全部();
@获取(“客户/{id}”)
调用getUser(@Path(“id”)长id);
@获取(“客户/{name}”)
调用getUser(@Path(“name”)字符串名);
@邮政(“客户/新”)
调用创建(@Body Customer);
}
这就是我用来按名称调用服务的函数。当/name和/id函数都在web服务控制器中时,response.body将为null,但当其中一个函数被注释掉时,这就可以了

findUsernameButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Call<Customer> createCall = service.getUser("John");
            createCall.enqueue(new Callback<Customer>() {
                @Override
                public void onResponse(Call<Customer> _, Response<Customer> resp) {
                    findUsernameButton.setText(resp.body().name);
                }

                @Override
                public void onFailure(Call<Customer> _, Throwable t) {
                    t.printStackTrace();
                    allCustomers.setText(t.getMessage());
                }
            });
        }
    });
findUsernameButton.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Call createCall=service.getUser(“John”);
createCall.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
findUsernameButton.setText(resp.body().name);
}
@凌驾
失败时公共无效(调用,可丢弃){
t、 printStackTrace();
allCustomers.setText(t.getMessage());
}
});
}
});

希望我能让自己明白。请询问是否有不清楚的地方或您需要更多信息。

使用不同的路径区分URL,这也会使它们更加RESTful

按姓名搜索:

/customers/names/{name}
按ID搜索:

/customers/ids/{id}
将来,您可能希望添加另一个搜索,可能是按城市:

/customers/cities/{city}

使用不同的路径区分URL,这也会使它们更加RESTful

按姓名搜索:

/customers/names/{name}
按ID搜索:

/customers/ids/{id}
将来,您可能希望添加另一个搜索,可能是按城市:

/customers/cities/{city}

您的控制器映射了不明确的处理程序方法,因此在调用端点时,您将实际得到一个异常。通过为“按id获取”和“按名称获取”创建不同的映射来修复此问题。

您的控制器映射了不明确的处理程序方法,因此在调用端点时,您实际上会得到一个异常。通过为“按id获取”和“按名称获取”创建不同的映射来修复此问题。

资源由其路径(而不是参数)唯一标识。因此,几乎没有具有相同路径的资源:
“customers/”

您可以创建两种不同的资源,如:

  • @RequestMapping(value=“/id”,method=RequestMethod.GET)
  • @RequestMapping(value=“/name”,method=RequestMethod.GET)
或者,您可以使一个资源具有多个请求参数:

@RequestMapping(value=“/get”,method=RequestMethod.get)
公共响应获取(@RequestParam(“id”)长id、@RequestParam(“name”)字符串名称)

资源由其路径(而不是参数)唯一标识。因此,几乎没有具有相同路径的资源:
“customers/”

您可以创建两种不同的资源,如:

  • @RequestMapping(value=“/id”,method=RequestMethod.GET)
  • @RequestMapping(value=“/name”,method=RequestMethod.GET)
或者,您可以使一个资源具有多个请求参数:

@RequestMapping(value=“/get”,method=RequestMethod.get)
公共响应获取(@RequestParam(“id”)长id、@RequestParam(“name”)字符串名称)

您的restful设计可以改进。我建议这样定义:

@RequestMapping(value = "/", method = RequestMethod.GET, , params = "name")
public ResponseEntity<Customer> getByName(@RequestParam("name") String name) {
    ...
}

@RequestMapping(value = "/", method = RequestMethod.GET, , params = "lastname")
public ResponseEntity<Customer> getByLastname(@RequestParam("lastname") String lastname) {
    ...
}
新建:

/customers/new
/customers/{id}
/customers/{name}
这是不正确的,在restful中,资源创建应该由方法类型定义。我建议:

/customers with POST method.
/customers?name=<<name>>
按ID搜索:

/customers/new
/customers/{id}
/customers/{name}
这是正确的,在restful中,应该使用path变量通过id访问资源

按名称搜索:

/customers/new
/customers/{id}
/customers/{name}
这是不正确的,您正在查询客户资源,因此,您应该使用查询参数,我建议:

/customers with POST method.
/customers?name=<<name>>
/cu