I have a success.jsp page which displays multiple rows and columns with an Edit button and a checkbox for each row. If the user clicks on Edit button, the checkbox is selected.
Below is success.jsp :
<%#page import="mymvc.model.TableColumns"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : success
Created on : Jul 8, 2014, 1:43:17 PM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Success</title>
<script type="text/javascript">
function validate(n) {
v = document.getElementById("check"+n)
v.checked = !v.checked;
x = document.getElementById("typeId"+n).removeAttribute('readonly');
y = document.getElementById("paramSeq"+n).removeAttribute('readonly');
z = document.getElementById("paramName"+n).removeAttribute('readonly');
}
</script>
</head>
<body>
<form action="DBController" method="post">
Welcome ${requestScope['user'].username}.
<table>
<tr style="background-color:#f0a64e;">
<th class="border">ID</th>
<th class="border">Param Sequence</th>
<th class="border">Param Name</th>
</tr>
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input id="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input id="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input id="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Update" name="update" />
</form>
</body>
</html>
I don't know how to send the whole row data to my servlet if more than one row is selected. I am able to get all the indexes of the checkboxes which are selected. But I am unable to extract other related values like typeId, paramSeq and paramName. My servlet is as follows :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] edited = request.getParameterValues("selectedItems");
//String pName = request.getParameter("paramName"+edited[1]);
Enumeration<String> paramName = request.getParameterNames();
String[] param = new String[10];
int i=0;
while(paramName.hasMoreElements()){
param[i]=paramName.nextElement();
}
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/update.jsp");
request.setAttribute("param", param);
request.setAttribute("edited", edited);
rd.forward(request, response);
}
In the above code, currently, I am trying to get all the parameters passed and the rows which are selected. I want to modify this servlet and access the selected row along with other data like typeId, etc. to create UPDATE statements for every row. I referred this and this but not much help.
I think what you are missing is that you are giving each input type a unique id but you are not specifying the name of the input types, and in the servlet you are trying to get values by name.
So please add names along with the id's in order to get them in the servlet
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input name="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input name="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input name="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
Related
I have a problem transferring data between two jsp
There are two controllers in which the first one accepts the input data, second generate lines with using this params
First controllers group receives two params
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String ProjectSizePost(
#RequestParam("countSprints") Integer countSprints,
#RequestParam("countWorkers") Integer countWorkers) {
BigInteger a = BigInteger.valueOf(countSprints);
return "project/project_size";
}
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String projectSizeGet() {
return "project/project_size";
}
And his jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Size</title>
</head>
<body>
<%--<c:forEach var="inputLine" begin="1" end="4">
<td><input type="text" name="projectManagerId" size="70" value={count} ></td><br>
</c:forEach>--%>
<form action="/project/show_size" method="post" name="/project/show_size"
commandName="projectSizeForm">
<tr>
<td>Count of sprints:</td>
<td><input type="text" name="countSprints" size="70" value = ${countSprints} ></td>
</tr> <br>
<tr>
<td>Count of workers:</td>
<td><input type="text" name="countWorkers" size="70" value = ${countWorkers} ></td>
</tr>
<tr>
<input type="submit" value="Next page"/></td>
</tr>
</form>
</body>
</html>
Second controller and jsp must take params from first jsp
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String createProject(
#RequestParam("projectId") Integer id,
#RequestParam("name") String name,
#RequestParam("startDate") String startDate,
#RequestParam("endDate") String endDate,
#RequestParam("projectStatus") OCStatus projectStatus,
#RequestParam("projectManagerId") Integer projectManagerId) {
MapperDateConverter mdc = new MapperDateConverter();
*//*Project project = new Project.ProjectBuilder()
.projectId(BigInteger.valueOf(id))
.name(name)
.startDate(mdc.convertStringToDate(startDate))
.endDate(mdc.convertStringToDate(endDate))
.build();
project.setProjectStatus(projectStatus);
project.setProjectManagerId(BigInteger.valueOf(projectManagerId));*//*
//projectDao.createProject(project);
return "project/create";
}
And second jsp:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<form action="/project/create" method="post" name="/project/create"
commandName="projectForm">
<table border="0">
<tr>
<h2>CreateProject</h2></td>
</tr>
<tr>
<td>Project Id:</td>
<td><input type="text" name="projectId" size="70" value = ${projectId} ></td>
</tr>
<tr>
<td>Project Name:</td>
<td><input type="text" name="name" size="70" value = ${projectName} ></td>
</tr>
<tr>
<td>StartDate (mm/dd/yyyy):</td>
<td><input type="text" name="startDate" size="70" value = ${startDate} ></td>
</tr>
<tr>
<td>EndDate (mm/dd/yyyy):</td>
<td><input type="text" name="endDate" size="70" value = ${endDate} ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" name="projectStatus" size="70" value = ${status} ></td>
</tr>
<tr>
<td>Project Manager:</td>
<td><input type="text" name="projectManagerId" size="70" value = ${pmId} ></td>
</tr>
<tr>
<td>Count of sprints</td>
<td><input type="text" name="countSprints" size="70" value = ${countSprints} ></td>
</tr>
<tr>
<td>Count of sprints</td>
<td><input type="text" name="countWorkers" size="70" value = ${countWorkers} ></td>
</tr>
<tr>
<input type="submit" value="Create"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Params countSprints and countWorkers
This question already has answers here:
Redisplay submitted value in input field
(2 answers)
Closed 7 years ago.
i have a jsp page which contains user name & password fields. For that two fields i am doing server side validation in servlet. And i am passing the error messages from servlet to jsp. Now what i want is when the error message is displayed on the jsp page at the same time only the fields should hold whatever the values i entered except error message field. It should not clear the values except error message fields.
UserLogin.java
String loginsubmit = request.getParameter("loginsubmit");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(loginsubmit!=null){
if(username==null || username.isEmpty()){
errors.put("username", "Please Enter User Name");
}
if(password == null || password.isEmpty()){
errors.put("password", "Please Enter Password");
}
if(errors.size()>0)
{
request.setAttribute("map",errors);
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}else{
int success_flag = fr.successFlag(username,password);
HttpSession ses=request.getSession();
String link = "<font color='red'>User Name Does Not Exist Please</font> <b><font color='#00ec00'>Create New Account</font></b>";
String resp=(success_flag==1?"<font color='#00ec00' size='5'>Login Successful</font>":link);
ses.setAttribute("resp_msg",resp);
if(success_flag==1){
response.sendRedirect("UserDetails.jsp");
}
else{
response.sendRedirect("index.jsp");
}
}
}
<head>
<link rel="stylesheet" type="text/css" href="css/button.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<%!
Map<String,String> errors=null;
%>
<body onload="onloadfunction();">
<%
if(request.getAttribute("map")!=null){
errors=(Map<String,String>)request.getAttribute("map");
out.println(errors.get("username"));
request.removeAttribute("map");
}
%>
<form method="post" action="./UserLogin" autocomplete="off">
<table align="center">
<tr>
<td>
<b><font color="#00ec00">Enter Username and Password</font></b>
</td>
</tr>
<tr>
<td>User Name</td>
<td>:</td>
<td><input type="text" name="username" id="username" placeholder="User Name"/></td>
<td style="color:red"><%=(errors!=null?(errors.get("username")!=null?errors.get("username"):""):"")%></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="password" id="password" placeholder="Password"/></td>
<td style="color:red"><%=(errors!=null?(errors.get("password")!=null?errors.get("password"):""):"")%></td>
</tr>
<tr>
<td colspan="3" style="text-align: center">
<input type="submit" value="Sign in" name="loginsubmit" id="submit"/>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: center">
<input type="button" value="Create Account" onclick="document.location.href='NewUserForm.jsp';" id="newuser"/>
</td>
</tr>
</table>
</form>
</body>
I am writing code for Username.Similar code You can write for password too.
<td>User Name</td>
<td>:</td>
<%if(request.getParameter("username")==null){ %>>
<td><input type="text" name="username" id="username" placeholder="User Name"/></td>
<%}
else{ %>
<td><input type="text" name="username" id="username" value=<%=request.getParameter("username") %>> placeholder="User Name"/></td>
<%}%>
I am a beginner in jsp.I want to get data from database and show checked on a checkbox depending on db value i.e. 0 or 1.This is working for me.But I also want o that when I check or uncheck the checkbox it will reset value and pass it to controller as a href parameter.
here is my jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Investor Account</title>
</head>
<body>
<script type="text/JavaScript">
function updateCheck(){
if(document.getElementById('chk').checked){
document.getElementById('chk').value = 1;
location.href=""
alert(document.getElementById('chk').value);
}
else{
document.getElementById('chk').value = 0;
alert(document.getElementById('chk').value);
}
}
</script>
<div align="center">
<h1>Investor Account List</h1>
<table border="1">
<th>ID</th>
<th>Investor Code</th>
<th>Investor Name</th>
<th>SMS Subscriber</th>
<th>Action</th>
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td> <input type="checkbox" id="chk" name="chkSms" value= <c:if test="${investorAcc.sms_sub==1}">1</c:if> onclick="updateCheck();"
<c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<td>
1</c:if>"> Update
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
To update checkbox value, the easiest way is to use form in loop. Try
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<form action="updateInvestorAcc">
<input type="hidden" name="id" value="${investorAcc.id}"/>
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td>
<c:choose>
<c:when test="${investorAcc.sms_sub==1}">
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" checked="checked"/>
</c:when>
<c:otherwise>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}"/>
</c:otherwise>
</c:choose><td> <!-- end of checkbox -->
<td><input type="submit" value="Update"></td>
</tr>
</form>
</c:forEach>
Edit:
You need a Servlet to get updated value
#WebServlet("/updateInvestorAcc")
public class UpdateInvestorAcc extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String idStr=request.getParameter("id");
int id= Integer.parseInt(idStr);// If you need to parse to int
String[] chkSms=request.getParameterValues("chkSms");
boolean isChkSms =false;
if(chkSms !=null && chkSms.length > 0){//If checkbox is checked than assign it with true or 1
isChkSms=true;
}
// Now update the DB with id and checkbox value.
}
you can simplify the middle bit in the other posters suggestion with a basic IF test. Because it's only going to be 1 or 0 (choose is overkill IMO). Technically because it's 1/0 you don't even need to ==1 comparitor, just reference it raw in the test="" block as test="${investorAcc.sms_sub}". The JSTL is smart enough to handle all angles (including NULL). 1=true, 0=false, NULL=false.
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<form action="updateInvestorAcc">
<input type="hidden" name="id" value="${investorAcc.id}"/>
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" <c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<td> <!-- end of checkbox -->
<td><input type="submit" value="Update"></td>
</tr>
</form>
</c:forEach>
For your second bit about the 'unchecked' box passing invalid values. That's a super annoying thing with HTML. Unchecked boxes get 'dropped to null' when a form is submitted. A lot of people are supplementing with a 2nd hidden input to get this done without NULL errors (note, it MUST be second). Different "ID", but same "NAME" so the Servlet will see it and capture the 'unchecked' value from it instead of the NULLed original checkbox:
ex:
<td>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" <c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<input type="hidden" id="chk_0" name="chkSms"
value="0"/>
<td> <!-- end of checkbox -->
I have searched this forum and net for this, found many example but still i am not able to populate the select box in jsp.
I have written a jsp servlet, where servlet returns an arraylist and in jsp uhsing jstl i am trying to create a select box and populating option with arraylist values.
Following is my code.
Servlet Code:
#SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response) {
UserService userService = new UserServiceImpl();
try {
String[] questions = userService.getQNA().getQuestions();
List<String> ques = new ArrayList<String>();
ques = Arrays.asList(questions);
request.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
} catch (IOException e) {
log.error("request failed "+ e.getMessage());
}
}
JSP code :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Enroll Migration Users</title>
</head>
<body>
<form method="post" action="/nycb/enrolluser" name="enrollForm">
<table>
<tr>
<td>User setup</td>
<td></td>
</tr>
<tr>
<td>UserId :</td>
<td><input type="text" name="userName" id="userName"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><input type="checkbox" name="computerType" value="public">Authorize this computer</td>
<td></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="<%=request.getAttribute(\"questionDTO\") %>" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="${questionDTO}" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
</table>
<input type="submit" value="click" name="dropdown" id="dropdown">
</form>
I am not able to populate the select box, the option field is empty.
Can anyone please let me know where i am going wrong?
sendRedirect() creates a new request and any attribute set in request will not be available in redirected JSP page.
Try any one
You can use RequestDispatcher#forward or RequestDispatcher#include in this case.
You can save it in session as attribute.
Sample code:
RequestDispatcher view = request.getRequestDispatcher("forms/enrollMigrationUser.jsp");
view.forward(request, response);
OR
HttpSession session = request.getSession();
session.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
Always try to avoid Scriplet elements instead use JSTL & EL.
You can do in this to read an attribute from any scope in order page, request, session and finally applicaion
<c:forEach items="${questionDTO}" var="question">
OR read from specific scope.
<c:forEach items="${requestScope.questionDTO}" var="question">
I have a JSP called create-account.jsp which collects a customer's details and sends the data to a Servlet. The Servlet inserts the customer's data into the database, queries the database add sets the results as request scoped attributes and the dispatches to create-account.jsp(same jsp). Now the inserted details must appear in a hidden html table in the jsp. How do I do it? Can any one help?
create-account.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Create New Account</title>
<style>
a {
text-decoration: none;
}
body {
border-color: azure;
}
</style>
</head>
<body>
<p align="right">Hi, ${sessionScope.user.userName} logout</p>
<h2 align="center">Create New Account</h2>
<form action="${pageContext.request.contextPath}/create.do" method="post">
<table border="1" align="center">
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>DOB:(yyyy-mm-dd)</td>
<td><input type="text" name="dob"></td>
</tr>
<tr>
<td>Balance:</td>
<td><input type="text" name="balance"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="Create" name="create">
</td>
</tr>
</table>
</form>
<p align="center" style="display: none">${requestScope.result} has been successfully inserted into the table</p>
<table id="hiddenTable" style="display: none" border="1">
<tr>
<td>
</td>
</tr>
</table>
</body>
</html>
Use
style="visibility: hidden;"
or
style="display:none;"
to hide the table.
for more info have a look at below links
CSS Display and Visibility
Show/Hide div javascript
How to show the result in table?
sample code:
Servlet:
public class Model{
private String name;
private String dob;
private double balance;
// getter and setter
}
...
List<Model> list = new ArrayList<Model>();
//add the data in list
request.setAttribute("list",list);
JSP:
<c:if test="${not empty list}">
<c:forEach var="ob" items="${list}">
<tr>
<td><c:out value="${ob.name}"/></td>
<td><c:out value="${ob.dob}"/></td>
<td><c:out value="${ob.balance}"/></td>
</tr>
</c:forEach>
</c:if>
For complete code have a look at jsp iterate over list