Issue
I have created a REST api which can used to save different urls those url have auto-increment feature that assign them an id one endpoint is to add urls and other is to fetch urls from id I want to do something like if I pass localhost:8080/getUrlById?id=4/ my browser should redirect me to that url which is there at 4th no.
my controller code -
@GetMapping("/addUrl")
public ResponseEntity<?> addUrlByGet(String url) {
return new ResponseEntity<>(sortnerService.addUrlByGet(url),HttpStatus.OK);
}
@GetMapping("/findUrlById")
public ResponseEntity<?> findSortnerById(Integer id){
return new ResponseEntity<>(sortnerService.findUrlById(id), HttpStatus.OK);
}
service class -
@Service
public class SortnerService {
@Autowired
private SortnerRepo sortnerRepo;
public Sortner addUrlByGet(String url) {
Sortner sortner = new Sortner();
sortner.setUrl(url);
return sortnerRepo.save(sortner);
}
// finding by particular Id
public List<Sortner> findUrlById(Integer id){
return sortnerRepo.findSortnerById(id);
}
}
Can anyone suggest me any way to do it I am really new to SpringBoot Sorry if I have made any silly mistake.
Solution
Based on the information from the comments, I suggest that the Sortner
class looks like this:
public class Sortner {
Long id;
URL url;
}
So to redirect to the URL by the Id from your service you need to rewrite your controller to look like this:
@GetMapping("/findUrlById")
public void findSortnerById(Integer id, HttpServletResponse response) throws IOException {
List<Sortner> urls = sortnerService.findUrlById(id);
if(urls != null && urls.size() > 0) {
response.sendRedirect(urls.get(0).getUrl().toString());
}
response.sendError(HttpServletResponse.SC_NOT_FOUND)
}
- response.sendRedirect redirects to the required URL
- response.sendError returns 404 as the URL cannot be found in the database
Answered By - VadymVL