I have a CSV file which has lastname and first name, i have a jsp file to to retrieve the data from CSV file. This is what I have done so far:
<body>
<%
String file = "C:\\Users\\user\\Desktop\\file.csv";
String line;
int count = 0;
int i = 0;
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
%>
<table border=0>
<%
while((line = dis.readLine())!=null) {
%>
<tr>
<%
String[] str = line.split(",");
for(int j=0; j<str.length; j++) {
%>
<td>
<%
out.print(" " + str[j] + " ");
%>
</td>
<%
}
%>
</tr>
<%
//out.println("<br>");
i++;
}
%>
</table>
</body>
</html>
But I need to sort the table based on last name, so what should I do in jsp file?
You may want to store first and last name into a List and then can sort that List Using Collection.sort method and displaying that list straight away in your jsp.
BTW you should not do this thing inside scriplet tag ,instead you can do all this inside a servlet class.In place of hardcoding filepath you should use something like property files .
Related
when i edit table and hitting update , after that if i press view button the contents of table set to null.. please help me out of this..
This is my index.jsp page used to retrieve data from database.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "test";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<html>
<body>
<!-- <h1>Retrieve data from database in jsp</h1> -->
<table border="1">
<tr>
<td>id</td>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>update</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from users";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td contenteditable><%=resultSet.getString("id") %></td>
<td contenteditable><%=resultSet.getString("first_name") %></td>
<td contenteditable><%=resultSet.getString("last_name") %></td>
<td contenteditable><%=resultSet.getString("city_name") %></td>
<td contenteditable><%=resultSet.getString("email") %></td>
<td>update</td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
This my update-process.jsp, this is used to store data back to database.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%! String driverName = "com.mysql.jdbc.Driver";%>
<%!String url = "jdbc:mysql://localhost:3306/test";%>
<%!String user = "root";%>
<%!String psw = "root";%>
<%
String id = request.getParameter("id");
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
if(id != null)
{
Connection con = null;
PreparedStatement ps = null;
int personID = Integer.parseInt(id);
try
{
Class.forName(driverName);
con = DriverManager.getConnection(url,user,psw);
String sql="Update users set id=?,first_name=?,last_name=?,city_name=?,email=? where id="+id;
ps = con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2, first_name);
ps.setString(3, last_name);
ps.setString(4, city_name);
ps.setString(5, email);
int i = ps.executeUpdate();
if(i > 0)
{
out.print("Updated");
}
else
{
out.print("There is a problem in updating Record.");
}
}
catch(SQLException sql)
{
request.setAttribute("error", sql);
out.println(sql);
}
}
%>
<html>
<body>
<form action="index.jsp">
<input type="submit" value="view">
</form>
</body></html>
First of all, I'll suggest you not to put any java code in jsp. Your code looks very messy and its hard for bug finding and further maintenance. I'm not sure about it but as per below lines of code:
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
you will always get null because you are no where having these input fields. The input fields generate request params or you need to append those requestParams in your access url like you have done for id.
Edit: In your index.jsp change:
<td>update</td>
to
<td><a href='update-process.jsp?id=<%=resultSet.getString("id")%>&first_name=<%=resultSet.getString("first_name")%>&last_name=<%=resultSet.getString("last_name")%>&city_name=<%=resultSet.getString("city_name")%>&email=<%=resultSet.getString("email")%>'>update</a></td>
But its a very bad approach to do this.
Better you write one servlet, have a html form in index.jsp with all the input fields.
I just wanted to upload the image using form in JSP, for that I have written a code, as per below code, it is not inserting in while loop. resultant Image is not getting uploaded in directory.
Can you please help to figure out the problem?
html code
<html>
<head><title>Upload page</title></head></p> <p><body>
<form action="upload_jsp.jsp" method="post" enctype="multipart/form-data" name="form1" id="form1">
<center>
<table border="2">
<tr>
<td align="center"><b>Multipale file Uploade</td>
</tr>
<tr>
<td>
Specify file: <input name="file" type="file" id="file">
<td>
</tr>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
<tr>
<td>
Specify file:<input name="file" type="file" id="file">
</td>
</tr>
<tr>
<td align="center">
<input type="submit" name="Submit" value="Submit files"/>
</td>
</tr>
</table>
<center>
</form>
</body>
</html>
jsp code
<%# page import="java.util.List"%>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.ResourceBundle" %>
<%# page import="java.io.File"%>
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%
String path= "C:\\Users\\gur29175\\Desktop" ;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
String directory="";
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
} else {
try {
String itemName = item.getName();
File savedFile = new File(path+itemName);
//File savedFile = new File("C:\\Users\\sagar\\Desktop\\JAVA Training\\code(1)\\test\\WebContent\\WEB-INF\\uploads\\"+itemName);
//File savedFile = new File(config.getServletContext ().getRealPath("/")+"uploadedFiles/"+itemName);
item.write(savedFile);
//out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+config.getServletContext().getRealPath
//("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
out.println("<tr><td><b>Your file has been saved at the loaction:</b></td></tr><tr><td><b>"+path+
("/")+"uploadedFiles"+"\\"+itemName+"</td></tr>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
%>
This is the line of code that might be problematic, as item.getName() will return the full path where the source file is located. This might result to a malformed file path.
Try replacing:
String itemName = item.getName();
with:
String itemName = FilenameUtils.getName(item.getName());
Make sure FilenameUtils is imported:
<%# page import="org.apache.commons.io.FilenameUtils" %>
and you have commons-io.jar in your Web app libraries.
I have aproblem. Here I am showing some bills from Invoice table in mysql. And for single bill I am keeping a checkbox. I want to pass selected checkbox values to next jsp page. Please help me to do it. Thanks in advance.
<%
String company_name=request.getParameter("c_name");
try
{
Integer count=0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","aadi");
Statement st = con.createStatement();
String sql="select invoice_no, invoice_date, gross_amount from tbl_invoice where client='"+company_name+"'";
ResultSet rs=st.executeQuery(sql);
%>
<center>
<table id="show_table">
<tr>
<td>PNR No</td>
<th>Date</td>
<th>Amount</td>
<th>Select</td>
</tr>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getInt(3)%></td>
<td><input type="checkbox" name="ck"/></td>
</tr>
%>
</table>
</center>
<%
}
catch(Exception e)
{
out.println(e);
}
%>
Hey I found the solution. On action page where I am going to receive values I will store all checkbox names in a array of string.
String selected_Checkboxes=request.getParameterValues("ck");
I will just change "td" tag of checkbox. I will put value of PNR NO which is coming from database and will put in checkbox.
<td><input type="checkbox" value="<%=rs.getInt(1)%>" name="ck"/></td>
I will use indexes of "selected_Checkboxes" to do further coding.
--Thanks Santino 'Sonny' Coleone
I am developing a web application using JSP and Servlets.
In that application I have to show data from database table stud(studID, name, add) in html table, And each row in the table will have a hyperlink associated with it at the last column. After clicking on that hyperlink I wants to get the (studID) from the table...
so far I have done getting the data from database and then putting it into the column and then adding hyperlink for each row.. But I am not able to get the (studID) from the html table associated with hyperlink..
Thanks in advance....
Source code :
<%
String[][] data = (String[][])request.getAttribute("data");
String[] cNames = (String[])request.getAttribute("columnNames");
//headings
%>
<table>
<tr>
<%
for(int i=0;i<cNames.length;i++) {
%>
<th>
<%= cNames[i] %>
</th>
<%
}
//data if(data!=null)
for(int i=0;i<data.length;i++) {
%>
<tr>
<%
for(int a=0;a<3;a++) {
%>
<td>
<%=
data[i][a]
%>
</td>
<%
//hyperlink
if(a==2) {
%>
<td>
<a href="PlanProtocol" id=<%=i%> onclick="<% session.setAttribute("ID","p2"); %>" >Edit</a></td>
<%
}
}
%>
</tr>
<% } %>
<tr>
</table>
You can pass the id as a query string in the url. Simply:
My Link
Will work. But if you are using JSTL or another tag library then you can do something like this:
<c:url value="/myservlet" var="myURL">
<c:param name="id" value="1234"/>
</c:url>
mylink
And this has its advantages such as url encoding etc.
So to add the id to the URL in your posted code you can:
<a href="PlanProtocol?id=<%=i%>" >Edit</a>
And the url will end up like this: PlanProtocol?id=1234.
In the Servlet you can get the Parameter by:
request.getParameter("i");
However, as I mentioned above, you probably want to use a tag library like the JSTL rather than placing these scriptlets in your page. There are several advantages.
think you should pull out the studID in JSP and format the studID into the query string of the URL, html page. (?studID=xxxxx) So the servlet will know the studID.
You can use request.setAttribute("studID","value"); in your jsp page to set the value and use request.getAttribute("studID"); in servlet to get value
I have to get the images from the database (oracle 10g) and display them, but I am unable to display the images. My code is:
<%
String[] salespersons;
String[] name;
String[] photoid;
String tempid="", tempname="", tempphoto="";
ResultSet rs = statement.executeQuery("select * from Employees where ManagerID=" + managerid);
while(rs.next()) {
tempid += rs.getInt("id") + ";";
tempname += rs.getString("firstname") + ";";
tempphoto += rs.getString("photoid") + ";";
}
salespersons = tempid.split(";");
name = tempname.split(";");
photoid = tempphoto.split(";");
%>
<input type="button" value="CLOSE" onclick="window.close()" />
<table border="5" cellpadding="2" align="center">
<%
for(int ite=0; ite < name.length; ite++) {
%>
<tr>
<td><%=salespersons[ite]%></td>
<td><%=name[ite]%></td>
<td><img src="<%=photoid[ite]%>" alt="image not available"/></td>
<td></td>
<%
}
%>
</tr>
</table>
Image has a wrong path than only image not showing first print image path and then put it as a image url...