Invalid working of #springFormSingleSelect in velocity template - spring

I am making spring mvc application and using velocity templates for views.There is form for filling it by the data and in this form i am using #springFormSingleSelect.Form works fine when data is valid, but when form is filled by invalid data as mentioned there are messages with errors, but #springFormSingleSelect is empty.That's my view:
<form action="saveEmployee" method="POST">
#springBind("newEmployee")
#springMessage("label.back")
<p>
<table>
<tr>
<td>#springMessage("label.firstName")</td>
<td>#springFormInput("newEmployee.firstName" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.lastName")</td>
<td>#springFormInput("newEmployee.lastName" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.salary")</td>
<td>#springFormInput("newEmployee.salary" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.birthdate")</td>
<td>#springFormInput("newEmployee.birthday" "")</td>
<td><font color="red">#springShowErrors("&nbsp" "")</font></td>
</tr>
<tr>
<td>#springMessage("label.departament")</td>
<td>#springFormSingleSelect("newEmployee.departamentId" $departamentsMap "")</td>
</tr>
</table>
<input type="submit" value="#springMessage("label.submit")">
</form>
That's part of controller to the view:
#RequestMapping(value="/saveEmployee", method= RequestMethod.GET)
public ModelAndView newuserForm(){
ModelAndView model = new ModelAndView("newEmployee");
Employee empl = new Employee();
Map departamentsMap = new TreeMap();
List<Departament> departamentsList = service.listDepartaments();
//for singleselect of departaments
for(int i=0; i<departamentsList.size(); i++){
Departament dep = departamentsList.get(i);
departamentsMap.put(dep.getDepartamentId(),dep.getTitle() );
}
model.addObject("departamentsMap",departamentsMap);
model.getModelMap().put("newEmployee", empl);
return model;
}
#RequestMapping(value="/saveEmployee", method=RequestMethod.POST)
public String create(#ModelAttribute("newEmployee")Employee empl, BindingResult result){
employeeValidator.validate(empl, result);
if(result.hasErrors()){
return "newEmployee";
}
service.saveEmployee(empl);
return "redirect:/listEmployees";
}
Maybe someone knows the reason of that behavior?

departamentsMap is null at the time of Error...So please add model.addObject("departamentsMap",departamentsMap);
in your post detail ,So when eeror Occured it must not be null.
//Modified this line of code..
if(result.hasErrors()){
Map departamentsMap = new TreeMap();
List<Departament> departamentsList = service.listDepartaments();
//for singleselect of departaments
for(int i=0; i<departamentsList.size(); i++){
Departament dep = departamentsList.get(i);
departamentsMap.put(dep.getDepartamentId(),dep.getTitle() );
}
model.addObject("departamentsMap",departamentsMap);
return "newEmployee";
}

Related

JSP&Spring: How can I pass one parameter using JSP EL with submit button?

I'm trying to pass one parameter from a jsp page to Spring controller file.
However, I fail and fail again.
When I put just real data of database like a, b, c... instead of "${deleteList['user_id']}", my codes works well.
I have no idea.
I'd be appriciated if I can get your answer.
<table border="0">
<c:forEach items="${deleteList}" var="deleteList">
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td></tr>
</c:forEach>
</table> <form action="${pageContext.request.contextPath}/user/delete" method="get"> <input type="hidden" name="user_id" value="${deleteList['user_id']}" />
<input type="submit" name="confirm" value="Delete" />
#RequestMapping(value = "/delete", params="confirm", method = RequestMethod.GET)
public String deleteConfirm(Model model, HttpServletRequest req) {
String user_id=req.getParameter("user_id");
UmsDAO dao=sqlSession.getMapper(UmsDAO.class);
ArrayList<UVO> uvo = dao.deleteList(user_id);
model.addAttribute("deleteList", uvo);
return "user/deleteConfirm";
}
<c:forEach items="${deleteList}" var="deleteList">
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td></tr>
</c:forEach>
you are not sending any value in user_id..
<tr><td align="right">ID:</td><td>${deleteList.user_id}</td>
<td> from this try once.. you will get specific value what you want</td>
</tr>
Instead of using form every time use anchor tag and send value in partameter
Solution:
use HttpSession
For example:
#RequestMapping(value = "/delete", params = "confirm", method = RequestMethod.GET)
public String deleteConfirm(Model model, HttpServletRequest req) {
HttpSession session = req.getSession();
String user_id = (String) session.getAttribute("user_id");
UmsDAO dao = sqlSession.getMapper(UmsDAO.class);
ArrayList<UVO> uvo = dao.deleteList(user_id);
model.addAttribute("deleteList", uvo);
return "user/deleteConfirm";
}

