Edit button on a dynamic table in jsp servlet application - java

I am working on a JSP Servlet project in which I have created a table on the JSP page. This table is getting populated from an arraylist that is the resultset of a query. So I am basically running a query, storing into an arraylist and displaying the values from that arraylist. How should I edit the fields in the table such that I can delete all information about that field from the table and create a new entry entered by the user.
The code for JSP page to run the query and display the table is as follows:
//run the query
try{
out.println("<html>");
out.println("<table id='tbl'class= 'cls' style='display;' border=''><tr><th>Tag</th><th>Severity</th><th>Threshold</th><th>ID</th><th id= 'del'>Delete</th> </tr>");
Iterator<String> li = alarmarr.iterator();
int flagy=1;
int temp = 1;
for (int f=0; f<=count; f++){
out.println("<tr>");
while(li.hasNext() && temp <=numberOfColumns){
temp++;
String temporaryvalue = (String)li.next();
out.println("<td><input type='text' value='"+temporaryvalue+"' /></td>");
if(temp ==5 && flagy==1){
out.println("<td> <a href='editalarm?id="+temporaryvalue+"'>Edit</a></td>");
out.println("<td id = 'delalarms' > <a id='delalarms' href='deletealarm?id="+temporaryvalue+"'>Delete</a></td>");
flagy = 0;
}
}
temp = 1;
flagy = 1;
out.println("</tr>");
}
out.println("</table></div>");
out.println("</center></div></body></html>");
}
catch(Exception e)
{
System.out.println(e);
}

You should update the alarmarr and re-render the table. For example to add a new table row you need to add the item to the alarmarr object while to delete a row you need to remove from the list.
Also I am not a huge fan of using JSPs scriptlets to render HTML. Please use JSTL atleast.

Try Ajax folk,
function myFunction() {
if(confirm("Are you sure you want to delete this?")){
var activeRecord= '${id}'; //or get id from click function
//Make sure it is having the value here.
//alert(activeRecord); or console.log(activeRecord);
$.ajax({
type: "POST",
url: "servletURL",
data: {"id": activeRecord},
dataType: 'json',
success: function(data){
// use data for populate form
}
});
}
else{
return false;
}
}

Related

Why isn't my List<Object> displaying on my webpage?

I'm trying to display the contents of a List<> of objects that are linked to the currently logged in user on a jsp page. The object is successfully created and stored in the database with a user_id of the user who created it, and with a simple system.out.print debugger I can see its added to the List.
But when I try to display this on the NewFile.jsp webpage its as if the the List is empty. There is no error, instead the page is just blank as if there is no List to iterate through.
Skill method in UserController
#RequestMapping(value = "/skill", method = RequestMethod.POST)
public String skill(#ModelAttribute("skillForm") Skill skillForm, BindingResult bindingResult, Model model, Principal principal) {
skillValidator.validate(skillForm, bindingResult);
if (bindingResult.hasErrors()) {
return "skill";
}
// Adds skill object to database and adding it to Users skill list
String name = principal.getName();
skillService.save(skillForm, name);
User currentUser = userService.findByUsername(principal.getName());
currentUser.addSkill(skillForm);
// Debug here shows that the list contains correct data and the list size
System.out.println(skillForm.getSkillName());
System.out.println(skillForm.getCategory());
System.out.println(currentUser.getSkills().size());
// Attempting to pass the list to NewFile.jsp to be displayed
List<Skill> savedSkills = currentUser.getSkills();
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills);
/*model.addAttribute("currentUser", currentUser);*/
}
return "NewFile";
}
NewFile.jsp
<table>
<c:forEach var="o" items="${savedSkills}" >
<tr>
<td>Skill Name:<c:out value = "${o.skillName}"/></td>
<td>Category:<c:out value = "${o.category}"/> </td>
</tr>
</c:forEach>
</table>
There are some mistakes. First you don't need a loop.
List<Skill> savedSkills = currentUser.getSkills();
model.addAttribute("skills", savedSkills);
Second, your EL has the wrong argument name, just like the others had stated.
<c:forEach var="o" items="${skills}" >
You need to specify what skill to be added , you are adding the List as an attribute but you need to the object that's inside it
for(int i = 0; i < savedSkills.size(); i++) {
model.addAttribute("skills", savedSkills[i]);
/*model.addAttribute("currentUser", currentUser);*/
}
Try by adding the code model.addAttribute("savedSkills", savedSkills); before the return statement. You haven't add the model attribute named with "savedSkills".

