Request method 'POST' not supported in Springboot MVC - spring-boot

Below are my GET and POST methods..
When I run the application, I get this error: Request method 'POST' not supported.
GET Method:
#RequestMapping(value = "userProfiles/{userId}/setup/Tool", method = RequestMethod.GET)
public String ToolSetup(Model model, #PathVariable int userId, #RequestParam(value = "update", defaultValue = "false") boolean update) {
model.addAttribute("formInput", new Resource());
model.addAttribute("userId", userId);
if (update) {
model.addAttribute("update", "update");
} else model.addAttribute("update", "");
return "Tool";
}
Below is my POST method:
#RequestMapping(value = "/userProfiles/{userId}/setup/Tool", method = RequestMethod.POST)
#ResponseBody
public void makeVideo(#PathVariable Long userId, #ModelAttribute("formInput") Resource formInput,
Authentication authentication,
ModelMap modelMap,
#RequestParam("uploadingFiles") MultipartFile[] uploadingFiles,
#RequestParam("track_value") int trackNumber,
HttpServletResponse response) throws IOException, URISyntaxException, InterruptedException, FrameGrabber.Exception,FrameRecorder.Exception {
UserProfile userProfile = userProfileRepository.findOne(userId);
ArrayList<String> photos = new ArrayList<>();
String audioPath= audioPath1;
for(MultipartFile file : uploadingFiles){
photos.add(file.getName());
}
formInput.setUploadingFiles(photos);
modelMap.put("formInput", formInput);
//some processing with images and the audio
response.sendRedirect("/userProfiles/" + userId + "/Tool/Processing"); //redirect to notif. page, then redirect to logged in home
}
HTML:
<form th:action="#{${#httpServletRequest.requestURI + '?update=true'}}" th:object="${formInput}" method="POST" enctype="multipart/form-data">
I know there are other posts related to this once, and I have tried all the recommended solutions from them but nothing seems to work..
Any help is appreciated!

Related

Redirect does not working properly using spring mvc

Redirection does not work properly. I could not understand the problem because I very new to spring.
Here is my controller when I submit my form then ("schoolform") submitForm controller called and it redirect to another controller to ('form') form controller but it goes to ("login") login controller. I don't know why ?
I want to redirect schoolform to form controller.
#RequestMapping(value = "/schoolform", method = RequestMethod.POST)
public String submitForm(#ModelAttribute("school")School school,Model model,HttpServletRequest request,HttpServletResponse resp) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
schoolService.update(school);
System.out.println("Form submitted finaly, No further changes can be made.");
return "redirect:/form.html";
}
#RequestMapping(value = "/form", method = RequestMethod.GET)
public String form(Model model,HttpServletRequest request) {
HttpSession session = request.getSession(true);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); // get logged in username
System.out.println(name+"--------form page-----");
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
logger.info("------------------LoginController ---------------");
System.out.println("LoginController ");
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
I think it is not working because the method in which you are trying to redirect to a url, accepts POST requests. You cannot redirect from POST methods UNLESS you have a handler method that accepts GET method and whose #RequestMapping accepts the value where you are trying to redirect.
So basically, the method submitForm which accepts POST requests only, is trying to redirect to /form.html. Now, there is no method in your controller that accepts /form.html, So now you gotto have a method in your controller class whose mapping value is /form.html and it accepts GET requests:
#RequestMapping(value = "/form.html", method = RequestMethod.GET)
public String methodName(arg1 ..){ ... }

Spring form validate : Whitelabel Error Page

