I have the controller method like below:
#RequestMapping(value = "/login/do", method = RequestMethod.POST)
public String loginProcess(#RequestParam("email") String email, #RequestParam("password") String password,
HttpSession session) {
session.setAttribute("email", email);
Optional<User> userDetail = userRepository.findById(email);
if (userDetail.isPresent()) {
String userType = userDetail.get().getUserType();
String passwordDb = userDetail.get().getPassword();
if (password.equals(passwordDb) && userType.equals("admin")) {
return "adminPage";
} else if (password.equals(passwordDb) && userType.equals("candidate")) {
return "candidatePage";
} else {
return "passwordError";
}
} else {
return "invalid";
}
I have URL localhost:8080/login/do as URL
for my login process method inside the method, some business logic is written upon execution of that it will take me to some page candidate.html,passworderror.html, etc however on moving to the any of the pages the URL is showing as localhost:8080/login/candidate.jsp here I don't want /login to be present in URL.
strong text
since here onwards moving on to any page if i move forward the localhost:8080**/
**login****
/candidate.jsp is present by default.
expected Url should not include login further.
remove from properties file if exists:
server.servlet.context-path=
and also specify where your jsp pages are created and also mention your properties file configuration and #Controller annotation code as well.
Related
I need some help from you all. Basically it has a base path at the class level (/grade), So the first method will return the jsp page to the user and second method will actually handle the request send from the client using xhr with GET method. So when it send the response I am able to handle it, but when i try to reload with the url http://localhost:8080/grade/12323 it returns me object not the page.
#GetMapping
public String getGradePage(HttpServletRequest request,Model model) {
HttpSession session = request.getSession();
User user = new User();
user.setUsername("1010000001");
user.setPassword("b");
session.setAttribute("user", user);
List<Course> courseList = gradeService.getAllClassById(user.getUsername());
model.addAttribute("courseList",courseList);
return "lecturer/submit-grade";
}
#GetMapping("/{courseCode}")
#ResponseBody
public List<Enrollment> submitGrade(#PathVariable String courseCode) {
List <Enrollment> enrollmentList = gradeService.getAllStudentEnrollmentById(courseCode);
return enrollmentList;
}
just solved it by changing the endpoint in my javascript xhr, what a silly mistake ..
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.
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
I am trying to make a log in system using spring. Problem is if username is not in the database I want to send a different status code and if username is in the database but password is wrong I want to send different status code. Because in my front end i am going to inform user using different alerts according to status code.
I cannot use HttpStatus.NOT_ACCEPTABLE or something like that because my controller is returning a User(my custom class). It will either return User or null.
#GetMapping("/users")
public User userLogin(#RequestParam String username,#RequestParam String password) {
User user = userService.findByUsername(username);
if(user==null) {
return null;
}
if(user.getPassword().equals(password)) {
return user;
} else {
return null;
}
}
Here I am trying to change status while returning nulls.
you can return ResponseEntity to meet your requirement
#GetMapping("/users")
public ResponseEntity<User> userLogin(#RequestParam String username,#RequestParam String password) {
User user = userService.findByUsername(username);
if(user==null) {
return new ResponseEntity<>(null,HttpStatus.NOT_FOUND);
}
if(user.getPassword().equals(password)) {
return new ResponseEntity<>(user,HttpStatus.OK);
} else {
return new ResponseEntity<>(null,HttpStatus.FORBIDDEN);
}
}
Spring 5 introduced the ResponseStatusException class. We can create an instance of it providing an HttpStatus and optionally a reason and a cause:
#GetMapping(value = "/{id}") public Foo findById(#PathVariable("id") Long id, HttpServletResponse response) {
try {
Foo resourceById = RestPreconditions.checkFound(service.findOne(id));
eventPublisher.publishEvent(new SingleResourceRetrievedEvent(this, response));
return resourceById;
}
catch (MyResourceNotFoundException exc) {
throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Foo Not Found", exc);
} }
Maybe this is which you looking for?
Detail in https://www.baeldung.com/exception-handling-for-rest-with-spring#controlleradvice
I have a spring mvc web application with the following code. When the user is not logged in I am sending one tiles view.
And when the user is logged in I am redirecting to specific url patterns.
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("Requested with /login mapping");
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {
List<String> userRoles = AuthenticationUtils.getUserRoles();
if (userRoles.contains("ROLE_ADMIN")) {
return "redirect:/admin.html";
} else if (userRoles.contains("ROLE_USER")) {
return "redirect:/user.html";
}
}
return "template";
}
I am getting the redirection but with some unexpected parameters. How to remove them?
http://localhost:8081/app/admin.html?total=48&loggedInUserRoles=207
I have tried the following url without success.
Spring MVC Controller: Redirect without parameters being added to my url
I have no clue of which part of code is adding the parameters.
You can make your method return View instead of String and then create RedirectView in a way:
RedirectView view = new RedirectView(url);
view.setExposeModelAttributes(false);
return view;
Using the redirectAttributes.addFlashAttribute("object",objectvalue);
Like this way it is successfully redirecting the object value to the next controller, but when we returned the view in the next controller it display the result in html page in browser. Then the problem starts when we refresh or reload the page then values disappears.
My code is
#RequestMapping(value = "/addRoom", method = RequestMethod.POST)
public String saveRoom(Room room,
ModelMap model, RedirectAttributes ra) {
amenitiesService.saveRoom(room);
Floor floor = amenitiesService.getFloorInfo(room.getFloorId());
String floorName = floor.getFloorName();
ra.addFlashAttribute(room);
ra.addFlashAttribute("floorName", floorName);
ra.addFlashAttribute("message","Room information is saved successfully.");
return "redirect:/redirectedUrl";
}
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model) {
return ADMIN_VIEW + SAVE_ROOM;
}
please any one suggest me how to redirect the object values to next controller with permanent not temporary visible like flash attributes
use this it may be work
#RequestMapping(value = "/redirectedUrl")
public String redirecturl(Room room, ModelMap model, RedirectAttributes re) {
String name=(String)re.getFlashAttributes("floorName");
return ADMIN_VIEW + SAVE_ROOM;
}