How to pass checkbox values to the controller in Spring MVC

I have a jsp page with list of functions. Here in controller I get this list from database and pass it to jsp.
#RequestMapping(value = "/functionlist", method = RequestMethod.GET)
public ModelAndView functionList(Model model) throws Exception {
ModelAndView mv = new ModelAndView("functionList");
mv.addObject("functionList", getFunctionsFromDB());
return mv;
}
In my jsp page I create table using this list of functions
<table id="table">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:choose>
<c:when test="${not empty functionList}">
<c:forEach var="function" items="${functionList}">
<tr>
<td><input name="id" value="${function.id}" hidden></td>
<td>${function.name}</td>
<td>
<input type="checkbox" id="${function.id}" value="${function.action}"></td>
</tr>
</c:forEach>
</c:when>
</c:choose>
</tbody>
</table>
<button type="submit" name="save">Save</button>
I also give function id to checkbox id.
My Function entity is the following
public class Function {
private Integer id;
private String name;
private Boolean action;
...
}
I want to press button Save and get in controller "/functionlist/save" my list of checkbox values.
Try to add form like this to your jsp page
<form:form id="yourForm" action="/functionlist/save" method="POST" modelAttribute="functionList">
<c:forEach items="${functionList}" varStatus="status" var="function">
<tr>
<td>${function.name}</td>
<td>
<form:checkbox path="functionList[${status.index}].action"/>
</td>
</tr>
</c:forEach>
<input type="submit" value="submit" />
</form:form>
and in Controller you should have a method like this
#RequestMapping(value = { "/functionlist/save" }, method = RequestMethod.POST)
public String savePerson(#ModelAttribute("functionList")List<Function> functionList) {
// process your list
}
If this does not work, you can try to wrap you list.
public class FunctionListWrapper {
private List<Function> functionList;
public FunctionListWrapper() {
this.functionList = new ArrayList<Function>();
}
public List<Function> getFunctionList() {
return functionList;
}
public void setFunctionList(List<Function> functionList) {
this.functionList = functionList;
}
public void add(Function function) {
this.functionList.add(function);
}
}
in controller instead of passing list, pass wrapper
FunctionListWrapper functionListWrapper=new FunctionListWrapper();
functionListWrapper.setFunctionList(userService.getFunctionList());
mv.addObject("functionListWrapper", functionListWrapper);
For more details please take a look at this questions: question 1 and question 2
First you need to add name attribute to your checkbox inputs.You can get these in
an array on controller with same name as your name attribute.eg-
#RequestMapping(value = "/functionlist", method = RequestMethod.GET)
public ModelAndView functionList(Model model,#RequestParam("checkboxname")String[] checkboxvalues) throws Exception {
ModelAndView mv = new ModelAndView("functionList");
mv.addObject("functionList", getFunctionsFromDB());
return mv;
}
few things.
First you should think about a form object, which is the exchange entity between the view and the controller. The form entity will be something similar to the followng:
public class Form {
private List<Function> functions;
//getters & setters
}
secondly, since you are using Spring MVC, you should leverage the <%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %> library. Consequently, your form will be:
<form:form commandName="form" action="/your/url">
<c:forEach items="${form.functions }" var="function" varStatus="status">
<tr>
<td><form:hidden path="functions[${status.index }].id"></td>
<td>${function.name}</td>
<td>
<form:checkbox path="functions[${status.index }].action" id="${function.id}" value="${function.action}"/>
</td>
</tr>
</c:forEach>
</form:form>
and finally the controller will be something like
#RequestMapping(value="/your/url", method=RequestMethod.POST)
public String postForm(#ModelAttribute("form") FormForm form)
{
//cool stuff here
}
please note that the proper HTTP method is POST, not GET. Yup, I know things work also with GET it's definitely a deprecated strategy.
In addition, figure out how I referred the list of Function in the Form. I used the variable function in the foreach statement when I had to display data, I referred the list when I had to bind the Form object for transferring data to the controller. Last but not least, I haven't tried the code. I wrote it on the fly just to give you hints about how to do it properly.
One last thing. Since you pass the Form to the JSP, you don't need anymore to fill the Model with the attribute you used. Just fill the form with your data and use it to diaplay them in the view. Just like this ${form.stuff.you.want}

com.google.appengine.api.datastore.Text Data type unable to read in JSP Page

I am using hibernate + spring MVC. In My project there is one column in table such as :
#Column(name = "CLM_DSCRIPTION")
private Text desc;
And getter & setter Method for this
public Text getDesc() {
return desc;
}
public void setDesc(Text desc) {
this.desc = desc;
}
now i used this table in jsp where i want to show this column data into table.
M doing as below
<c:forEach items="${tbleObjs}" var="tbl" varStatus="status">
<tr>
<td>${status.index+1}</td>
<td class="labels2">${tbl.desc}</td>
</tr>
</c:forEach>
but it is not geting ${tbl.desc} here.
if i did desc.getValue() then it will work but i don't know, which is the best way to achieve this.
Please suggest me a better way.
i have achieve with following code :
<c:forEach items="${entityObjs}" var="tbl" varStatus="status">
<tr>
<%
Entity entityObj = (Entity)pageContext.getAttribute("tbl");
String disc = project.getDesc().getValue();
pageContext.setAttribute("disc",disc);
%>
<td>${status.index+1}</td>
<td class="labels2">${disc}</td>
</tr>
</c:forEach>

If you intend to handle the same path in multiple methods Spring

Im using spring MVC.
My Controller is :
#RequestMapping(value = "/approval/pendingescort", method = RequestMethod.GET)
public String getPendingEscort(Model model) {
log.debug("Received request to show Pending Escorts");
// Retrieve all pending escort details by delegating the call to Servicelayer
List<EscortRegistration> pendingEscortdetails = approvalService.getAllPendingEscort();
// Attach zones to the Model
model.addAttribute("pendingEscortdetails", pendingEscortdetails);
// This will resolve to /WEB-INF/jsp/pendingescort.jsp
return "pendingescort";
}
#RequestMapping(value = "/approval/pendingescort/success", method = RequestMethod.GET)
public String addEscort(#RequestParam(value="mobileno", required=true) String mobileno,Model model) {
log.debug("Received request to Accept Escort Request");
// Call ZonedetailsService to do the actual Updating
approvalService.approveEscortRequest(mobileno);
// Add mobile reference to Model
model.addAttribute("mobileno", mobileno);
// This will resolve to /WEB-INF/jsp/addedescortpage.jsp
return "pendingescort";
}
and my JSP Is :
<tbody>
<c:forEach items="${pendingEscortdetails}" var="escort">
<c:url var="editUrl" value="/efmfm/main/approval/pendingescort/success?mobileno=${escort.mobilenumber}" />
<c:url var="deleteUrl" value="/efmfm/main/approval/pendingescort/delete?mobileno=${escort.mobilenumber}" />
<tr>
<td><c:out value="${escort.mobilenumber}" /></td>
<td><c:out value="${escort.imei}" /></td>
<td> Approve
<!-- <td>Approve</td> -->
Reject
</td>
</tr>
</c:forEach>
</tbody
when i click to approve its sending to success page. i want to bring this to previous page with refresh.
Can any one solve my problem.
use
return "redirect:../../../approval/pendingescort";
Instead of
return "pendingescort";
First: I guess you need to use "../.."
return "redirect:../../../approval/pendingescort";
One more doubt. Are you using tiles??

How to handle IEnumerable with IGrouping in the view?

I am trying to send to the view an IEnumerable and to show every element in it but I have a problem when I send it. It says that:
{System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Linq.IGrouping<string,MvcApplication4.Models.USER>,<>f__AnonymousType8<string,int>>}
and I dont know how to handle it.
This is my view :
#model IEnumerable<dynamic>
I get dynamic because i go to this view from couple of functions how send different types.
<table border="1" style="text-align:center">
<tr>
<td> </td>
<td> user name </td>
<td>age </td>
<td>comments </td>
</tr>
#foreach (var t in (Model))
{
<tr>
<td>#(count++))</td>
<td> #Console.WriteLine(t)</td>
<td> </td>
<td> </td>
</tr>
}
</table>
I get the IEnumerable from this linq :
var allU = (from m in comList
join c in users on m.user equals c.user into cm1
from cm2 in cm1.DefaultIfEmpty()
group cm2 by m.user into grouped
select new { name = grouped.Key, count = grouped.Count() }).AsEnumerable();
So my question is really : how can I get the elements of it in the view?
You can't reference the type in your view because it is an anonymous type. Instead, define a type to store the results of your query:
public class Result
{
public string Name { get; set; }
public int Count { get; set; }
}
Then change your query to project into that type:
var allU = (from m in comList
join c in users on m.user equals c.user into cm1
from cm2 in cm1.DefaultIfEmpty()
group cm2 by m.user into grouped
select new Result { Name = grouped.Key, Count = grouped.Count() }).AsEnumerable();
Then you'll be able to bind to the type IEnumerable<Result> in your view.

Resources