#RequestMapping(method = RequestMethod.GET, value = "/add")
public ModelAndView add() throws ConferenceNotFoundException {
LOGGER.debug("Getting adding page");
return new ModelAndView("conference/add", "form", new ConferenceForm());
}
#RequestMapping(method = RequestMethod.POST, value = "/add")
public String handleAddConferenceForm(#Valid #ModelAttribute("form") ConferenceForm form,
BindingResult bindingResult,
#ModelAttribute("currentUser") CurrentUser currentUser) {
LOGGER.debug("Processing add conference form={}, bindingResult={}", form, bindingResult);
form.setHost(currentUser.getUser());
if (bindingResult.hasErrors()) {
// failed validation
return "conference/add";
}
try {
conferenceService.create(form);
} catch (Exception e) {
e.printStackTrace();
}
// ok, redirect
return "redirect:/";
}
I make spring form like above the code. And it works well like above the picture.
#RequestMapping(method = RequestMethod.GET, value = "/{id}/admin/update")
public ModelAndView update(Model model,
#PathVariable("id") Long id) throws ConferenceNotFoundException {
LOGGER.debug("Getting update page");
Conference conference = conferenceService.findById(id);
model.addAttribute("conference", conference);
return new ModelAndView("conference/update", "form", new ConferenceForm(conference));
}
#RequestMapping(method = RequestMethod.POST, value = "/{id}/admin/update")
public String handleUpdateConferenceForm(#Valid #ModelAttribute("form") ConferenceForm form,
#PathVariable("id") Long id,
BindingResult bindingResult,
#ModelAttribute("currentUser") CurrentUser currentUser) {
LOGGER.debug("Processing update conference form={}, bindingResult={}", form, bindingResult);
form.setHost(currentUser.getUser());
if (bindingResult.hasErrors()) {
// failed validation
return "conference/update";
}
try {
conferenceService.update(form, id);
} catch (Exception e) {
e.printStackTrace();
}
// ok, redirect
return "redirect:/conferences/" + id + "/admin";
}
Otherwise, above the code does not work well. It's validator works well and it update the contents. But it generate Whitelabel Error Page when validator works.
I don't know why it generate Whitelabel Error Page.
I found what the problem is.
Change BindingResult bindingResult's location.
From:
public String handleUpdateConferenceForm(#Valid #ModelAttribute("form") ConferenceForm form,
#PathVariable("id") Long id,
BindingResult bindingResult,
#ModelAttribute("currentUser") CurrentUser currentUser)
To:
public String handleUpdateConferenceForm(#Valid #ModelAttribute("form") ConferenceForm form,
BindingResult bindingResult,
Model model,
#PathVariable("id") Long id,
#ModelAttribute("currentUser") CurrentUser currentUser)

Sending ajax response to another controller using Spring MVC

I have a view from where I am sending a request to a Controller and as a result getting response back to the view page. Now I want to pass the ajax response in to the next Controller but I do not know what will be the type of response in Controller
This is my ajax code:
$.ajax({
type: "POST",
url: "<c:url value="/menu/menucheckout/${restaurant_menu.name}"/>",
data : {"amount":amount, "orderoption" :orderoption, "date":date , "time":time ,'menuitemsArray': menuitemsArray ,'menuPriceArray': menuPriceArray , 'menuSpiceeArray': menuSpiceeArray , 'ItemQuantityArray': ItemQuantityArray },
success: function(response){
console.log(response);
window.location.href = "/BistroServicesMenuApp/welcome/getordercheckout/"+response.model;
}
});
Here is the Menu Controller
#Controller
#RequestMapping(value = "/menu")
public class MenuController {
#Autowired
private MenuTypeService menutypeService;
#RequestMapping(value="/menucheckout/{restaurantname}" ,method = RequestMethod.POST )
#ResponseBody
public ModelAndView menucheckout(#PathVariable("restaurantname") String restaurantname , HttpSession session, HttpServletRequest request, HttpServletResponse response) throws SQLException, NamingException, IOException
{
ModelAndView model = new ModelAndView("/welcome/getordercheckout");
System.out.println("COMING IN menucheckout CONTROLLER" + restaurantname);
System.out.println("orderoption" + request.getParameter("orderoption"));
String amount = request.getParameter("amount");
String orderoption = request.getParameter("orderoption");
String date = request.getParameter("date");
String time = request.getParameter("time");
String[] menuitemsArray = request.getParameterValues("menuitemsArray[]");
String[] menuPriceArray = request.getParameterValues("menuPriceArray[]");
String[] menuSpiceeArray = request.getParameterValues("menuSpiceeArray[]");
String[] ItemQuantityArray = request.getParameterValues("ItemQuantityArray[]");
model.addObject("restaurantname", restaurantname);
model.addObject("amount", amount);
model.addObject("orderoption", orderoption);
model.addObject("date", date);
model.addObject("time", time);
model.addObject("menuitemsArray", menuitemsArray);
model.addObject("menuPriceArray", menuPriceArray);
model.addObject("menuSpiceeArray", menuSpiceeArray);
model.addObject("ItemQuantityArray", ItemQuantityArray);
return model;
}
}
Now Here is the Second Controller "OrderController":
#Controller
#RequestMapping("/welcome")
public class OrderController {
#Autowired
private OrderService orderService;
#RequestMapping("/getordercheckout/{response}")
public ModelAndView getOrderCheckOut(#PathVariable("response") ModelAndView response)
{
ModelAndView model = new ModelAndView("/getordercheckout");
model.addObject("response" , response);
System.out.println("Response : " +response);
return model;
}
Now here I want to get the response but I am not sure what will be the datatype of reponse.
The System.out.println prints this error:
ModelAndView: reference to view with name '[object Object]'; model is null
Please Help me out as I am new to the Spring MVC.
Thank You in advance.

Login and get information user with token in spring (no OAuth)

I am implementing a project RESTful API, it should login (username / password) and returns a token, I want to use token to retrieve user information.
I follow the instructions:
https://github.com/virgo47/restful-spring-security
But: I do not know how to use it in my function, you can help me with?
#RequestMapping(value = "/login", method = RequestMethod.POST)
public #ResponseBody ResponseObject<Object> login(
#RequestParam(value = "username", required = true) String username,
#RequestParam(value = "password", required = true) String password,
#RequestHeader(value = "token") String token,
HttpSession session) {
//TODO
return new ResponseObject<Object>(1, "Success", data);
}
#RequestMapping(value = "/info", method = RequestMethod.GET)
public #ResponseBody ResponseObject<User> getInfo(#RequestHeader(value = "token", required = true) String token,
HttpSession session) {
//TODO
return null;
}
Why would you want to do that ? Why not just get the logged in user from the SecurityContext as follows
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
System.out.println(" *** MainRestController.test");
// Spring Security dependency is unwanted in controller, typically some
// #Component (UserContext) hides it.
// Not that we don't use Spring Security annotations anyway...
return "SecurityContext: "
+ SecurityContextHolder.getContext().getAuthentication()
.getName();
}
If you insist on doing it, you can do the following.
UserDetails userDetails =
(UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
tokenManager.getUserTokens(userDetails)

Change url path in Spring MVC by #RequestMapping

Currently path is showing
http://localhost:8081/UserLogin/login
But i want this as
http://localhost:8081/UserLogin/index
or
http://localhost:8081/UserLogin/
My controller class is
#RequestMapping(value = "/login" ,method = RequestMethod.POST)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
//return "hi this is a test";
String userName = request.getParameter("data[Admin][user_name]");
String userPass=request.getParameter("data[Admin][password]");
int userId=userDAO.getUser(userName, userPass);
if(userId!=0){
String message = "welcome!!!";
return new ModelAndView("result", "message", message);
}
else{
String message = "fail";
return new ModelAndView("index", "message",message);
}
}
Want to change in else condition when not match.
Thanks in advance. :)
I would return a redirect to render the view under the new URL:
request.addAttribute("message",message) // better use a Model
return "redirect:/[SERVLET_MAPPING]/index";
It take some time to understand what you want: - I guess you want to alter the URL that is returned from the Server after login.
But this does not work this way, because the URL is requested from the browser and the server can not change them. Instead the server can respond an "HTTP 303 Redirect" (instead of the view). This cause the Browser to load the URL given with the Redirect.
#RequestMapping(value = "/login" ,method = RequestMethod.POST)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
//return "hi this is a test";
String userName = request.getParameter("data[Admin][user_name]");
String userPass=request.getParameter("data[Admin][password]");
int userId=userDAO.getUser(userName, userPass);
if(userId!=0){
return new ModelAndView(new RedirectView("/result", true)); // "/result" this is/become an URL!
}
else {
return new ModelAndView(new RedirectView("/index", true)); // "/index" this is/become an URL!
}
}
#RequestMapping(value = "/index" ,method = RequestMethod.GET)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
String message = "fail";
return new ModelAndView("index", "message",message); //"index" the the name of an jsp (or other template)!!
}
#RequestMapping(value = "/result" ,method = RequestMethod.GET)
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) {
String message = "welcome!!!";
return new ModelAndView("result", "message", message); //"result" the the name of an jsp (or other template)!!
}
#See http://en.wikipedia.org/wiki/URL_redirection

Resources