How to send JSON data to a Dojo data grid? - java

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).

Related

jsp save blob images in database mysql - my code doesn't work [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
I am creating a Dynamic Web Project, with Eclipse EE, using JSP and servlet. In the project a user will select a image file in the hard disk and send it to a mysql database in a LongBlob field.
This is my form to select the image file:
<form name="formfoto1" action="guardafotonueva.jsp" method="post">
Comentario:
<input type="text" name="comentariofoto1">
<input type="file" name="archivofoto1">
<input type="submit" name="subir" value="Enviar foto">
</form>
And this is the code that don't work:
<% String cadenanombre, cadenausuarioadmin, cadenaclaveadmin;
Connection conexion = null;
String nombrearchivofoto1, sqlfoto1, cadenacomentariofoto1, cadenacodigofoto1, cadenaarchivofoto1;
FileInputStream fisfoto1 = null;
PreparedStatement psfoto1, pscodigof1;
Vector<Integer> vectorcodigofotos;
Vector<Integer> vectorcodigocliente = new Vector<Integer>();
ResultSet rscodigof1, rscantidadclientes;
Integer rcodigof1 = 11, cantidadclientes = 0, vn;
String sql, sqlcodigof1; vectorcodigofotos = new Vector<Integer>();
String sqlactualizaclientesfotos, cadenaarchivo, cadenacodigotemafoto1, cadenacodigofotofoto1;
cadenacomentariofoto1 = request.getParameter("comentariofoto1"); URL url;
cadenaarchivofoto1 = request.getParameter("archivofoto1"); File file = null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conexion = DriverManager.getConnection("jdbc:mysql://localhost/entrenam_contenidos", "entrenam_bruno", "Bsl30121986");
session.setAttribute("sessionfoto1", cadenaarchivofoto1);
file = new File("C://Users//Aloisio//fotos//"+cadenaarchivofoto1);
}
catch(Exception ex)
{
out.println("Conexion sigue con problemas");
}
sqlcodigof1 = "select codigof1 from foto1 order by idf1 desc limit 1";
out.println("Cadena foto: "+cadenaarchivofoto1+" su longitud es: "+cadenaarchivofoto1.length()+"</br>");
pscodigof1 = conexion.prepareStatement(sqlcodigof1);
rscodigof1 = pscodigof1.executeQuery();
while(rscodigof1.next())
{
rcodigof1 = rscodigof1.getInt("codigof1"); vectorcodigofotos.addElement(rcodigof1); rcodigof1++;
}
session.setAttribute("codigosfotos", vectorcodigofotos);
session.setAttribute("cantidadfotos", vectorcodigofotos.size());
sql = "insert into foto1 (codigof1, comentariof1, archivof1, blobf1) values (?, ?, ?, ?)";
psfoto1 = conexion.prepareStatement(sql);
file = new File("C://Users//Aloisio//fotos//"+cadenaarchivofoto1);
fisfoto1 = new FileInputStream(file);
psfoto1.setInt(1, rcodigof1);
psfoto1.setString(2, cadenacomentariofoto1);
psfoto1.setString(3, cadenaarchivofoto1);
psfoto1.setBinaryStream(4, fisfoto1, (int) (file.length()));
psfoto1.execute();
%>
</body>
</html>
try
<form name="formfoto1" action="guardafotonueva.jsp" enctype="multipart/form-data" method="post">
instead of
<form name="formfoto1" action="guardafotonueva.jsp" method="post">
Try this code.
try {
MultipartHttpServletRequest multipartRequest;
MultipartFile f;
multipartRequest = (MultipartHttpServletRequest) request;
f = multipartRequest.getFile("file");
if(f != null) {
long size = f.getSize(); // size of the file
byte[] filebytes= f.getBytes() // get the file data as byte array, what you are going to store it as blob in DB
String fileName = f.getOriginalFilename(); // Name of file
}
} catch (IOException e) {
} finally {
// do something
}

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

RequestMapping does not occurs

