How to show set of Arrays in one <TD> in Spring Boot / JSP? - spring-boot

I would like to show all the right answers(Green) in one TD if there are more than one and all the wrong answers(Red) in one TD if there are more than one. Is there anyway in the controller or at the front end that I can achieve this?
With my current code this is what I get.
The aim is to display like this
Controller
#GetMapping("/quesInAss/{id}")
public String quesInAssessment(#PathVariable("id") Integer id, Model model, HttpSession session) {
Integer insId = (Integer) session.getAttribute("instId");
List<Answers> rlist = new ArrayList<Answers>();
List<Answers> wlist = new ArrayList<Answers>();
Assessments ass = as.getAllByAssInst(id, insId);
model.addAttribute("assName", ass.getAssName());
List<Questions> queslist = qs.getQuesByAssessment(ass);
for (Questions ques : queslist) {
List<Answers> anslist = ansService.getAnswersByQuestion(ques);
for (Answers answer : anslist) {
if (answer.getAnsStatusCode().equals("CORR")) {
rlist.add(answer);
Answers[] array = new Answers[rlist.size()];
array = rlist.toArray(array);
model.addAttribute("rightAnsList", array);
} else {
wlist.add(answer);
Answers[] array = new Answers[wlist.size()];
array = wlist.toArray(array);
model.addAttribute("wrongAnsList", array);
}
}
}
model.addAttribute("queslist", queslist);
return "listOfQuesInAss";
}
JSP
<c:forEach items="${queslist}" var="ques">
<tr>
<td>${ques.quesText}</td>
<c:forEach items="${rightAnsList}" var="rightans">
<c:if test="${rightans.questions.quesId == ques.quesId}">
<td>${rightans.answer}</td>
</c:if>
</c:forEach>
<c:forEach items="${wrongAnsList}" var="wrongans">
<c:if test="${wrongans.questions.quesId == ques.quesId}">
<td>${wrongans.answer}</td>
</c:if>
</c:forEach>
</tr>
</c:forEach>

I'm not sure if I could understand your question right, try this:
<c:forEach items="${queslist}" var="ques">
<tr>
<td>${ques.quesText}</td>
<td>
<c:forEach items="${rightAnsList}" var="rightans" varStatus="status">
<c:if test="${rightans.questions.quesId == ques.quesId}">
${rightans.answer}
</c:if>
<c:if test="${not status.last}">,</c:if>
</c:forEach>
</td>
<td>
<c:forEach items="${wrongAnsList}" var="wrongans" varStatus="status">
<c:if test="${wrongans.questions.quesId == ques.quesId}">
${wrongans.answer}
</c:if>
<c:if test="${not status.last}">,</c:if>
</c:forEach>
</td>
</tr>
</c:forEach>

Related

The server encountered an unexpected condition that prevented it from fulfilling the request

