The code I have written gives me the output of only a single data in the drop down list. I want my drop down list to retrieve and hold all the data of the fname and userid column of the table. I am using struts concept and JSP. Kindly help as to how I should modify my code?
public String subjectAllocation2()throws Exception
{
try{
Map session=ActionContext.getContext().getSession();
Long idd=(Long)session.get("USERID");
System.out.println("sss"+idd);
ResultSet rs=ConnectionDb.getStatement().executeQuery("select USERID,FNAME from DIP_FACULTY");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList al = new ArrayList();
while(rs.next())
{
for (int i = 1; i <= columns; i++)
{
String value1 = rs.getString(i);
al.add(value1);
}
setUserid(rs.getString(1));
setFname(rs.getString(2));
System.out.println("The details="+rs.getString(1)+rs.getString(2));
}
catch(Exception e)
{
System.out.println("exception");
}
return "subjectAllocation2";
}
and this is the JSP code
<s:form action="addSubject" method="post" enctype="multipart/form-data">
<table border="1" cellpadding="15" width="300">
<tr><td><s:combobox name="semestar" label="Semestar" list="{'1st','2nd','3rd','4th','5th','6th','7th','8th'}"></s:combobox></td>
<td><s:combobox name="branch" label="Branch" list="{'CSE','IT','EEE','ETC','MECH','EE','CIVIL'}"></s:combobox></td>
<td><s:radio name="section" label="Section" list="{'A','B'}"/></td></tr>
<tr><td>
<s:select name="fname" label="Faculty name" list="fname"></s:select>
</td></tr>
<tr><td><s:combobox name="userid" label="Faculty id" list="userid"></s:combobox></td></tr>
<tr><td><s:combobox name="subject" label="Subject Name" list="{'Software Engineering','Soft Computing','Computer Graphics','Real Time System','Introduction To Digital Signal Processing','Entreprenaurship Development'}"></s:combobox></td></tr>
<tr><td><s:select name="sub_code" label="Subject Code" list="{'PCS098','HCS232','WQ1232','PNB342','WQW232','QAZ213'}"></s:select></td></tr>
<s:checkbox name="theory" label="Theory"></s:checkbox>
<s:checkbox name="practical" label="Practical"></s:checkbox>
<tr><td><s:submit value="allocate"/></td><td><s:submit action="reset" value="Reset"/></td></tr>
</table>
</s:form>
<s:property value="msg"/>
Related
I want to update a particular column in my database with the word 'trash' but I need to first tick the values in check box. Then when u tick the checkbox, the system will only update the status field of the id's selected
public void updateNow(Messages message){
Query query = em.createNativeQuery("Update Messages set status = 'trash' WHERE id =:id");
query.setParameter("id", message.getId());
query.executeUpdate();
}
}
<%
//updating the filed
String[] arr = request.getParameterValues("content");
int sum=0;
if(request.getParameter("update")!=null){
try{
for (int i=0; i<arr.length; i++){
sl.updateNow(arr[i]);
sum++;
msg = "<script>alert('You have move message to trash')</script>";
}
}catch (Exception e){
msg="Please Do select an email before performing an action" + e.getMessage();
e.printStackTrace();
}
}
%>
<html>
<body>
<form action="" method="post">
<%
List inboxFetch = sl.allMessages(user, "inbox");
Iterator inboxIterate = inboxFetch.iterator();
while(inboxIterate.hasNext()){
Messages all = (Messages) inboxIterate.next();
%>
<input type="checkbox" value="<%=all.getId() %>" name="content">
<%
}
%>
<br />
<hr />
<button type="submit" name="update" class="btn btn-sm btn-danger">Update</button>
</form>
</body>
</html>
Please how do I achieve this? I have been on this code now for quite some hours seems I can't get through it
I have created a table to display data and there is a checkbox next to each of the data. I want to create a function where if the user click the checkbox of that data and press the delete button, the data will be remove from the table and the database. I have came up with the code but it doesn't remove the data. What is the problem with my code ?
Display on Webpage
HTML
<%
String id = request.getParameter("hiddenID");
String sql1="";
{
sql1 = "select * from exercise1";
PreparedStatement pstmt1=conn.prepareStatement(sql1);
ResultSet rs1 = pstmt1.executeQuery();
while(rs1.next()){
String arm = rs1.getString("Arm");
String time1 = rs1.getString("Time1");
out.println("<tr>");
out.println("<td style = 'width: 20%'>");
out.println(arm);
out.println("</td>");
out.println("<td style = 'width: 5%'>");
out.println(time1);
out.println("</td>");
%>
<td style="width: 5%"><input class="mychkbox" type="checkbox"
value="<%=id%>" form="multipleDele" name="DeleteChkbox" /></td>
<%
out.println("</tr>");
}
conn.close();
}
%>
This is my delete.jsp file
<%
String[] id = request.getParameterValues("DeleteChkbox");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (id != null)
{
for(int i=0;i<id.length;i++){
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(id[i]));
//pstmt.setInt(1, Integer.parseInt(id[i]));
int rec=pstmt.executeUpdate();
if (rec==1)
count++;
}
}
//System.out.println(functions);
%>
<form action="exercise.jsp" method="post">
<label><%=count%> record(s) deleted!!</label>
<input type="submit" value="Return" name="ReturnBtn" />
</form>
<%
conn.close();
} catch (Exception e) {
out.println(e);
}
%>
The id you are writing to the checkbox value is not coming from the database results. It is being retrieved in the JSP from a request parameter:
String id = request.getParameter("hiddenID");
... and then being written to every checkbox field:
<input class="mychkbox" type="checkbox" value="<%=id%>" form="multipleDele" name="DeleteChkbox" />
You aren't writing a different id for each checkbox.
As such, it probably is not the id of any of the database records, and therefore none of them are being deleted.
You should be reading the id of each record in your while loop when building the HTML.
I suspect you need something like this:
<input class="mychkbox" type="checkbox" value="<%=rs1.getString("id")%>" form="multipleDele" name="DeleteChkbox" />
Your image has three columns: arm exercises, number of times and action. The DeleteChkboox field will only tell you if the field is selected or not for a particular row. You need to get the ids that have been selected for deletion. Unchecked checkboxes will not show up in an array of checkboxes so your form has to take this into account. It needs to look something like
<form action = "...">
<input type="submit" value="delete">
<input type="submit" value="assign">
<table>
<c:forEach items="${ records }" var="r">
<tr>
<td>
${ r.exercise }
</td>
<td>
${ r.times }
</td>
<td>
<input type="checkbox" value="${ r.id }" name="userAction">
</td>
</tr>
</c:forEach>
</table>
</form>
Then you need to change your jsp so that you get the ids of the selected rows. Change the jsp part that iterates your ids to
<%
// get array of ids
String[] ids = request.getParameterValues("userAction");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (ids != null) {
for(int i=0; i < ids.length; i++) {
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(ids[i]));
int rec=pstmt.executeUpdate();
if (rec==1) {
count++;
}
}
}
}
%>
That aside, it's generally not the best of ideas to be running sql updates in jsps if you can help it. Consider moving this logic to a controller class and using the jsp layer for presentation only.
EDIT
As per your comment "it's not working", instead of looking at this particular problem (why doesn't the code you wrote remove the data) you have to look at the bigger picture: what is the problem you are trying to accomplish?
It looks something like this, in plain English:
Show a user a set of records
Allow the user to mark the records they'd like to delete (array of checkboxes); allow the user to submit this information (the record ids)
Process (delete) the submitted ids
Step 1
Iterate over a list of records in jsp, inside a <form> element
For each record, create a checkbox whose value is that record's id
Step 2
Add a delete button allowing the user to submit the form of ids
Step 3
Process the submitted information: get the list of ids submitted in the request, iterate over it and delete the records one by one
Which step are you stuck on?
I have this JSP form where i have some values inserted from the previous page.
<script language="javascript" type="text/javascript">
var i = 1;
function addRow() {
var tbl = document.getElementById('table1');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'name_' + i;
el.id = 'name_' + i;
el.size = 10;
el.maxlength = 10;
firstCell.appendChild(el);
// alert(i);
i++;
frm.h.value = i;
// alert(i);
}
</script>
<form action="CreateAssignments" method="post"
enctype="multipart/form-data">
<center>
<table id="table1">
<tr>
<td>
<p>Degree :</p>
</td>
<td><label><%=request.getParameter("degree")%> </label> <input type="hidden" name="degree"
value="<%=request.getParameter("degree")%>" /></td>
<td></td>
<td>
<p>Course :</p>
</td>
<td><label><%=request.getParameter("course")%> </label><input
type="hidden" name="course"
value="<%=request.getParameter("course")%>" /></td>
</tr>
<tr>
<td>
<p>Stream :</p>
</td>
<td><label><%=request.getParameter("stream")%> </label><input
type="hidden" name="stream"
value="<%=request.getParameter("stream")%>" /></td>
<td></td>
<td>
<p>Section :</p>
</td>
<td><label><%=request.getParameter("section")%> </label><input
type="hidden" name="section"
value="<%=request.getParameter("section")%>" /></td>
</tr>
<tr>
<td>
<p>Semester :</p>
</td>
<td><label><%=request.getParameter("semester")%></label><input
type="hidden" name="semester"
value="<%=request.getParameter("semester")%>" /></td>
<td></td>
<td>
<p>Paper Code :</p>
</td>
<td><label><%=request.getParameter("papercode")%></label><input
type="hidden" name="papercode"
value="<%=request.getParameter("papercode")%>" /></td>
</tr>
<tr>
<td><p>
<input type="button" value="Add Questions" onclick="addRow();" />
</p></td>
</tr>
<tr>
<td><p>Start Date:</p></td>
<td><p>
<input type="date" name="startdate" />
</p></td>
</tr>
<tr>
<td><p>End Date:</p></td>
<td><p>
<input type="date" name="enddate" />
</p></td>
</tr>
<tr>
<td><p>Assignment Name:</p></td>
<td><p>
<input type="text" name="assname" />
</p></td>
</tr>
<tr>
<td><p>Upload File</p></td>
<td><p>
<input type="file" name="fileupload" value="" />
</p></td>
</tr>
<tr>
<td><p></p></td>
<td></td>
<tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</center>
</form>
And this Java class to insert data into the database.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
session = request.getSession(true);
String assignmentName = request.getParameter("assname");
String startDate = request.getParameter("startdate");
String endDate = request.getParameter("enddate");
String course = request.getParameter("course");
String degree = request.getParameter("degree");
System.out.println("degree: "+degree);
String semester = request.getParameter("semester");
String paperCode = request.getParameter("papercode");
String stream = request.getParameter("stream");
String fileName = uploadFile(request, response);
String question1=request.getParameter("name_1");
String question2=request.getParameter("name_2");
String question3=request.getParameter("name_3");
String question4=request.getParameter("name_4");
String question5=request.getParameter("name_5");
String question6=request.getParameter("name_6");
System.out.println("FILE NAME : " + fileName);
try {
PreparedStatement ps = connection.prepareStatement("insert into assignment_master values (?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, "2");
ps.setString(2, assignmentName);
ps.setString(3, degree);
ps.setString(4, course);
ps.setString(5, stream);
ps.setString(6, semester);
ps.setString(7, (String) session.getAttribute("employeeId"));
ps.setString(8, fileName);
ps.setString(9, startDate);
ps.setString(10, endDate);
ps.executeUpdate();
PreparedStatement ps1 = connection
.prepareStatement("select max(assignment_id) assignmentId from assignment_master");
ResultSet rs = ps1.executeQuery();
PreparedStatement ps2 = connection.prepareStatement("insert into assignment_subject(?,?)");
ps2.setString(1, rs.getString("assignmentId"));
ps2.setString(2, paperCode);
ps2.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String uploadFile(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html");
// PrintWriter out = response.getWriter();
// out.println("<html>");
// out.println("<body>");
String value = "";
FileItemStream fileItemStream = null;
boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
if (isMultiPart) {
// out.println("Yes Multipart data");
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator itr = upload.getItemIterator(request);
while (itr.hasNext()) {
fileItemStream = itr.next();
if (fileItemStream.isFormField()) {
// do field related work
String fieldName = fileItemStream.getFieldName();
InputStream is = fileItemStream.openStream();
byte[] b = new byte[is.available()];
is.read(b);
value = new String(b);
// out.println(fieldName + " : " + value);
} else {
String path = getServletContext().getRealPath("/");
System.out.println("PATH : " + path);
if (FileUpload.processFile(path, fileItemStream, value)) {
System.out.println("File Uploaded Successfully");
// request.setAttribute("imagePath", path
// + fileItemStream.getName());
// RequestDispatcher gotoShowPage = request
// .getRequestDispatcher("showPage.jsp");
// gotoShowPage.forward(request, response);
} else {
// out.println("File Uploading failed ");
System.out.println("File Uploading failed ");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
}
} else {
// out.println("No Multipart data");
}
// out.println("</body>");
// out.println("</html>");
return fileItemStream.getName();
}
}
But when i submit this form and try to insert data, I get an error saying primary key cannot be null and when i debug i realise that actually all the fields from the form returns null values. And i also want to know to acesss data from the dynamic textboxes and insert them.
Thank you.
Your insert statement is incorrect.
insert into assignment_master values (?,?,?,?,?,?,?,?,?,?)
You have to name columns like these:
insert into assignment_master(assignment_id, assignment_name, degree, course, stream, semester, employee_id, file_name, start_date, end_date) values (?,?,?,?,?,?,?,?,?,?)
Same is true in second insert stament:
insert into assignment_subject(?,?)
has to have column names specified.
If you do not specify column names than all columns will be assigned their default values. See [3] for MySQL.
Assuming that you are using MySQL, see INSERT syntax: [1]
For PostgreSQL see [2].
[1] http://dev.mysql.com/doc/refman/5.7/en/insert.html
[2] https://www.postgresql.org/docs/current/static/sql-insert.html
[3] http://dev.mysql.com/doc/refman/5.7/en/insert.html#idm139777556167776
Whenever you upload the form data using Multipart, the request object is converted into a stream, stream of data to be specific.
In such a scenario, you do not get the fields as parameters. They come along with the file data. The code shown below - already present in your code shown handles this:
if (fileItemStream.isFormField()) {
// do field related work
String fieldName = fileItemStream.getFieldName();
InputStream is = fileItemStream.openStream();
byte[] b = new byte[is.available()];
is.read(b);
value = new String(b);
// out.println(fieldName + " : " + value);
}
You can modify this code to create a hashmap of parameters that are present in your form. The code can be like:
HashMap<String,String> myvaluemap = new HashMap();
if (fileItemStream.isFormField()) {
String fieldName = fileItemStream.getFieldName();
InputStream is = fileItemStream.openStream();
byte[] b = new byte[is.available()];
is.read(b);
value = new String(b);
myvaluemap.put(name,value);
}
I have it tested at my end. Let me know if still any further help is required.
For your reference, you can refer to:
this link. in the processing uploaded items section. It is not the exact thing, but provides the hint
HTML :
<table>
<tr>
<td>
<input type="hidden" value="flag1" />
</td>
<td>
<input type="text" value="orange" />
</td>
<td>
<input type="text" value="1.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
<tr>
<td>
<input type="hidden" value="flag2" />
</td>
<td>
<input type="text" value="apple" />
</td>
<td>
<input type="text" value="2.00" />
</td>
<td>
<input type="text" value="5" />
</td>
</tr>
</table>
JS :
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
alert(JSON.stringify(array));
$(document).on("click","#save",function(){
$.post("servlet.html","data="+JSON.stringify(array)+"",function(response){
});
});
Java servlet contains this :
String data = request.getParameter("data");
data looks like this :
[{"flag1":["orange","1.00","5"]},{"flag2":["apple","2.00","5"]}]//this is get from table row data using stringify
i want to get on first loop using javax.json-api1.0.jar or javax.json-1.0.jar only :
on first loop :
flag1
Orange
1.00
5
on second loop :
flag2
Apple
2.00
5
Any help will be best.
You can do it with only json-api, but you must be sure of the structure of the input data.
If not, gson or jackson2 are easier to use.
If you want to use json-api, you could do something like :
First declare a JsonFactoryReader attribute in your servlet because you will create a reader per request.
JsonReaderFactory readerFactory = Json.createReaderFactory(null);
then in your service or doXXX method do :
String data = request.getParameter("data");
// create a reader for json data
JsonReader jr = readerFactory.createReader(new StringReader(data));
// tol level must be an array, and we count the iteration for eventual error messages
JsonArray ja = jr.readArray();
int iteration = 0;
for (JsonValue jv: ja) {
// sub elements must be dicts
if (jv.getValueType() != ValueType.OBJECT) {
throw new FormatException(iteration, jv);
}
for (Entry<String, JsonValue> e: ((JsonObject) jv).entrySet()) {
// the key
String key = e.getKey();
if (e.getValue().getValueType() != ValueType.ARRAY) {
throw new FormatException(iteration, e.getValue());
}
// the values, first is a string
JsonArray array = (JsonArray) e.getValue();
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(0).getValueType());
}
String name = array.getString(0);
// next a float and an int
float fval;
int ival;
try {
fval = Float.valueOf(array.getString(1));
ival = Integer.valueOf(array.getString(2));
}
catch (NumberFormatException ex) {
throw new FormatException(iteration, array);
}
// Do your stuff with those values ...
// for instance Data data = new Data(key, name, fval, ival) ...
iteration++;
}
}
I propose you an exception class to handle format errors (at least you know why it breaked ...):
class FormatException extends ServletException {
FormatException(int i, JsonValue jv) {
super("Iteration " + String.valueOf(i) + " : " + jv.toString());
}
}
The code for retrieving data from database into Drop Down List.
<%
DataSource data = new MysqlDataSource();
Connection con = data.getConnection("root","system");
System.out.println("Connected to MySQL");
PreparedStatement pre = con.prepareStatement("select * from library.booklist");
ResultSet result = pre.executeQuery();
%>
<tr>
<font color="black" size="5"> <td> Book List : </td> </font>
<td> <select name= "BookList" id="booklist" onchange="show()">
<option> - select - </option>
<%
while (result.next())
{
String name = result.getString("Book");
System.out.println("Output Done");
%>
<option value="<%=name%>"> <%=name%></option>
<%
}
%>
</select></td>
</tr>
<tr>
<%
/* my code for displaying quantity is below but it's not working. I am new to jsp, so don't know how to populate the textbox. */
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
result = pre.executeQuery();
%>
<font color="black" size="5"><td> Quantity : </td>
<%
while (result.next())
{
int quantity = result.getInt("Quantity");
System.out.println("quantity dikha raha hai");
%>
<input name = "Quantity" type = "text" size = "25" readonly = "readonly" value = "<%=quantity%>"> <%=quantity%> </input>
<%
}
%>
</td>
</tr>
Edit
You need to pass your BookList parameter to your prepared statement:
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
pre.setString(1, value); // <------
result = pre.executeQuery();
Otherwise your query does not know which Book to select.
Original
You haven't said what the actual problem is, but your HTML markup has problems that definitely aren't helping.
Don't use the <font> tag. It is not supported in
HTML5.
Your second <font> needs a closing </font>.
You have a closing </td> tag at the end with no opening <td>.
The <input> tag is a void element, meaning it does not accept content between opening and closing tags. Write it as <input type="text" name="Quantity" .../>
Clean up those things and your problem might be fixed, or at least more obvious.