Servlet Jsp Array Printing Links - java

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>

Related

Edit button on a dynamic table in jsp servlet application

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;
}
}

How to send JSON data to a Dojo data grid?

I had written a JSP page with database connectivity getting the data from the database and printing it JSON format.
And now I want that JSON data to be sent to the Dojo data grid
Here is my JSP code.
<html>
<head>
<script type="text/javascript">
dojo.require("dojox.data.QueryReadStore");
dojo.require("dojox.grid._CheckBoxSelector");
dojo.require("dojo.data.ObjectStore");
dojo.require("dojo.parser");
dojo.require("dojox.grid.DataGrid");
dojo.require("dijit/form/Button");
dojo.require("dojox/grid/DataGrid");
dojo.require("dojo/data/ItemFileReadStore");
dojo.ready(function(){
mystore=new dojox.data.QueryReadStore({url:"/DojoProject/test"});
grid = new dojox.grid.DataGrid({
store: mystore,
structure: [
{type: "dojox.grid._CheckBoxSelector", editable: true},
[{name:"id", field:"ID", width: "200px",editable: true},
{name:"name", field:"name", width: "200px",editable: true},
{name:"Result", field:"Result", width: "200px"}]
]}, dojo.byId("gridContainer"));
grid.startup();
});
</script>
<%
JSONObject responseObj = new JSONObject();
List<JSONObject> data = new LinkedList<JSONObject>();
try {
String dbms = "SQL SERVER";
String serverName = "";
String portNumber = "1106";
String userName = "";
String upassword = "";
String databaseName = "";
int datacount = 0;
//String connectionURL = "jdbc:" + dbms + "://" + sN
// + ":" + PN + "/" + databaseN;
Connection conn = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("");
System.out.println("connection::" + conn);
String strQuery = "select * from sample";
System.out.println(strQuery);
PreparedStatement st = conn.prepareStatement(strQuery);
ResultSet rs = st.executeQuery();
while(rs.next()) {
datacount++;
JSONObject object = new JSONObject();
object.put("s1",(String.valueOf(datacount)));
object.put("ID",rs.getString(1));
object.put("Name",rs.getString(2));
System.out.println("ID&name&::"+rs.getString(1) +","+rs.getString(2));
}
responseObj.put("data",data);
PrintWriter writer = response.getWriter(); System.out.println({\"identifier\":\"data\",\"label\":\"data\",\"items\":"+responseObj+"}");
writer.write(" "+responseObj+"");
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
} %>
<head>
<body class="claro">
<div id="some">
<div id="gridContainer" style="width: 100%; height: 200px;">
<button data-dojo-type="dijit/form/Button" type="submit" name="submitButton" value="Submit">Submit</button> </div>
</div>
</body>
</html>
Here, I am getting the data from the database in the JSON format as following:
{"data":[{"sl":"1","id":"1","name":"shivasrinat"}
{"data":[{"sl":"1","id":"1","name":"shivasrinat"}
The QueryReadStore needs the data from JSP on a specific JSON format, otherwise it doesn't know what to do with it.
Take a look at the very last line of the sample PHP implementation for a QueryReadStore backend:
print '/*'.json_encode(array('numRows'=>$numRows, 'items'=>$ret, 'identity'=>'id')).'*/';
It's not so different from your format, but you see it requires 3 specific keys: numRows, items and identity. You only have one: data. So try changing your JSP to output something like this:
{"numRows":42, "identity":"id", "items": [{"sl":"1","id":"1","name":"shivasrinat"}] }
The numRows attribute should be the total number of items available that matches the query (because sometimes you only want to retrieve a small amount, not the entire database).

Get Value of dynamically create dropdownlist in JSP

I am new to JSP and servlet for 1 month, and there are many things that I am still unsure off.. Inside a JSP, I have a dropdownlist(the values inside are grab from database) and it would be dynamically created on the number that the user keyed in. Example, the user key in 3, this digit would store in session, and 3 dropdownlist would be generated.
I am able to do this, however I am unable to grab the value of all the 3 dropdownlist in a servlet. and instead of getting 3 diff values, the output repeat the value of the first dropdownlist. Example "john,john,john" instead of "john, ken, andy".
JSP code:
<form action="Adding" method="post">
<%
session = request.getSession();
ProjectGroup projGrp1 = (ProjectGroup)session.getAttribute("PROJECTNAME");
//getMaxMember is the int that user keyed in
int staff =projGrp1.getMaxMember();
for(int i = 0; i < staff; i++) {
%>
<select name="list1" >
<%#page import="sit.bean.*,sit.data.*"%>
<%
GroupTaskManager mgr3 = new GroupTaskManager();
GroupTask[] at3 = mgr3.getCheckBox();
for(int g = 0; g < at3.length; g++) {
%>
<option><%=at3[g].getStaffName()%></option>
<%
}
%>
</select>
<%
}
%>
<input type="submit" name="submit">
</form>
In servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
ProjectGroup projGrp = (ProjectGroup)session.getAttribute("PROJECTNAME");
int member = projGrp.getMaxMember();
String total = null;
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1");
total += names + " , ";
}
PrintWriter pw = response.getWriter();
pw.write("<HTML><BODY>");
pw.write(total);
pw.write("</HTML></BODY>");
pw.close();
}
Can i set the downdownlist name like "list<%i%>", to set different id to each downdownlist? therefore i can retrieve each of them seperately???
In servlet you are getting same parameter every time which is list1 in loop.
and also in JSP creating dropdownlist with same name attribute,
that's why you are getting john,john,john instead of john, ken, andy.
Yes you can use list<%i%> to set different id as well as name
change your select with below in JSP
<select name="list<%=i%>" >
and for loop in servlet with below
for(int i=0; i< member; i++)
{
String names = request.getParameter("list1"+i);
total += names + " , ";
}

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();
});

Chat app popup a window at client

I made a simple chat app. It uses database, this is not efficient cause the client queries database every few sec. Any way, I achieved what i needed, There are good ways out there like polling and commet, I will implement those later. Please take time to read abt this, I have few probs with this.
1) Consider two users 100 and 101, When 100 sends a msg to 101, i am saving the id as 100_101 in DB
2) When 101 send back msg to 100 it is saved as 101_100 in DB.
3) I am able to get the messages in order.
Problem-
1) Users should keep tht particular window open.
I want popup to open when there is new message. How to achieve that.
2) When a user(100) is typing user(101) should see the text as "100 is typing" if 101 chat window with 100 is open only. This should not involve any database stuff.
Work I have done. I can send data to server when user(100) starts typing to server. How to send data, i.e how to push data to user(101).
My presnt code is below.
ajax
$.ajax( {
type : "POST",
data : "uName=" + uName +"&opName=" + opName + "&msg=" + msg + "&colorCode="
+ colorCode,
url : "<%= path %>/chat/SaveChat",
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
},
success : function(data) {
// alert(data);
$("#chat-area").html(data);
document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight;
}
});
Servlet
try {
String newline = System.getProperty("line.separator");
String uName = req.getParameter("uName");
String opName= req.getParameter("opName");
String msg = req.getParameter("msg");
String colorCode = req.getParameter("colorCode");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dat =dateFormat.format(date);
PreparedStatement ps = db.conn.prepareStatement("INSERT INTO chatmessage"
+ "(message,username,msgtime,colorselected) "
+ " VALUES(?,?,?,?)");
ps.setString(1,msg);
ps.setString(2,uName+"_"+opName);
ps.setString(3,dat);
ps.setString(4,colorCode);
ps.executeUpdate();
ps.close();
ps = db.conn.prepareStatement("select * from chatmessage where username=? or username=? order by id asc");
ps.setString(1,uName+"_"+opName);
ps.setString(2,opName+"_"+uName);
ResultSet rs=ps.executeQuery();
String temp[];
StringBuilder sb = new StringBuilder();
while(rs.next())
{
temp=rs.getString("username").split("_");
/* out.println(newline);
out.print(temp[0]+":");
out.print(rs.getString("message"));
out.println(newline);*/
sb.append("<span style='background:#"
+ rs.getString("colorselected") + "'>" + temp[0]
+ "</span>" + rs.getString("message") + "<br/><br/>");
}
db.conn.close();
out.print(replaceEmoticons(sb.toString()));
//out.print("success");
}
catch(Exception ce){
out.println("<font size='30' color='red'>Error Code 004</font>");
// RequestDispatcher rd = req.getRequestDispatcher("../status/error.jsp");
// rd.forward(req, res);
}finally{
try{
db.conn.close();
}catch(Exception e){}
}
Thankyou any easy and valid ideas are appreciated.

Categories

Resources