#RequestMapping in spring 3.2.8 - spring

I have this controller in Spring Framework MVC application (version 3.2.8) with 2 different methods: 1 for the GET and the other one for the POST
#Controller
public class ManageAccountController {
private static final Logger LOGGER = Logger.getLogger (ManageAccountController.class);
//private static final String USER="userBean";
#Autowired
private UserService userService;
/**
*
* #param request the http servlet request.
* #param model the spring model.
*
*/
#RequestMapping(value = "/accounts/manageaccount.do", method = RequestMethod.GET)
public String showForm ( #ModelAttribute("dataAccountCommand") final DataAccountCommand dataAccountCommand,
BindingResult result,
HttpServletRequest request,
Model model,
Locale locale) {
dataAccountCommand.setUserBean(getUser(request));
return "registerAccountView";
}
#RequestMapping(value = "/accounts/saveaccount.do", method = RequestMethod.POST)
private String saveAccount ( #ModelAttribute("dataAccountCommand") final DataAccountCommand dataAccountCommand,
BindingResult result,
HttpServletRequest request,
Model model,
Locale locale) {
return "registerAccountView";
}
}
the point is that when I put this in the browser
http://127.0.0.1:7001/devices_admin/accounts/manageaccount.do
I am redirected to the jsp, but when I put
http://127.0.0.1:7001/devices_admin/accounts/saveaccount.do
I have this error
URL: /devices_admin/accounts/saveaccount.do
???error404.error???
calling it from a jsp gives me the same result:
<form:form commandName="dataAccountCommand"
name="dataAccountForm"
id="dataAccountForm"
method="post"
action="${pageContext.servletContext.contextPath}/accounts/saveaccount.do"
htmlEscape="yes">
</form:form>

You can not invoke a POST method directly from the URL bar of your Browser. If you put something in the URL bar you are invoking the GET mehtod.
Instead you have to create a page with a form
<form method="POST" action="http://127.0.0.1:7001/devices_admin/accounts/saveaccount.do">
...
</form>
Or you can install a REST client in your browser and make the call directly using the POST method.

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 !

Errors/BindingResult argument declared without preceding model attribute in spring 3.2.8

I have this controller, But i don't know why when I access to /accounts/manageaccount.do I got an error
public class ManageAccountController {
public static final Logger LOGGER = Logger.getLogger (ManageAccountController.class);
/**
*
* #param request the http servlet request.
* #param model the spring model.
*
*/
#RequestMapping(value = "/accounts/manageaccount.do", method = RequestMethod.GET)
public String showForm( #ModelAttribute("dataAccountCommand") final DataAccountCommand dataAccountCommand,
HttpServletRequest request,
BindingResult result,
Model model,
Locale locale) {
return "SHOW_VIEW";
}
Exception: org.springframework.web.bind.annotation.support.HandlerMethodInvocationException: Failed to invoke handler method [public java.lang.String fr.telecom.controller.accounts.ManageAccountController.showForm(fr.telecom.domain.formBeans.DataAccountCommand,javax.servlet.http.HttpServletRequest,org.springframework.validation.BindingResult,org.springframework.ui.Model,java.util.Locale)]; nested exception is java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!
You need to place the BindingResult parameter directly after the parameter that is annotated with #ModelAttribute. So changing your signature to:
#RequestMapping(value = "/accounts/manageaccount.do", method = RequestMethod.GET)
public String showForm(
#ModelAttribute("dataAccountCommand") final DataAccountCommand dataAccountCommand,
BindingResult result, // moved up!
HttpServletRequest request,
Model model,
Locale locale) {
return "SHOW_VIEW";
}
should do the trick.
See also: http://viralpatel.net/blogs/errorsbindingresult-argument-declared-without-preceding-model-attribute/

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 MVC Controller List<MyClass> as a parameter

I have a Spring MVC application. Jsp page contains form, which submitting.
My controller's method looks like:
#RequestMapping(value = "photos/fileUpload", method = RequestMethod.POST)
#ResponseBody
public String fileDetailsUpload(List<PhotoDTO> photoDTO,
BindingResult bindingResult,
HttpServletRequest request) {
// in the point **photoDTO** is null
}
My class is:
public class PhotoDTO {
private Boolean mainPhoto;
private String title;
private String description;
private Long realtyId;
//getters/setters
But, if I write the same method, but param is just my object:
#RequestMapping(value = "photos/fileUpload", method = RequestMethod.POST)
#ResponseBody
public String fileDetailsUpload(PhotoDTO photoDTO,
BindingResult bindingResult,
HttpServletRequest request) {
// Everething is Ok **photoDTO** has all fields, which were fielded on the JSP
What should I do in the situation? What if I have on Jsp many PhotoDTO objects (15) how can I recive all of them on the server part?
The page should pass the parameters for each PhotoDTO in the list back to the server in the appropriate format. In this case you need to use the status var to specify the index of each object in the list using the name attribute.
<form>
<c:forEach items="${photoDTO}" var="photo" varStatus="status">
<input name="photoDTO[${status.index}].title" value="${photo.title}"/>
<input name="photoDTO[${status.index}].description" value="${photo.description}"/>
</c:forEach>
</form>

Nested Velocity template with Spring formView

I have a Spring app that I'd like to add a login feature to. I'd like to put the login form in the header of the site. This means that it'll be included on several pages. When defining the controller that the form submits to, what do I specify as the formView?
Is it possible to specify the login template that's included in header (that's included in each head :-)) as the formView?
Thanks for the help. If anything is unclear than I'm happy to provide more details or show code.
Nevermind. I realized that it doesn't matter whether the Velocity template is included in another file. I added this to the template:
<form method="POST">
#springBind("credentials.*")
and my controller looks like this:
#Controller
public class SplashController implements Serializable {
protected final Log logger = LogFactory.getLog(getClass());
private static final long serialVersionUID = 7526471155622776147L;
#ModelAttribute("credentials")
public LoginCredentials getFormBean() {
return new LoginCredentials();
}
#RequestMapping(method = RequestMethod.GET)
public String showForm() {
logger.info("In showForm method of SplashController");
return "splash";
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(LoginCredentials credentials, BindingResult bindingResult) {
logger.info("In onSubmit method of SplashController");
logger.info("Username = " + credentials.getUsername());
logger.info("Password = " + credentials.getPassword());
ModelAndView modelAndView = new ModelAndView("home");
return modelAndView;
}
}
and it works.

Resources