I'm trying to communicate between two portlets by rendering the URL.
One portlet shows the table containing the list of available options. When one of the options is clicked, a javascript function renders the URL and in the second portlet should appear the detailed info about the clicked project.
However, it is not working: the URL is rendered correctly, with the proper id of the row in the URL but the method of the second portlet, set with #RenderMapping(params) is never called.
Thanks in advance
First portlet view.jsp:
<%#page import="java.util.List"%>
<%#page import="pl.spot.vorange.model.Project"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<div id="projectListDiv" style="width: 100%;"></div>
<script type="text/javascript">
var pids = new Array();
var pnames = new Array();
var projectId = "${p.id}";
<%
List<Project> all = (List<Project>) request.getAttribute("all");
if(all!=null && !all.isEmpty()) {
int i = 0;
for(Project project : all) {
out.println("pids[" + i + "]='"+project.getId()+"';\n");
out.println("pnames[" + i + "]='"+project.getName()+"';\n");
i++;
}
} else {
out.println("brak projektów w zasięgu requestu");
}
%>
function createProjectList() {
var tags = "<table width='100%'>";
for(var i=0; i<pids.length; i++) {
tags += "<tr class='projectTr'>";
tags += "<td class='orangeArray' onClick='firePortletEvent2(" + pids[i] +
")'> </td>";
if(pids[i]!=projectId) {
tags += "<td class='orangeTableItem' onClick='firePortletEvent2(" +
pids[i] + ")'>";
} else {
tags += "<td class='orangeTableItemSel'
onClick='firePortletEvent2(" + pids[i] + ")'>";
}
tags += pnames[i] + "</td></tr>";
}
tags += "</table>";
el = document.getElementById("projectListDiv");
if(el!=null) {
el.innerHTML = tags;
}
}
function firePortletEvent2(projectId) {
var url ="<portlet:renderURL />";
prefix = "&_offer2_WAR_vorange_";
url += prefix+"a=getproject";
url += prefix+"page=expiring";
url += prefix+"tab=expiringOffers";
url += prefix+"pid="+encodeURI(projectId);
location = url;
}
createProjectList();
</script>
Clicking on one of the projects renders the URL.
Second portlet controller:
#RenderMapping(params = "a=getproject")
public String getProject(RenderResponse response, RenderRequest request) {
String pid = request.getParameter("pid");
Project p = null;
if (pid != null) {
long id = Long.parseLong(pid);
p = projectService.searchById(id);
request.getPortletSession().setAttribute("project", p);
}
p = (Project) request.getPortletSession().getAttribute("project");
request.setAttribute("p", p);
return "view";
}
I don't know if it's working correctly because this method is never called.
I know the code is messy but I haven't written it. I just obtained it and I must fix it.
I wouldn't be surprised if this code will never work but I have just started developing on Liferay and don't know many things.

Creating a random password generates a password with length 0: Blame JavaScript or Java Servlet?