I am trying to display Data from DB.But Shows error as
The server encountered an unexpected condition that prevented it from
fulfilling the request
Exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/pages/Detail.jsp at line 14
11: </head>
12: <body>
13:
14: <c:forEach var="x" items="${prdt}">
15: <table>
16: <img src="resources/Images/${x.id}.png"/>
17: <td>"
MY JSP
<c:forEach var="x" items="${prdt}">
<table>
<img src="resources/Images/${x.id}.png"/>
<td>
<c:out value="${x.product_Name}"/></td>
<td>
<c:out value="${x.descripction}"/></td>
<td>
<c:out value="${x.price}"/></td>
<td>
<c:out value="${x.mfg_Date}"/>
</td>
</table>
</c:forEach>
My Controller
public ModelAndView productDtails(#PathVariable int id)
{
ModelAndView model=new ModelAndView("Detail");
model.addObject("prdt",pd.getById(id));
return model;
}
My DAO IMpl
public Product getById(int id)
{
Session session=sessionFactory.openSession();
Product p=(Product) session.get(Product.class, id);
session.close();
return p;
}
Any Idea????
You can't iterate over prdt object i.e., you are using forEach tag and prdt is not a List object, so to solve the issue simply remove <c:forEach var="x" items="${prdt}"> or else you need to return a list object from your Contoller.
Your JSP looks as below (after removing <c:forEach):
<table>
<img src="resources/Images/${x.id}.png"/>
<td>
<c:out value="${prdt.product_Name}"/></td>
<td>
<c:out value="${prdt.descripction}"/></td>
<td>
<c:out value="${prdt.price}"/></td>
<td>
<c:out value="${prdt.mfg_Date}"/>
</td>
</table>
My issue was resolved by adding the below in the model
[AllowHtml]
public string Description { get; set; }
C# MVC for POST

ModelAttribute not working with lists in spring

I want to bind a List using ModelAttribute. The list contains objects of type Transaction each of which contains transactionid (type int). This is my controller code:
#RequestMapping(value = "/approvecreditdebit.do", method = RequestMethod.POST)
public ModelAndView doActions(HttpServletRequest request,
#ModelAttribute("clc") Clc transactionList, BindingResult result,
ModelMap model) {
/*
* switch (action) { case "approve":
*/
System.out.println("Obj = " + transactionList.getClass());
System.out.println("Val = " + transactionList.getTransactionList());
Users users = new Users();
return new ModelAndView("internal","internal",users);
}
This is my jsp code:
<form:form action="approvecreditdebit.do" method="POST"
modelAttribute="clc">
<table border="1">
<tr>
<th>no</th>
<th>ID</th>
</tr>
<c:forEach items="${clc.transactionList}"
var="transaction" varStatus="status">
<tr>
<td>${status.index}</td>
<td><input name = "transaction[${status.index}].transactionId"
value="${transaction.transactionId}" /></td>
</tr>
</c:forEach>
</table>
<br>
<br>
<center>
<input type="submit" value="approve" />
</center>
</form:form>
This is the Clc class:
public class Clc{
private List<Transaction> transactionList;
public List<Transaction> getTransactionList() {
return transactionList;
}
public void setTransactionList(List<Transaction> transactionList) {
this.transactionList = transactionList;
}
}
The value of transactionList is not being set to the values received from the form. I receive the following error:
Request processing failed; nested exception is java.lang.NullPointerException
I tried searching for the solution on google and got a lot of solutions from stackoverflow but none of them seem to work.
Try something like this (notice the use of <form:input>). I just tried it on a simple Spring MVC app and it works (list is not null and has the values from the form when I try to access it in my POST method).
<c:forEach var="transaction" varStatus="status" items="${clc.transactionList}">
<tr>
<td>${status.index}</td>
<td><form:input path="transactionList[${status.index}].id" /></td>
</tr>
</c:forEach>

is it possible to add buttons dynamically and pass their values accordingly?

I am new to spring technology please help to solve this problem.
I am developing a web application in spring in which I have a leaveRecords.jsp page,and It should load following things,
For each records the page should display records into the table with two buttons like
<button id="Accept"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
<button id="Reject"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id()/>
After clicking on accept button relevant action will be performed and should redirect to same page but this time the page should contain button like
<button id="Cancel"
name="action"
type="submit"
value="Accept<%= dtoBean.getEmployee_id() />
the leaveRecords.jsp is:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<% CommonDTOBean dtoBean=(CommonDTOBean)session.getAttribute("dtoBean");
List upcomingLeavesList=(ArrayList)session.getAttribute("upcomingLeavesList");%>
<table ><col><thead ><tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<%if(upcomingLeavesList!=null){
for(int i=0;i<upcomingLeavesList.size();i++){
dtoBean=(CommonDTOBean)upcomingLeavesList.get(i);%>
<tr>
<td ><span><%= dtoBean.getEmployee_id() %></span></td>
<td ><span><%= dtoBean.getNo_of_leave() %></span></td>
<td ><span></span><%= dtoBean.getFromDate() %>-<%= dtoBean.getToDate() %></td>
<td > <span><%= dtoBean.getLeaveType() %></span></td>
<td ><span></span><%= dtoBean.getLeavePeriod() %></td>
<td><span></span><%= dtoBean.getAppliedLeave() %></td>
<td><span></span><%= dtoBean.getLeaveStatus() %></td>
<td><button id="btnAccept" name="action" type="submit" value="Accept<%= dtoBean.getEmployee_id() %>" onclick="">Approve</button></td>
<td><button id="btnReject" name="action" type="submit" value="Reject<%= dtoBean.getEmployee_id() %>">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel<%= dtoBean.getEmployee_id() %>">Cancel</button></td>
</tr>
<%}}%>
</tbody>
</table>
</form:form>
Controller class is:
public String ApproveLeaves(#RequestParam(required=false , defaultValue="")String aion,#RequestParam(required=false,defaultValue="")String Cancel,HttpServletRequest request, HttpServletResponse response, ModelMap model){
try{
//following strings are used for getting the value of button and spiting it to get employee id
String buttonName=request.getParameter("action");
String buttonValue=buttonName.substring(0,6);// here we are spliting up the string and button name
int buttonValue1=Integer.parseInt(buttonName.substring(6));
if (buttonValue.equalsIgnoreCase("Reject"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Cancel"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
if (buttonValue.equalsIgnoreCase("Accept"))
{
boolean status=LeaveStatusWorker.Approve(buttonValue1,buttonValue,dtoBean);
if (status)
{
return "redirect: GlobalConstants.UPCOMING_LEAVES";
}
}
return GlobalConstants.UPCOMING_LEAVES;
}
catch(Exception e)
{
System.out.println(e);
}
return GlobalConstants.ERRORPAGE;
}
service class has a method for db interaction:
public static boolean Approve(int id,String buttonValue,CommonDTOBean dtoBean2)
{
try {
con=DBConnection.getConnection();
String query="select no_of_leave from newemp_register where emp_id=?";//get available leaves from db
pstmt.executeQuery();
if(buttonValue.equalsIgnoreCase("Cancel"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
}
if(buttonValue.equalsIgnoreCase("Reject"))
{
return true;
}
if(buttonValue.equalsIgnoreCase("Accept"))
{
String approve="Update newemp_register set no_of_leave=? where emp_id=?";
pstmt.executeUpdate();
return true;
}
}
}//End Of while
} catch (Exception e) {
}
return false;
}//End of Approve
Please go through this example and help me I have tried very hard and searched on Google but could not solve it.
CommonDTOBean class:
public class CommonDTOBean {
private int emp_id;
private String Status;
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
Use JSTL for conditional rendering the DOM in jsp. like:
<form:form method="POST" action="upcomingLeaves.do" commandName="loginForm" modelAttribute="loginForm">
<table>
<thead>
<tr style="background-color:#666633;">
<th>Employee id</th>
<th>Leave Balance</th>
<th>Date</th>
<th>Leave Type</th>
<th>Leave Period</th>
<th>Applied Leaves</th>
<th>Status</th>
<th colspan="4">Action</th>
</tr></thead>
<tbody>
<c:choose>
<c:when test="${not empty upcomingLeavesList}">
<c:forEach items="${upcomingLeavesList}" var="upComLeave">
<tr>
<td><span>${upComLeave.emp_id}</span></td>
<td><span>${upComLeave.status}</span></td>
<td><span>${upComLeave.fromDate} - ${upComLeave.toDate}</span></td>
<td><span>${upComLeave.leaveType}</span></td>
<td><span>${upComLeave.leavePeriod}</span></td>
<td><span>${upComLeave.appliedLeave}</span></td>
<td><span>${upComLeave.leaveStatus}</span></td>
<c:if test="${upComLeave.leaveStatus ne 'accepted' }"> //check status if accepted, don't render Accept button
<td><button id="btnAccept" name="action" type="submit" value="Accept${upComLeave.emp_id}" onclick="">Approve</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus ne 'rejected' }">//check status if accepted, don't render Reject button
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
</c:if>
<c:if test="${upComLeave.leaveStatus eq 'cancel' }">//check status if cancel, render cancel button
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
</tr>
</c:forEach>
</c:when>
<c:otherwise>
upcomingLeavesList is empty or null..
</c:otherwise>
</c:choose>
</tbody>
</table>
</form:form>
Edit 1(based on comments):
If I click on approve the page should redirect with only Cancel and
Reject button
use one more if condition like:
<c:if test="${upComLeave.leaveStatus eq 'accepted' }">
<td><button id="btnReject" name="action" type="submit" value="Reject${upComLeave.emp_id}">Reject</button></td>
<td><button id="btnCancel" name="action" type="submit" value="Cancel${upComLeave.emp_id}">Cancel</button></td>
</c:if>
Note:
add this on top of jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

How to send back the model data from jsp to controller

I have a controller which sets few values to a model and sends to jsp. In jsp i need to show those values(as labels) along with additional values from user as input values. When i submit the jsp i only get valid values that user has entered and the values set earlier by controller is null.
JSP
<form:form
action="${pageContext.request.contextPath}/admin/deviceAction.html"
modelAttribute="deviceData">
<table class="gridtable" width="500px">
<tr>
<td>Device Name : </td>
<td>${deviceData.deviceName}</td>
</tr>
<tr>
<td>Model Name : </td>
<td>${deviceData.modelName}</td>
</tr>
<tr>
<td>Serial No : </td>
<td>${deviceData.serialNo}</td>
</tr>
<tr>
<td>Device Id : </td>
<td>${deviceData.deviceId}</td>
</tr>
<tr>
<td>Status : </td>
<td>${deviceData.statusCode}</td>
</tr>
<tr>
<td>Action : <span class="required">*</span></td>
<td>
<form:select path="deviceAction" >
<form:option value="" label="--- Select ---" />
<form:options items="${model.actionList}" />
</form:select>
</td>
</tr>
</table>
<input type="submit" value="Submit" id="btn_submit">
</form:form>
Controller:
public ModelAndView beforeSubmit() {
ModelAndView modelView = new ModelAndView();
DeviceData deviceData = new DeviceData();
deviceData.setDevicePk("123");
deviceData.setAccessToken("abcwetrwertewrtetr");
deviceData.setDeviceId("deferterterterterwtetetertg");
deviceData.setDeviceName("test");
deviceData.setEnrolledDate("7-8-13");
deviceData.setModelName("test1");
deviceData.setSerialNo("test2dsfgdfgdfg");
deviceData.setStatusCode("test3");
List<String> actionList = getActionList();
Map<String, List<String>> model = new HashMap<String, List<String>>();
model.put("actionList", actionList);
modelView.addObject("deviceData", deviceData);
modelView.addObject("model", model);
modelView.setViewName("admin/tokenSearchResult");
}
public ModelAndView afterSubmit() {
#ModelAttribute("deviceData") DeviceData deviceData, BindingResult result) {
logger.info("#################device datas are : " + deviceData.getDevicePk() + "###### " + deviceData.getDeviceAction());
return new ModelAndView();
}
deviceData.getDevicePk() is null
Only the drop down value is having valid value. Other values displayed in the screen are received as null.
Edit:
Till now i have found only one solution:
<form:input path="deviceName" readonly="true" />
But this way UI does not looks good. The editable and non editable values mixup in the screen. Looking for a better answer
Finally i am using hidden parameters to solve the problem.
Example:
<td>${deviceData.deviceName}</td>
is replaced by:
<td><form:hidden path="deviceName"</td>
By this way it helps me to avoid any css work(which i am not much comfortable)
If anyone get a better solution kindly post it here
You need to make them into form inputs using the Spring form tags in much the same way as you have for the form:select. If they are not editable by the user, you can always disable them.
You can simple hide those input. For example :
<input type="hidden" name="VehSeriesModelId" value="${vehDetailsVM.id }">
This way, you can get the data to the controller and the user will also not be able to edit the value. On the other hand, your form will also not show it :)

how to get the element of a list inside jsp using JSTL?

I have such this code inside my Spring MVC java controller class:
#RequestMapping(value = "jobs", method = { RequestMethod.GET })
public String jobList(#PathVariable("username") String username, Model model) {
JobInfo[] jobInfo;
JobStatistics js;
LinkedList<JobStatistics> jobStats = new LinkedList<JobStatistics>();
try {
jobInfo = uiClient.getJobs(username);
for (int i = 0; i < jobInfo.length; i++) {
js = uiClient.getJobStatistics(jobInfo[i].getJobId());
jobStats.add(js);
}
model.addAttribute("jobs", jobInfo);
model.addAttribute("jobStats", jobStats);
}
which uiClient will get some data from database using RMI ...
now I want to show the jobs & related statistic inside my JSP file using JSTL :
<c:set var="stats" value="${jobStats}" />
<c:forEach var="jobs" items="${jobs}">
<c:set var="jobID" value="${jobs.JobId}"/>
<table>
<tr class="tr1">
<td>${jobs.Topic}</td>
<td>${stats.get(i).No}</td>
</tr>
</table>
</c:forEach>
How do I get the LinkedList elements of Model inside my JSP using JSTL? There might be no no counter i been put in scope for me.
In my opinion, the right answer is a combination of both of the answers you got:
use varStatus attribute of c:foreach tag
but:
"get" is not a jstl function.
<c:forEach var="jobs" items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs.jobId}"/>
<table>
<tr class="tr1">
<td>${jobs.topic}</td>
<td>${stats[i.index].no}</td>
</tr>
</table>
</c:forEach>
EDIT: this is the code finally used by the author of the question:
<c:set var="stats" value="${jobStats}" />
<c:forEach items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs[i.index].jobId}"/>
<table>
<tr class="tr1">
<td>${jobs[i.index].topic}</td>
<td>${stats[i.index].no}</td>
<td>${jobID}</td>
</tr>
</table>
</c:forEach>
get is not a jstl function.
<td>${stats[i.index].No}</td>
use varStatus attribute of c:foreach tag
<c:forEach var="jobs" items="${jobs}" varStatus="i">
<c:set var="jobID" value="${jobs.JobId}"/>
<table>
<tr class="tr1">
<td>${jobs.Topic}</td>
<td>${stats.get(i.index).No}</td>
</tr>
</table>
</c:forEach>

Resources