I want to display table contents and edit the the specific row obtained based on unique id fetched by clicking submit button for respective row.
Below code is for listing all the records from table with edit button on every row:
<TABLE align="Center" border="1px" width="80%">
<%Iterator itr;%>
<%List data=(List) request.getAttribute("UserData");
for(itr=data.iterator();itr.hasNext();)
{%>
<tr>
<% String s= (String) itr.next(); %> <!-- Stores the value (uniquie id) in the String s -->
<td><%=s %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
When I click the edit button I want to get the value from first column and first row which contains unique id.
The code fetching the value from String "s" is given below:
<form id="edit" action="EditRecord" method="post" onsubmit=<%=s %>>
<td><input type="submit" value="Edit" name="edit"> </td>
</form>
Now I want to pass this value stored in String s to my servlet "EditRecord" but somehow the value is not getting passed.
The code for servlet is given below:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn;
Statement stmt;
ResultSet res = null;
String id ;
String query;
DatabaseConnection dbconn;
// protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
id=request.getParameter("id");
System.out.println(id);
dbconn=new DatabaseConnection();
conn=dbconn.setConnection();
System.out.println(conn);
stmt=conn.createStatement();
System.out.println(stmt);
query="select * from user_details where User_id="+id;
res=dbconn.getResultSet(query, conn);
System.out.println(res);
}catch (Exception e)
{
}finally{
request.setAttribute("EditData",res );
RequestDispatcher rd=request.getRequestDispatcher("/editdata.jsp");
rd.forward(request, response);
out.close();
}
}
}
Could anyone tell me where I am making the mistake..Please guide me
Thanks in advance
The onSubmit event is invoked when the submit button is clicked, but it doesn't send any data to the server.
In your case I suggest you to add a hidden input to the form, so it will be sent to the server when submit button is clicked. Check the code below:
<form id="edit" action="EditRecord" method="post" >
<td><input type="hidden" id="id" value="<%=s %>"/>
<input type="submit" value="Edit" name="edit"> </td>
</form>
Related
i am creating a simple crud system in Java Servlet. I am beginner of Servlet.I filled the form and clicked submit button and got the error - HTTP Status 404 - Not Found. I have attached the screen shot image below along with the code.
folder structure
Form
<form method = post action = "employee/employee.java">
<table class="table table-borederd">
<tr>
<td>Enter Employee ID:</td>
<td ><input class="form-control" type = "text" name = "txtEmpId"/></br></td>
</tr>
<tr>
<td>Enter Employee FirstName:</td>
<td ><input class="form-control" type = "text" name = "txtFName"/></td>
</tr>
<tr>
<td>Enter Employee LastName:</td>
<td ><input class="form-control" type = "text" name = "txtLName"/></td>
</tr>
<td><input type = "submit" value = "submit"/></td>
</form>
employee.java
public class employee extends HttpServlet
{
Connection con;
int row;
public void doPost(HttpServletRequest req, HttpServletResponse rsp) throws IOException, ServletException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/empp","root","");
System.out.println("Connection Established");
}
catch(Exception e)
{
System.out.println("Sorry...........");
}
rsp.setContentType("text/html");
PrintWriter out = rsp.getWriter();
String empId = req.getParameter("txtEmpId");
String empFName = req.getParameter("txtFName");
String empLName = req.getParameter("txtLName");
try
{
PreparedStatement stat = con.prepareStatement("insert into record (id,fname,lname) Values(?,?,?)");
stat.setString(1,empId);
stat.setString(2,empFName);
stat.setString(3,empLName);
row = stat.executeUpdate();
}
catch(Exception e)
{
}
out.println("<html>");
out.println("<font color = 'red'>Sucessfully registered!</font>");
out.println("</body>");
out.println("<h2>");
out.println(row);
out.println("</h2>");
out.println("</body>");
}
}
I have been trying to list out the data that is in a specific table in my database. The data is only retrieved when i just execute the particular servlet. It does not fetch that list when i have logged in and has created a session and is directed to that particulr jsp page. I only get an empty page.
I have tried getting the session attribute to that jsp page but it does not work
list-medicine.jsp
<body>
<%
if(session.getAttribute("email")==null)
{
response.sendRedirect("login.jsp");
}
%>
<div>
<div id="wrapper">
<div id="header">
Welcome ${email}
add medicine
</div>
</div>
<form action="UserLogoutControllerServlet">
<input type="submit" value="Logout">
</form>
<div id="container">
<div id="content">
<table>
<tr>
<th>Name</th>
<th>Amount</th>
<th>Price</th>
<th>Email of the user</th>
</tr>
<c:forEach var="tempStudent" items="${MEDICINE_LIST}">
<tr>
<td>${tempStudent.name}</td>
<td>${tempStudent.amount}</td>
<td>${tempStudent.price}</td>
<td>${tempStudent.email}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
</body>
MedicineControllerServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
//list tje medicine...in MVC fashion
{
listMedicine(request,response);
}
catch(Exception e)
{
throw new ServletException(e);
}
}
private void listMedicine(HttpServletRequest request, HttpServletResponse response) throws Exception {
//get medicine from db util
List<Medicine> medicine=medicineDbUtil.getMedicine();
//add medicne from db util
request.setAttribute("MEDICINE_LIST", medicine);
//send to jsp view(view)
RequestDispatcher dispatcher=request.getRequestDispatcher("/list-medicine.jsp");
dispatcher.forward(request, response);
}
MedicineDbUtil.java
public List<Medicine> getMedicine() throws Exception
{
List<Medicine> medicine=new ArrayList<>();
Connection myConn=null;
Statement myStmt=null;
ResultSet myRs=null;
try
{
//get a connection
myConn = dataSource.getConnection();
//create sql statement
String sql="select name,amount,price,users_email from medicine ";
myStmt= myConn.createStatement();
//execute query
myRs=myStmt.executeQuery(sql);
//process result set
while(myRs.next())
{
//retrieve data from result set row
//int id=myRs.getInt("id");
String name=myRs.getString("name");
int amount=myRs.getInt("amount");
double price=myRs.getDouble("price");
String email=myRs.getString("users_email");
//create new medicine
Medicine theMedicine=new Medicine(name,amount,price,email);
//add it to list of medicine
medicine.add(theMedicine);
}
return medicine;
}finally
{
//close jdbc objects
close(myConn,myStmt,myRs);
}
}
I want the data list fetched from the database to be shown in the jsp page while i am logged in through a session
I'm trying to get all the values from a list of selected checkboxs in a JSP Page, to a Java Class.
That's My JSP Page:
<table border="1" cellpadding="5" cellspacing="1" style="width: 877px; ">
<tr>
<th>Code</th>
<th>Name</th>
<th>Price</th>
<th>Select</th>
<th>Edit</th>
<th>Delete</th>
<th>Show</th>
</tr>
<c:forEach items="${productList}" var="product" >
<tr>
<td>${product.code}</td>
<td>${product.name}</td>
<td>${product.price}</td>
<td>
<input type="checkbox" name="ProductItem" value="${product.code}">
<c:url value="ShowProductList" var="url">
<c:param name="ProductItemP" value="${product.code}"/>
</c:url>
</td>
<td>
Edit
</td>
<td>
Delete
</td>
<td>
Show
</td>
</tr>
</c:forEach>
</table>
Show Items
As you can see there is a Table with a list of items with a check box in each line. At the end of the table there is button "Show Items" that triggers the user's request.
That's the servlet class that perform the request:
#WebServlet(urlPatterns = { "/ShowProductList" })
public class ShowProductList extends HttpServlet {
private static final long serialVersionUID = 1L;
public ShowProductList() {
super();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
String[] paramValues = request.getParameterValues("ProductItemP");
System.out.println(paramValues.length);
response.sendRedirect(request.getContextPath() + "/productList");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
When an user select two or more checkbox and click on the button "Show item" I can have only the last product code with the checkbox clicked and not all the codes with the box selected. If I Try request.getParameterValues("ProductItem"); I have a null value. I'd prefer to not have code in the JSP Page (if it is possible.)
Can someone help me find a solution ?
Thanks for your patience.
`
In table 10 rows are there..selected data has to delete (using check box) and display all the content in table....Here newsid in JSP file is auto incremented value....
This is DeleteSuccess.java File
public class DeleteSuccess extends HttpServlet {
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession();
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/MyDataBase","root","root");
PreparedStatement ps = con.prepareStatement("delete from ROOT.NEWSTABLE where newsid='" + (* here what i have 2 write *) +"'");
int i= ps.executeUpdate();
PreparedStatement pss = con.prepareStatement("select NEWSID,NEWS from ROOT.NEWSTABLE");
ResultSet rs =pss.executeQuery();
ArrayList<News> listnewsobj = new ArrayList<News>();
while(rs.next())
{
News obj=new News();
obj.setNewsId(rs.getInt(1));
obj.setNews(rs.getString(2));
listnewsobj.add(obj);
}
session.setAttribute("listnewskey",listnewsobj);
System.out.println(listnewsobj);
if (i > 0)
{
System.out.println("Venkatesh");
//out.print("You are successfully registered...");
//RequestDispatcher rs = request.getRequestDispatcher("Login.html");
// RequestDispatcher rd = request.getRequestDispatcher("JSP/AddNews.jsp");
// rd.include(request, response);
response.sendRedirect("JSP/AddNews.jsp");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
This is JSP file
<form method="post" action="../newsdelete">
<fieldset class="rt">
<legend> <b> Manage News </b> </legend>
<table>
<tr>
<th>News Id</th>
<th>News Name</th>
<th>Action</th>
</tr>
<c:forEach items="${listnewskey}" var="listnews">
<tr>
<td class="first_col">${listnews.newsId}</td>
<td>${listnews.news}</td>
<td class="third_col">
<input id="" type="checkbox" name="check" value="action"><label for="radio1"><span><span></span></span></label>
</td>
</tr>
</c:forEach>
</table>
<div> <br><input type="submit" value="Delete" name="delete"></div>
</fieldset>
</form>
This is web.xml
<servlet>
<servlet-name>Delete</servlet-name>
<servlet-class>com.venkatesh.DeleteSuccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Delete</servlet-name>
<url-pattern>/newsdelete</url-pattern>
</servlet-mapping>
Can anyone tell me how to delete the row which is checked and automatically display the information from the table in same JSP file which i have written the table in Loop...
I am trying to print checked values of checkbox list from a JSP page but nothing appears even if some selections are there.
<form action="process" method="POST">
<c:forEach var="item" items="${list.items}">
<input type="checkbox" name="chkSkills" value="${$item.Id}">${item.name}
</c:forEach>
<input type="submit" name="Getvalue" value="Get value" />
</form>
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] Answers = request.getParameterValues("chkSkills");
PrintWriter out = response.getWriter();
String ButClicked = request.getParameter("Getvalue");
if (ButClicked != null) {
for (String Answer : Answers) {
out.print(Answer + "<br>");
}
}
//processRequest(request, response);
}
Correct your value attribute to
value="${item.Id}"
Notice, there's no need to put a $ inside the {} again.