Getting ? when alerting the ajax response or posting it to a text field

I have created an ajax call in jquery to my server, the trouble I'm facing now is that my response is printing ? even though the correct integer value is written into the output stream. Ajax function is given below.
$dntb.on('click', 'button', function(event) {
var i = $(this).closest('tr').index(); //have to get the row where the button is clicked
var sditmId = $("#sditm").val();
var sdhedId = $("#sdhed").val();
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = ""+response;
$("#stk").val(stk);
});
});
This function is called on click of an issue button in my table shown below
The server code is given below
int stk = null;
switch (userPath) {
case "/getstock":
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId")); //value to write into the output stream.
break;
case "/temp":
//er = opo.checkCatUniqueForEdit(request.getParameter("catName"), request.getParameter("catId"));
break;
}
System.out.println(stk); //Printing correctly
response.setContentType("text/html");
response.getWriter().write(stk);
Code to get the value
public int getStockData(String sditm, String sdhed) {
int stk = 0;
try {
String query = "Select stk.Stk_instk from tbstk stk inner join tbsditm itm on itm.Sditm_prdid=stk.Stk_prdid where itm.Sditm_sdhed=" + sdhed + " and itm.Sditm_id=" + sditm;
Statement stmt = dcon.con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
stk = rs.getInt("Stk_instk");
}
} catch (SQLException ex) {
Logger.getLogger(Op_OrdConf.class.getName()).log(Level.SEVERE, null, ex);
}
return stk;
}
The ajax call happens successfully but when I alert the response I'm getting and I'm getting the value correctly in the server but in the client side it is ?. Please help me solve this
Not sure but seems that you are missing a comma here:
stk = opo.getStockData(request.getParameter("sditmId"), request.getParameter("sdhedId"));
//----------------------------------------------------^-----i think this is missing.
As per your comment i would suggest you to explicitly set the dataType to html:
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = "" + response;
$("#stk").val(stk);
},"html"); //<----------add the dataType here.
I converted the int value returning from the function as given below to String, it seems to be some conflict between the content type and the value written into the output stream
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId"));

How to change list(select) data dynamically

I am adding product details.
So for that with it I have to add product attribute, product feature with it.
I am loading all data of attribute from mysql table.
I am using one mechanism that first user have to select attribute category from list (select control), when user select category then as per it data of other list (select control) changes.
main category image :
sub attribute category :
I have added data like this in JavaScript array :
var at_category_id = [];
var at_category_name = [];
<%
List<Integer> aIDList = (List<Integer>) request.getAttribute("aID");
List<String> aNAMEList = (List<String>) request.getAttribute("aNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_category_id.push(<%= aIDList.get(i) %>);
at_category_name.push(<%= aNAMEList.get(i) %>);
<%
}
%>
var option_str = document.getElementById('list_main_category');
for (var i=0; i<at_category_id.length; i++)
{
option_str.options[option_str.length] = new Option(at_category_id[i],at_category_name[i]);
}
I have done same like this for attribute and add data to JavaScript array.
var at_id = [];
var at_name = [];
<%
List<Integer> acIDList = (List<Integer>) request.getAttribute("acID");
List<String> acNAMEList = (List<String>) request.getAttribute("acNAME");
for (int i = 0; i < aIDList.size(); i++)
{
%>
at_id.push(<%= acIDList.get(i) %>);
at_name.push(<%= acNAMEList.get(i) %>);
<%
}
%>
but now how to move forward I don't know.
I want to do something like that.
Means when user click on first list that is main category how second list will be changed ?
any suggestion please.
The usual way would be to put a javascript action on the value changing for the first combo box.
At that point you can either (easy way) submit the whole form and then send back the new page with the extra value added or (slightly more complex) do an AJAX call to fetch the data and populate the new dropdown.

