Home > database >  How to redirect to a new domain(url) using Spring Boot?
How to redirect to a new domain(url) using Spring Boot?

Time:04-23

I am building a link shortener using spring boot. Everything is working except to redirect the user to the their url. I have checked other example on stackoverflow but nothing seems to be working for me.

Please view my code below

public class DosuController {

    private final DosuService dosuService;

    public DosuController(DosuService dosuService) {
        this.dosuService = dosuService;
    }

    @GetMapping("/{dosu}")
    public ResponseEntity<Void> redirect(@PathVariable("dosu") String dosu) {
        return dosuService.redirect(dosu);
    }
}
//SERVICE
public class DosuService {

    private final DosuRepo dosuRepo;

    public DosuService(DosuRepo dosuRepo) {
        this.dosuRepo = dosuRepo;
    }

    public ResponseEntity<Void> redirect(String dosu) {
        Dosu dosus = dosuRepo.findByDosu(dosu);
        if (dosus == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dosu not found with name:  "dosu);
        }

        return ResponseEntity.status(HttpStatus.FOUND)
            .location(URI.create(dosus.getRedirectUrl())
            .build();
    }
}


Output: localhost:8080/www.google.com

Desire Output: www.google.com

CodePudding user response:

You should check your dosus.getRedirectUrl() first. is this actual url what you expect?

Then, refactor your code, and try to return a redirect:url from your controller.

Controller:

@GetMapping("/{dosu}")
public String redirect(@PathVariable("dosu") String dosu) {
    Dosu dosus = dosuService.findByDosu(dosu);
    if (dosus == null) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Dosu not found with name: "   dosu);
    }
    return "redirect:"   dosus.getRedirectUrl();
}

Service:

public Dosu findByDosu(String dosu) {
    return dosuRepo.findByDosu(dosu);
}

CodePudding user response:

You can set the URI in the location headers as describe in the following code snippet. Make sure that you should add the proper URI SCHEME (like https mentioned in the uri). Ex:

  public ResponseEntity<Void> redirect() {
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(URI.create("https://www.google.com"));
    return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
  }

Updated service class method

public ResponseEntity<Void> redirect(String dosu){
 Dosu dosus = dosuRepo.findByDosu(dosu);
 if(dosus == null){
  throw new ResponseStatusException (HttpStatus.NOT_FOUND,"Dosu not found with name:  "dosu);
 }
 HttpHeaders headers = new HttpHeaders();

 // Make sure uri should be valid uri with proper scheme name

 headers.setLocation(URI.create(dosus.getRedirectUrl()));
 return new ResponseEntity<>(headers, HttpStatus.MOVED_PERMANENTLY);
}
  • Related