When my users forget their passwords, they are sent to the page shown below. I generate a random password in JavaScript, encrypt it, and send both the plain text and md5 hash to a Servlet. The Servlet then e-mails the password to the user and stores the md5 hash in my database. This process works fine most of the time. But for some reason frequently generates an error where the generated password has length 0.
I tested my JavaScript code separately and had it generate hundreds of passwords. None had length 0. So where is this error coming from?
Here is the HTML form:
//This method returns a randomly generated mathy password.
function randomPassword(theForm) {
first = ["Euler", "Erdos", "Newton", "Eucl1d", "Gauss", "H1lb3rt", "Cantor", "Bernoulli", "PascaL"];
second = ["Const", "Number", "Theorem", "Prime", "Ratio", "Lemma", "Postulate", "Method", "Algorithm"];
symbol = ["!","#","#","$","%","^","&","*","_","+","-","?"];
a = Math.floor(Math.random() * first.length);
b = Math.floor(Math.random() * second.length);
n = Math.floor(Math.random() * 10);
style = Math.floor(Math.random() * 3); //0,1, or 2
if(style==0) password = first[a] + n + second[b];
else if(style==1) password = first[a] + second[b] + n;
else password = first[a] + second[b] + symbol[n];
theForm['newPass'].value = password;
theForm['passwordLog'].value = "style="+style + " a=" + a + ", b=" + b+ ", n=" + n;
hashField = theForm['passHash'];
hashField.value = hex_md5(password);
theForm.submit();
}
<body>
<h2>You can reset your password below.</h2>
<form action="ResetPassword" method="post" >
Enter your e-mail address:
<input type="text" name="eMail" id="eMail" size="20"/> <br />
<input type="button" value="Reset Password" onclick="randomPassword(this.form);" />
<input type="hidden" id="passHash" name="passHash" />
<input type="hidden" id="newPass" name="newPass" />
<input type="hidden" id="passwordLog" name="passwordLog" />
</form><br/>
<strong>Attention Coaches: If you are having trouble logging into this system,
please contact the scorekeeper: llaspina#bethpage.ws </strong>
</body>
And here is the Servlet that receives the form data sent from the above file:
#WebServlet(name = "ResetPasswordServlet", urlPatterns = {"/ResetPassword"})
public class ResetPasswordServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ConnectionPool pool = ConnectionPool.getInstance();
java.sql.Connection con = pool.getConnection();
String emailAddress = request.getParameter("eMail");
String newPass = request.getParameter("newPass");
String passHash = request.getParameter("passHash");
String log = request.getParameter("passwordLog");
try {
Coach coach = null;
ArrayList<Coach> coachList = MathTeamDAO.getAllCoaches(con);
for(Coach c : coachList) {
if(c.email.equals(emailAddress) ) {
coach = c;
break;
}
}
out.println("<html><head><title>Scorekeeper Reset Password Servlet</title></head>");
out.println("<body>");
out.println("<h1>Reset Password Servlet</h1>");
if(coach==null) {
out.println("Your email address was not found in our database.<br/>" +
"Please contact the scorekeeper or the secretary to gain access to the sytem.");
}
else {
if(newPass == null || newPass.length()<3) {
out.print("An error occurred while generating a random password. The randomly generated password came back as ");
out.print(newPass);
out.println(" Please try to reset your password again.");
String errorMsg = "An error was encountered while attempting a password reset. ";
if(newPass==null)
errorMsg += "null newPass generated.";
else
errorMsg += " The newPass had length " + newPass.length() + " and =" + newPass;
if(log!=null)
errorMsg += ("\n" + log);
if(UtilityServlet.emailAnError(coach,errorMsg, this.getServletName() + " at " + this.getServletName()))
out.println("<br/>The scorekeeper was just informed of this error through email, so you do not need to report it.");
}
else {
out.println("<h3>Check your email for your new password and directions for signing into the scorekeeper system.</h3>");
out.print("Sending new password to " + coach.email + "<br/>");
ChangePasswordServlet.changePassword(con, coach.schoolID, passHash);
School herSchool = MathTeamDAO.getSchoolByCoach(con, coach);
String emailServerMessage = ChangePasswordServlet.sendPasswordEmail(coach, herSchool.shortName, newPass);
if(herSchool!=null) {
out.print("<br/>The username for " + herSchool.fullName);
out.print(" is <strong>");
out.print(herSchool.username);
out.println("</strong><br/>");
}
out.print(emailServerMessage);
}
out.flush();
}
out.println("<br/>Return to <a href=\"login.jsp\" >login page.</a>");
out.println("</body></html>");
}
catch(java.sql.SQLException utoh) { }
finally {
pool.freeConnection(con);
out.close();
}
}
Notice that I am having error messages sent to myself if the password is null or too short. This happens fairly regularly and they always have length 0. Why?
With the comment in the middle of this line:
else //if(style==2) password = first[a] + second[b] + symbol[n];
you are going to get undefined passwords in about a third of the cases...
else //if(style==2) password = first[a] + second[b] + symbol[n];
theForm['newPass'].value = password;
With the comment there, the else is now affecting theForm['newPass'].value = password;, meaning the value will not be set, causing an empty password.
This is why using {} is recommended even if you only have one statement.

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