how to add value listbox with another listbox java struts?

i want to use two listbox (multiple) on java struts enviroment. first listbox is listed personel names and second listbox is blank at first. With add and remove buttons fill up second listbox with value from selected first listbox. But i don t know how to use this?
value is string array or collection to getter/setter? and how to use?
furthermore i know javascript code how is making but struts is complex.
my code is:
JSP :
first listbox and second listbox
< td class="formitem">
< html:select multiple="true" size="4" styleClass="textField" >
< html:options collection="pName" property="deger" labelProperty="pers"/>
</html:select>
</td>
<td class="formitem">
<html:select property="personelName" styleClass="textField" >
<html:options collection="personelList" property="deger" labelProperty="xxx"/>
</html:select>
</td>
my form code is
private String[] pName = null; is string array or another type?
public String[] getpName() {
return pName;
}
public void setpName(String[] pName) {
this.pName = pName;
}
model class
public static Collection personelFill(String x) {
{
Connection connection = null;
PreparedStatement pst = null;
ResultSet rs = null;
ArrayList personelList = null;
try {
connection = DBFactory.getConnection();
String sql =
"select p.adi || ' ' || p.soyadi isim, p.tckimlikno , p.subeno, p.daireno " +
"from personel p " +
"where p.listedegorunsun = 1 "
+ x
+ "order by nlssort(p.adi||' '||p.soyadi,'NLS_SORT = TURKISH')";
pst = DBFactory.getPreparedStatement(connection, sql);
rs = pst.executeQuery();
personelList = new ArrayList();
PersonelForm pForm = null;
while (rs.next()) {
pForm = new PersonelForm();
//fill form setter
personelList.add(pForm);
}
return personelList;
} catch (Exception e) {
throw new BDException(e.getMessage());
} finally {
DBFactory.closeConnection(connection, pst, rs);
}
}
}
It's nothing to do with serverside. It can be done on the client side using javascript or jquery
see the following jsfiddle and original post.
http://jsfiddle.net/RbLVQ/62/
$('#btnRight').click(function(e) {
var selectedOpts = $('#lstBox1 option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#lstBox2').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});

Servlet Jsp Array Printing Links

I have a java servlet that passes an array to a jsp page, on that jsp page it displays a bunch of results. What I am trying to do is when it prints out it prints a link so I can use it as a parameter. In my case it prints out a bunch of lab classes, what i want to happen is they click the link related to that lab then i click the link and can use that lab.id in a sql statement.
here is the code for the array being printed out
here is the servlet
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT s.name, l.time, l.day, l.room" +
" FROM lab l, subject s, user_lab ul" +
" WHERE ul.user_id=" + (Integer)session.getAttribute("id") +" AND ul.lab_id ="+ "l.id"+" AND l.subject_id ="+"s.id";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1) + " " + res.getString(2) +" "+ res.getString(3) + " " + res.getString(4));
System.out.print(res.getString(1) + res.getString(2));
}while(res.next());
System.out.println("Outside");
String[] arr = list1.toArray(new String[list1.size()]);
request.setAttribute("res", arr);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("Lecturer_labs.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
and here is the jsp page
<h3>Manage Labs</h3>
<table>
<% String[] list1 = (String[])request.getAttribute("res");
if(null == list1){%>
<%
}else{
for(int i=0; i<list1.length; i++)
{ %>
<tr><%out.println(list1[i] + "<br/>");%></tr>
<% }
}
%>
</table>
so how can I get it to print the results as a link that passes a parameter
To display the results as a link that pass the parameter id, each link could look like:
Link <%out.println(list1[i]);%>
but look how clunky this looks.
JSTL tags can eliminate all this scriptlet code:
<c:forEach items="${res}" var="id">
<tr><td>Link ${id}</td></tr>
</c:forEach>

Categories

Resources