I have used the #ModelAttribute annotation on a get method in my controller:
#ModelAttribute
public TSetTestEmp get(#RequestParam(required=false) String id) {
TSetTestEmp entity = null;
if (StringUtils.isNotBlank(id)){
entity = tSetTestEmpService.get(id);
}
if (entity == null){
entity = new TSetTestEmp();
}
return entity;
}
and have requested the TSetTestEmp info like this:
#RequiresPermissions("set:emp:tSetTestEmp:list")
#RequestMapping(value = {"list", ""})
public String list(TSetTestEmp tSetTestEmp, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<TSetTestEmp> page = tSetTestEmpService.findPage(new Page<TSetTestEmp>(request, response), tSetTestEmp);
// model.addAttribute("tSetTestEmp", tSetTestEmp); // fixed using this.
model.addAttribute("page", page);
return "modules/set/emp/tSetTestEmpList";
}
As beginning without the comment statement, the JSP code like below throw an exception:
<form:form id="searchForm" modelAttribute="tSetTestEmp" action="${ctx}/set/emp/tSetTestEmp/" method="post" class="form-inline">
<span>Employee Nameļ¼</span>
<form:input path="empName" htmlEscape="false" maxlength="64" class=" form-control input-sm"/>
</form:form>
Error
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'tSetTestEmp' available as request attribute
According to my debugging, the form:input tag causes this exception. If I use input tag and bind the value empName using ${tSetTestEmp.empName}, this page will show the right result.
If I want to use the form:input tag in my JSP page, the comment in the list method must be removed which means I must assign the Model manually.
#M. Deinum suggested me to fix the problem like this and it works:
#RequiresPermissions("set:emp:tSetTestEmp:list")
#RequestMapping(value = {"list", ""})
public String list(#ModelAttribute("tSetTestEmp") TSetTestEmp tSetTestEmp, HttpServletRequest request, HttpServletResponse response, Model model) {
Page<TSetTestEmp> page = tSetTestEmpService.findPage(new Page<TSetTestEmp>(request, response), tSetTestEmp);
model.addAttribute("page", page);
return "modules/set/emp/tSetTestEmpList";
}
But as I can see, the initial code without #ModelAttribute before method argument can also reach the instance returned by get method. However the JSP page just cannot reach it same as back-end do.
I'm totally confused about how this situation happens.
Thanks for reading till here :)
Any suggestion will help.
Related
I have been using ModelAndView as the object type in my controller to handle method to do data binding with front-end html form.Such as this:
#RequestMapping(value = "/postSth", method = RequestMethod.POST)
public ModelAndView postSomething(#RequestParam("name") String name){
ModelAndView model = new ModelAndView("displayPage");
model.addObject("name", name);
return model;
}
This method will allow me to bind the name and I can display the name to the displayPage.jsp after the POST method. displayPage is the JSP page name and by using the InternalResourceViewResolver from Spring framework.
Lately I have been using jQuery ajax function to pass the data to my controller, and I am working on method looks like this:
#RequestMapping(headers = "Content-Type=application/json", value = "/postSth", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public ModelAndView postSomething(#RequestBody String name){
ModelAndView model = new ModelAndView("displayPage");
model.addObject("name", name);
return model;
}
I noticed I can successfully grabbing the JSON string with this controller, but this method will not redirect my webpage to the displayPage and the data binding with .addObject no longer work.
Why it does not work? How do I change it to still allow me to direct to the displayPage.jsp? I understand I can do the redirect with javascript at front-end, but it is not what I want to do.
I understand your requirement as you trigger an ajax call but instead of loading the output of data to current jsp you need to populate it in new jsp.
I have had the similar requirement, I used jquery load() to implement it. It worked fine in my case. Basically its like a 3 step process;
Trigger Ajax call to the controller to get the required data to be loaded on new jsp.
use load() once required data is available to load the new jsp in current page.(you can use some div to load it, if you want to completely replace current page then empty the contents of current page and laod with new jsp)
Write javascript/jquery codes to manipulate the dom in new JSP which we rendered on previous step.
Below is the snippet of how it can be done.
#RequestMapping(headers = "Content-Type=application/json", value = "/postSth", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.OK)
public String postSomething(#RequestBody String name){
return model;
}
<div id='currentContent'>
<!--Existing content -->
</div>
var ajaxResult = '';
$.ajax({
type : POST,
url: "postSth",
async:false}).then(function(data){
//DIV ID here would be the ID which you need to have in your page to append the HTML content.
//if you want to completely reload the page then use the id where your current contents are displayed
//Inside your somenewjsp.jsp you can write your jquery codes to access the variable ajaxResult on document ready
ajaxResult = data;
$('#currentContent').load('/somenewjsp.jsp');
});
});
Please share your results on this approach.
I am submitting a form using jquery in my Spring mvc.
this is the jquery call to submit form.
function uploadJqueryFormForEdit(documentId){
alert("ccc");
$('#result').html('');
$("#editDocumentForm").ajaxForm({
success:function(data) {
alert("ddd");
$('#result').html(data);
alert("eee");
//getProjectSegment('documents','DocumentSegment',projectId);
$('#editDocumentForm').remove();
},
error:function(e){
alert(e.responseText);
$("#msgDiv").html('Error');
},
dataType:"text"
}).submit();
}
And this is the form that I'm going to submit.
<form action="cont/uploadEdit?documentId=15&projectId=2" name="editDocumentForm" id="editDocumentForm" enctype="multipart/form-data" method="post">
When i'm using one parameter in action url, eg.
action="cont/uploadEdit?documentId=15"
it works fine. but when i'm using two parameters as
action="cont/uploadEdit?documentId=15&projectId=2"
it doesn't call to controller method correctly(not hitting that method at all)
here is the controller method
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
why can't I use two parameters in action tag.?
this is the controller method that worked fine with first action
#RequestMapping(value = "cont/uploadEdit", method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
}
Add params = {"documentId", "projectId"} attribute to the RequestMapping annotation
#RequestMapping(value = "cont/uploadEdit", params = {"documentId", "projectId"}, method = RequestMethod.POST)
public #ResponseBody String uploadEdit(#ModelAttribute("sessionId") String sessionId,#RequestParam("documentId") int documentId,#RequestParam("projectId") int projectId,MultipartHttpServletRequest request, HttpServletResponse response, UploadedFile fileDetail,UserBean userbean,Model model) throws SessionException {
logger.info("uploadEdit");
found the error:
In the form that we are going to submit (in my case "editDocumentForm") there should be no any other input tags with the same name as in action url variables,
eg if there is something like this,
<input type="hidden" id="projectId" name="projectId" value="somevalue"/>
it will make conflicts. So make sure that no conflicts occur.
I have an object called Request which is the main object of my portal that stores all the information of a request, the user, their form selections, etc. How to I persist all the previous information in between the different forms? In each .GET I have to set the request object, and then in each .POST, the only information that is passed to it is what is in the forms on the .GET pages. So on each page I have to have hidden fields such as
<form:input path='requestId' style='display:none' />
<form:input path='currentUserId' style='display:none' />
<form:input path="step" style='display:none' />
I need these fields, and would also like to have the rest of the fields in the request object that are not on the form without having to repeat that for each and every field in my object.
#RequestMapping(value = "/review", method = RequestMethod.GET)
public ModelAndView showCorReview(#RequestParam(value = "requestId") String requestId,
#CookieValue(value = "EMP_ID", defaultValue = "168") int userId)
{
Request request = requestManager.getRequestById(Integer.parseInt(requestId));
request.setCurrentUserId(userId);
String pageTitle = "2.1: Initiate New Service Request -- (Review)";
ModelAndView mav = new ModelAndView();
mav.setViewName("newRequest/review");
mav.addObject("title", pageTitle);
mav.addObject("request", request);
mav.addObject("cpm", userManager.getUserById(request.getCpm()).getName());
return mav;
}
#RequestMapping(value = "/review", method = RequestMethod.POST)
public String saveReview(Request request, #RequestParam(value = "commentData", required = false) String[] additionalComments)
{
if (additionalComments != null)
commentLogManager.addCommentLog(additionalComments, request);
if (request.getRejectReason() == "")
{
request.setCpm(admin.getCPM(request.getContract()).getId());
request.setCor(admin.getCOR(request.getContract()).getId());
requestManager.updateRequest(request);
}
else
{
if (request.getSubmitType().equals("return"))
{
request.setNextStep(1);
requestManager.moveRequestToStep(request);
}
}
return worksheetUrl + request.getId();
}
Alternatately I could also in the .POST do the
Request request = requestManager.getRequestById(Integer.parseInt(requestId))
Then use setters on all the form fields, but again, I would prefer the data to actually persist on it's own without explicitly calling that.
#Tim, if I understood your requirement correctly, you have a sequence of forms and you would like to transfer information from one form to the next without having to hit a database or copy over request variables from one form to another. I could support #JB Nizel's suggestion of employing HTTP Session, but you may not want to make the session "heavy"; after all, it is the next most persistent scope after application-scope.
Spring Web Flow may be the answer. Flow-scope will allow you to build up form-state as the user progresses from one form to the next. Plus you don't have to worry about form-scoped variables when the flow finishes, unlike session variables that you don't want to have lingering around.
An item is displayed at this URL:
/item/10101
using this Controller method:
#RequestMapping(value = "/item/{itemId}", method = RequestMethod.GET)
public final String item(HttpServletRequest request, ModelMap model,
#PathVariable long itemId)
{
model = this.fillModel(itemId);
return "item";
}
The page contains a form that submits to the following method in the same controller:
#RequestMapping(value = "/process_form", method = RequestMethod.POST)
public final String processForm(HttpServletRequest request,
#ModelAttribute("foo") FooModel fooModel,
BindingResult bindResult,
ModelMap model)
{
FooModelValidator validator = new FooModelValidator();
validator.validate(FooModel, bindResult);
if (bindResult.hasErrors())
{
model = this.fillModel(fooModel.getItemId());
return "item";
}
return "account";
}
If the validator finds errors in the form, it redisplays the item but instead of displaying it at the original url:
/item/10101
it displays it at its own url:
/process_form
Is it possible to redisplay the form at the original URL?
/item/10101
(I've tried getting the referrer and redirecting to it in processForm but then all of the model contents end up displayed as URL name/value pairs:)
#RequestMapping(value = "/process_form", method = RequestMethod.POST)
public final String processForm(HttpServletRequest request,
#ModelAttribute("foo") FooModel fooModel,
BindingResult bindResult,
ModelMap model)
{
String referrer = request.getHeader("referer");
FooModelValidator validator = new FooModelValidator();
validator.validate(FooModel, bindResult);
if (bindResult.hasErrors())
{
model = this.fillModel(fooModel.getItemId());
return "redirect:" + referrer;
}
return "account";
}
Short answer: No.
What happens is a server-side redirect (forward), which is within the same request, and so the submitted values are preserved (and displayed in the form)
The url will change if you use a client-side redirect (return "redirect:item";), but in that case a new request will come and the submitted values will be lost.
But here are two options that you have:
use the same URL in the mappings for both methods and distinguish them based on request method - GET for the former, POST for the latter. This might be confusing, so document it.
find / implement flash scope for spring-mvc. There's nothing built-in. The flash scope means that values are preserved (in the session usually) for a submit and the subsequent redirect. This option includes the manual handling, by putting the submitted object in the session, and later retrieving & removing it
I have this scenario:
I display a list of assets to users.
User selects an asset and then clicks add item
On my requestmapping, during GET operation. I use the service class to check if indeed this asset still exist in DB
If not, user should be notified by a message. I use the form:error tag
My problem is when I add the error object in the method signature, I got this error:
Errors/BindingResult argument declared without preceding model attribute
Code:
#RequestMapping(value = "/addItemsToAsset.htm", method = RequestMethod.GET)
public String setupForm(#RequestParam("assetID") Long assetID,
Errors error, ModelMap model) {
AssetItemVo voAsset = null;
if (assetID != null && assetID != 0) {
//Get data for asset from DB using assetID
List<AssetDraftTempVo> lstDraft = service.getAssetDraftByLngID(assetID);
if (lstDraft.size() == 0) {
voAsset = new AssetItemVo();
// I wanted to add validation here. If no data for asset id is found, I would like to add an error to the error object
error.reject("123","Unable to find info for the asset in the database.");
} else {
AssetDraftTempVo voDraft = lstDraft.get(0);
voAsset = new AssetItemVo();
voAsset.setStrPlant(voDraft.getStrPlant());
.
. /*other DTO property here*/
.
}
}
model.put("assetItemDetail", voAsset);
return "additemstoasset";
}
My goal is that during the display of the form, I wanted to populate the error object right away (if there is an error)
Here's my form for clarity.
<form:form modelAttribute="assetItemDetail" method="post">
<div id="error_paragraph">
<form:errors path="*" cssClass="errors" />
</div>
</form:form>
To get past the error, I manually change the method signature and added the model attribute but it still cannot populate the form:error tag
#RequestMapping(value = "/addItemsToAsset.htm", method = RequestMethod.GET)
public String setupForm(#RequestParam("assetID") Long assetID,
#ModelAttribute("assetItemDetail") AssetItemVo voAssetData, Errors error,
ModelMap model)
If you want to associate a BindingResult with a model attribute that doesn't present in the method signature, you can do it manually:
BindingResult result = new Errors();
...
model.put(BindingResult.MODEL_KEY_PREFIX + "assetItemDetail", result);
model.put("assetItemDetail", voAsset);
Spring MVC needs to associate a bunch of errors with some objects on the model, so tags such as <form:errors path="..." /> will correspond to model objects according to the path attribute. In this case, it does so by looking for the Errors argument directly after the ModelMap argument in your controller method.
Try swapping the error and model method arguments and see if it clears up the "Errors/BindingResult argument declared without preceding model attribute" error.
Change this:
public String setupForm(#RequestParam("assetID") Long assetID,
#ModelAttribute("assetItemDetail") AssetItemVo voAssetData, Errors error,
ModelMap model)
to this:
public String setupForm(#RequestParam("assetID") Long assetID,
#ModelAttribute("assetItemDetail") AssetItemVo voAssetData, ModelMap model,
Errors error)