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();
});
Related
I am trying to update several records from spring jdbc but this is not working what am i doing wrong?
does not respond when I make a request, but the data in the array is arriving, try without array and the same thing happens.
I am sending an array of objects to be able to update but I get to the method cstmt.executeQuery(); it does not execute and it waits and does not go any further.
#PostMapping(path = "/updateEstadoPlanesServicios", produces = MediaType.APPLICATION_JSON)
public String updateEstadoPlanesServicios(#RequestBody String lista) {
ServiciosPlanesUpdateDTO[] fromJson = gson.fromJson(lista, ServiciosPlanesUpdateDTO[].class);
return gson.toJson(consultaPlanesComisionPortal.estadoPlanesServicios(fromJson));
}
#Transactional(rollbackFor = { Exception.class })
public replyDTO estadoPlanesServicios(ServiciosPlanesUpdateDTO[] list) {
System.out.println("data: "+list.toString());
replyDTO re = new replyDTO();
int count = 0;
try {
StringBuilder update = new StringBuilder();
update.append("UPDATE Detalleproductoservicio ");
update.append(" SET loginregistro = ?, estado = 'D', fechasys = sysdate ");
update.append(" WHERE codigo_Servicio = ? and codigo_planproductoservicio = ? and NIT = ?");
try (Connection conexion = obtenerConexion.obtenerConexion(0);
PreparedStatement cstmt = conexion.prepareStatement(update.toString())) {
conexion.setAutoCommit(false);
for(ServiciosPlanesUpdateDTO elements: list) {
//System.out.println(elements.toString());
System.out.println("1 element:"+elements.getLoginRegistro());
System.out.println("2 element:"+elements.getCodigoServicio());
System.out.println("3 element:"+elements.getCodigoPlanProductoServicio());
System.out.println("4 element:"+elements.getNit());
cstmt.setString(1, elements.getLoginRegistro().trim());
cstmt.setInt(2,Integer.parseInt( elements.getCodigoServicio().trim()));
cstmt.setString(3, elements.getCodigoPlanProductoServicio().trim());
cstmt.setString(4, elements.getNit().trim());
count = cstmt.executeUpdate();
//cstmt.execute();
//count++;
//cstmt.addBatch();
//cstmt.executeBatch();
//
}
conexion.commit();
if(count > 0) {
re.setMessage("Status ok,"
+"count: "+count);
re.setExitoso(true);
}else {
re.setExitoso(false);
re.setMessage("failed");
}
}
} catch (Exception e ) {
re.setExitoso(false);
re.setMessage(e.getMessage());
}
return re;
}
this is working I found the problem apparently the database conflicts when I have Oracle SQL Developer open and I make the request by postman this is a little weird but I closed Oracle Developer and it worked.
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"));
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>
OK, I have a JSP running the following script section.
<% irCollection mgrq = new irCollection();
mgrq.setMgrid("Chris Novish");
mgrq.populateCollection();
int pagenum;
if (request.getParameter("p") != null) {
String pagedatum=request.getParameter("p");
pagenum = Integer.parseInt(pagedatum);
} else { pagenum = 0; }
for (int i=0;i<10;i++) {
int rownum = pagenum * 10 + i;
InquireRecord currec = mgrq.getCurRecords(rownum);
out.println(currec.getID()); %>
irCollection has an ArrayList property that stores a several InquireRecord objects. It gets this data from a database using the mgrid as (set in line 2 there) as the matching term.
But I'm getting an IndexOutOfBounds exception on what appears here as line 11.
I've done some tests, and I'm pretty sure that it's because populateCollection() isn't getting things done. I have a getSize method that gives me a size of 0.
I made a test class in Eclipse to make sure all my methods were working:
package com.serco.inquire;
public class test {
public static void main (String[] args) {
String mgr = "Chris Novish";
irCollection bob = new irCollection();
bob.setMgrid(mgr);
bob.populateCollection();
InquireRecord fred = bob.getCurRecords(1);
System.out.println(fred.getID());
}
}
That test class produces exactly what I'd expect.
Other than the names of some of the local variables, I can't see what I'm doign different in the JSP.
So... tell me, what noobish mistake did I make?
for the sake of being thorough, here's the populateCollection() method:
public void populateCollection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "inquire.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute ("SELECT * FROM inquiries WHERE manager = '" + mgrid + "'");
ResultSet rs = s.getResultSet();
int cur;
if (rs != null) {
while (rs.next()) {
cur = rs.getRow();
cur -- ;
int curID = rs.getInt("ID");
this.newIR.setID(curID);
String cursub = rs.getString("submitter");
this.newIR.setSubmitter(cursub);
this.iRecords.add(cur, this.newIR);
}
this.size = iRecords.size();
this.pages = this.size / 10;
int remain = this.size % 10;
if (remain > 0) { this.pages++; }
} else { System.out.println("no records."); }
}
catch (Throwable e) {
System.out.println(e);
}
}
Your IndexOutOfBounds exception is probably being caused by the value of rownum being passed to mgrq.getCurRecords().
Your test code proves nothing because there you're calling getCurRecords() with a constant which is probably always valid for your system and will never cause the exception.
My suggestion is to step through the code in your JSP with a debugger, or even simply to print out the value of your variables (especially pagedatum, pagenum and rownum) in your JSP code.
Is your JSP Snippet correct? It looks like you started the braces for the
for (int i=0;i<10;i++) {
but I dont see a end braces for that at all. Can you check if that is the case and if so, fix the code appropriately?
how to generate RSS for news sites programmatically? I dont know how to start..
I learned how to write RSS from this article:
http://www.petefreitag.com/item/465.cfm
You can also just go to an RSS feed you like and press "View Source". Then you should simply use your java application to reproduce an XML similar to the XML you see (Only with your data).
When you finish, use one of many RSS Validators to validate your RSS.
It's easier than it first looks...
This code shows how to query a database to generate arbitrary XML from a JSP, manually.
It's not RSS, but the idea might be helpful to you.
private String ExecQueryGetXml(java.sql.PreparedStatement stmt, String rowEltName) {
String result= "<none/>";
String item;
java.sql.ResultSet resultSet;
java.sql.ResultSetMetaData metaData ;
StringBuffer buf = new StringBuffer();
int i;
try {
resultSet = stmt.executeQuery();
metaData= resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
String[] columnNames = new String[numberOfColumns];
for( i = 0; i < numberOfColumns; i++)
columnNames[i] = metaData.getColumnLabel(i+1);
try {
// if ((root!=null) && (!root.equals("")))
// buf.append('<').append(root).append('>').append('\n');
// each row is an element, each field a sub-element
while ( resultSet.next() ) {
// open the row elt
buf.append(' ').append('<').append(rowEltName).append(">\n");
for( i= 0; i < numberOfColumns; i++) {
item = resultSet.getString(i+1);
if(item==null) continue;
buf.append(" <").append(columnNames[i]).append('>');
// check for CDATA required here?
buf.append(item);
buf.append("</").append(columnNames[i]).append(">\n");
}
buf.append("\n </").append(rowEltName).append(">\n");
}
// conditionally close the row elt
// if ((root!=null) && (!root.equals("")))
// buf.append("</").append(root).append(">\n");
result= buf.toString();
}
catch(Exception e1) {
System.err.print("\n\n----Exception (2): failed converting ResultSet to xml.\n");
System.err.print(e1);
result= "<error><message>Exception (2): " + e1.toString() + ". Failed converting ResultSet to xml.</message></error>\n";
}
}
catch(Exception e2) {
System.err.print("\n\n----Exception (3).\n");
System.err.print("\n\n----query failed, or getMetaData failed.\n");
System.err.print("\n\n---- Exc as string: \n" + e2);
System.err.print("\n\n---- Exc via helper: \n" +
dinoch.demo.ExceptionHelper.getStackTraceAsString(e2));
result= "<error><message>Exception (3): " + e2 + ". query failed, or getMetaData() failed.</message></error>\n";
}
return result;
}
How about using a framework like Rome or jrss