405 error while using POST method in Spring + google app engine - spring

Whenever I try to use method post I am getting 405 error. The get method is working properly. I tried changing the type by using ajax. but it didn't work. Please help
#Controller
public class PaymentController {
#Autowired
private IAccountService accountService;
#RequestMapping(value = "/payment", method = RequestMethod.POST)
public String returnAccountInformation(HttpSession session, Model model) {
String email = (String) session.getAttribute("email");
PlanInfo planInfo = getAccountService().getPlanInfo(email);
PlanInfoBean planInfoBean = new PlanInfoBean();
planInfoBean.setPlanName(planInfo.getPlanName());
planInfoBean.setPlanType(planInfo.getPlanType());
planInfoBean.setFeatures(planInfo.getFeatures());
model.addAttribute(IPaymentConstants.PLANINFO2, planInfoBean);
// System.out.println(session.getAttribute("email"));
return "AccountDetails";
}

Related

Root url "/" of the homepagecontroller gives http error 404

I have defined a controller using:
#Controller
#RequestMapping("/")
public class HomePageController {
#RequestMapping(method = RequestMethod.GET)
public String home(#RequestParam(value = "logout", defaultValue = "false") final boolean logout, final Model model, final RedirectAttributes redirectModel, final HttpServletRequest request, final HttpServletResponse response) {
System.out.println("testing");return "homepage";
}
The control doesnt even come to the home method defined here and gives the response:
HTTP Status 404 – Not Found
However when I change the request mapping to #RequestMapping("/test"), I am able to get control in the home method defined above.
Why am I not able to hit the controller when the request mapping is defined with "/"? I need the root url to land me on the homepage.
Try this
Remove #RequestMapping("/") above HomePageController and add above specific method signature like below
public class HomePageController {
#RequestMapping(method = RequestMethod.GET,path="/")
public String home(#RequestParam(value = "logout", defaultValue = "false")....
}
Should work !

How can I correctly set a SessionAttribute into a Spring MVC Controller class and retrieve and use it into another Controller class?

I am pretty new in Spring MVC and I have the following problem.
Into an home() controller method defined into a class named **HomeController I retrieve an object using a service. This object have to be put as Session Attribute so it can be used from other methods in other controller classes.
So I have done in this way:
#Controller
#SessionAttributes({"progettoSelezionato"})
#PropertySource("classpath:messages.properties")
public class HomeController {
private static final Logger logger = Logger.getLogger(LoginController.class);
private #Autowired HomeService homeService;
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model) {
List<Tid023Intervento> listaInterventi = homeService.getListaInterventiRUP(18);
model.addAttribute("progettoSelezionato", listaInterventi.get(0));
model.addAttribute("listaProgettiRUP", listaInterventi);//TODO
return "home";
}
}
As you can see I have used this annotation on the class level:
#SessionAttributes({"progettoSelezionato"})
and then I put this object by:
model.addAttribute("progettoSelezionato", listaInterventi.get(0));
I am not sure that this is correct because, from what I know, this put the retrieved listaInterventi.get(0) object into the model with the voice progettoSelezionato. So I am absolutly not sure that it is putted as SessionAttributes.
Then, after that this object is putted as SessionAttriibute I have to retrieve and use if from a gestioneDatiContabiliEnte() method defined into another controller class, so I am doing in this way:
#Controller
#SessionAttributes({"progettoSelezionato"})
#PropertySource("classpath:messages.properties")
public class GestioneDatiContabiliEnteController {
private static final Logger logger = Logger.getLogger(LoginController.class);
#RequestMapping(value = "/gestioneDatiContabiliEnte", method = RequestMethod.GET)
public String gestioneDatiContabiliEnte(Model model) {
System.out.println("INTO gestioneDatiContabiliEnte()");
System.out.println("PROGETTO SELEZIONATO: " + progettoSelezionato);
return "gestioneDatiContabiliEnte/gestioneDatiContabiliEnte";
}
}
But it seems can't work because Eclipse sign me error on this line:
System.out.println("PROGETTO SELEZIONATO: " + progettoSelezionato);
The error is: progettoSelezionato cannot be resolved to a variable.
How can I correctly put the listaInterventi.get(0) as SessionAttribute into my HomeController? And how can I retrieve and use it into the gestioneDatiContabiliEnte() method defined into my GestioneDatiContabiliEnteController class?
Soled by myself, I can access to this object by:
model.asMap().get("progettoSelezionato");

Why Spring REST do not analyze "get","post" methods with same url

I am using spring rest , I have two methods
#RequestMapping(value="/",method = RequestMethod.POST)
public #ResponseBody
Object test1(HttpServletRequest request) {}
#RequestMapping(value="/",method = RequestMethod.GET)
public #ResponseBody
Object test2(HttpServletRequest request) {}
But it is not able to detect the two methods. Is it necessary that the URL should be different for each http method in spring.
Spring can support GET and POST for the same url. I've done it many times. For example (this is POST and PUT, but it's the same difference):
#Controller
#RequestMapping(value="player")
public class PlayerController {
#Autowired
private PlayerService playerService;
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public Player createNewPlayer(#RequestBody Player player) {
return playerService.createNewPlayer(player);
}
#RequestMapping(method = RequestMethod.PUT)
#ResponseBody
public Player updatePlayer(#RequestBody Player player) {
return playerService.updatePlayer(player);
}
}
If you can post the error message you're getting, maybe we can help you figure out what's wrong.
I am bit late but i might be useful for someone who still wants to know this concept. In below code we will be getting the error: java.lang.IllegalStateException: Ambiguous mapping.Cannot map 'XXX' method.
#RequestMapping(value="/",method = RequestMethod.POST)
public #ResponseBody
Object test1(HttpServletRequest request) {}
#RequestMapping(value="/",method = RequestMethod.GET)
public #ResponseBody
Object test2(HttpServletRequest request) {}
this error occurs because RequestHandlerMapper delegates the request on the basis of pattern of URL only and not on the method type.Hence if we have the same URL pattern, handlermapping will fail to distinguish that to which method it should map because of ambiguity.

Passing json object to spring mvc controller using Ajax

I am trying to send a json via Ajax request to a Spring mvc controller without success.
The json string has the following form:
{"Books":
[{'author':'Murakami','title':'Kafka on the shore'},{'author':'Murakami','title':'Norwegian Wood'}]}
The controller that parses the json wraps it through this java bean:
class Books{
List <Map<String, String>> books;
//...get & set method of the bean
}
The controller method has the following form:
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody Books books){....}
Unfortunately this does not work, I get the following error when invoking the method:
"Null ModelAndView returned to DispatcherServlet with name..."
Where am I getting wrong?
Thank you in advance!
Regards
create a Model class
class Books
{
private string author;
private string title;
// gets and sets
}
And Also create Wrapper class like this
class BookWrapper{
private List<Books> Books; // this name should matches the json header
}
Now in controller
#RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }, value = "/checkBook.do")
public ModelAndView callCheckBook(
#RequestBody BookWrapper Books){....}
in Ajax call create a seralizeArray of you forum this will give you json object and then it will bind to the wrapper class

Spring #PathVariable integration test

I'm trying ot write an integration test for one of my methods, that handles a form submission.
The problem is that i use #PathVariable int id in the #RequestMapping of my controller.
I get the following error message when my test method reaches the .handle() part.
nested exception is java.lang.IllegalStateException: Could not find #PathVariable [id] in #RequestMapping
So the controller cant reach the id. I'm using request.setRequestURI("/url-" + s.getId()); But appareantly its not helping with setting up #PathVariable.
Is there any way to set up the #PathVariable of my Mock object?
Update:
Yeah, im useing MockHttpServletRequest and annotationMethodHandlerAdapter.handle in my test class.
The Controller:
#RequestMapping(method = RequestMethod.POST, params = {"edit" })
public String onSubmit(#ModelAttribute("sceneryEditForm") SceneryEditForm s,
#PathVariable int id, Model model) {
// some code that useing id
}
The test method:
#Test
public void testEditButton() throws Exception {
MyObject s = new MyObject();
request.setMethod("POST");
request.setRequestURI("/edit-" + s.getId());
request.setParameter("edit", "set");
final ModelAndView mav = new AnnotationMethodHandlerAdapter()
.handle(request, response, controller);
assertViewName(mav, "redirect:/view-" + s.getId());
}
The error is correct: there is no path variable id
You need to add the path expression with an placeholder id
#RequestMapping(value = "/something/{id}",
method = RequestMethod.POST,
params = {"edit" })
public String onSubmit(#ModelAttribute("sceneryEditForm") SceneryEditForm s,
#PathVariable int id, Model model) {
// some code that useing id
}

Resources