Friends i have a jsp page which retrieves data from mysql table and displays them in form of table. I will also display another column consisting of a button to give Status to 1 . i need to update the database table when i click the status button.
following is the code for jsp
<form action="Edit" method="post">
<table cellspacing="8">
<tr>
<td><b>Name</b>
</td>
<td><b>Place</b>
</td>
<td><b>Gender</b>
</td>
<td><b>UserName</b>
</td>
<td><b>Password</b>
</td>
<td><b>Status</b>
</td>
<td></td>
</tr>
<%
ViewService vs = new ViewService();
ResultSet rs = vs.getRecords();
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(2) %></td>
<td><%=rs.getString(3) %></td>
<td><%=rs.getString(4) %></td>
<td><%=rs.getString(5) %></td>
<td><%=rs.getString(6) %></td>
<td><%=rs.getString(7) %></td>
<td></td>
<td><input type="text" name="userid" value="<%=rs.getString(2) %>"
style="visibility: hidden;" > <input type="submit" value="Active"></td>
</tr>
<% }
%>
</table>
</form>
And my edit servlet is
package Admin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DBcon.Dbcon;
#WebServlet("/Edit")
public class Edit extends HttpServlet {
private static final long serialVersionUID = 1L;
public Edit() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = ? where userid
= ?");
ps.setInt(7,status);
ps.setInt(1, userid);
ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}
inside while loop
put the form tag inside while loop ( < td > ) not around the < table >
....
<td><%=rs.getString(7) %></td>
<td></td>
<td>
<form action="Edit" method="post">
<input type="text" name="userid" value="<%=rs.getString(2) %>" style="visibility: hidden;" > <input type="submit" value="Active">
</form>
</td>
</tr>
<% }
%>
</table>
OR
Use Hyperlink instead of form and button
<td>
Activate
<td>
try this bro i modified your codes.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con;
PreparedStatement ps;
Dbcon db = new Dbcon();
con = db.getCon();
int status=1;
int userid =Integer.parseInt(request.getParameter("userid"));
try {
ps=con.prepareStatement("update tbluser set status = '"+status+"' where userid = '"+userid+"'");
ps.executeUpdate();
int updateQuery = ps.executeUpdate();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("ViewUser.jsp");
}
}
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>");
}
}
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 need help in checking the data into the database before insertion.
Issue:
I have used the general method to insert the values into database.But I need to include this condition into my servlet code i.e if a data is already present in the database,then that data should not be inserted into the database and the remaining data should be inserted into the database.While doing this no alert should be raised to the user.
This is my code.
products.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
Servlet code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs=null;
Connection connection = null;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
prep.close();
}
catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
}
finally {
try {
connection.close();
}
catch (Exception ex) {
System.out.println("The error is"+ex.getMessage());
}
}
}
}
Here i come up with problem while performing some operation like update,delete and insert but its return some null value with exception kindly some one could look at the code if its wrong:
Error:
HTTP Status 500 - null
type Exception report
message null
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Integer.java:454)
java.lang.Integer.parseInt(Integer.java:527)
Controller.ControllerTest.doGet(ControllerTest.java:48)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.
Apache Tomcat/6.0.37
user.jsp:
<form method="POST" action='ControllerTest' name="frmAddUser">
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
id:<input type="text" name="ID" value="<%=user.getID() %>"><br/>
Name:<input type="text" name="Name" value="<%= user.getName() %>"><br/>
Password:<input type="text" name="password" value="<%= user.getPassword() %>"><br/>
phoneno:<input type="text" name="Phoneo" value="<%= user.getPhoneo() %>"><br/>
Emailid:<input type="text" name="Emailid" value="<%= user.getEmailID() %>"> <br/>
<%} %>
<input type="submit" value="Submit" />
</form>
listuser.jsp
<body>
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td><a href="ControllerTest?action=edit&userId=<%= user.getID() %>" >Update</a></td>
<td>Delete</td>
</tr>
<% } %>
</tbody>
</table>
<p>
Add User
</p>
Controllertest.java:
package Controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.UserDao;
import dbBean.UseBean;
public class ControllerTest extends HttpServlet
{
private static final long serialVersionUID = 1L;
private static String INSERT_OR_EDIT = "/user.jsp";
private static String LIST_USER = "/listUser.jsp";
private UserDao dao;
public ControllerTest()
{
super();
dao = new UserDao();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String forward = "";
String action = request.getParameter("action");
if (action.equalsIgnoreCase("delete"))
{
try
{
int userId = Integer.parseInt(request.getParameter("userId"));
dao.deleteUser(userId);
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
}
catch (NumberFormatException ex)
{
System.out.println("Error occured with during conversion delete");
}
}
else if (action.equalsIgnoreCase("edit"))
{
forward = INSERT_OR_EDIT;
try
{
int userId = Integer.parseInt(request.getParameter("userId"));
UseBean bean = dao.getUserById(userId);
request.setAttribute("user", bean);
} catch (NumberFormatException ex)
{
System.out.println("Error occured with during conversion edit");
}
}
else if (action.equalsIgnoreCase("listUser"))
{
forward = LIST_USER;
request.setAttribute("users", dao.getAllUsers());
} else
{
forward = INSERT_OR_EDIT;
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
try
{
UseBean bean = new UseBean();
bean.setName(request.getParameter("Name"));
bean.setPassword(request.getParameter("password"));
bean.setPhoneo(request.getParameter("Phoneo"));
bean.setEmailID(request.getParameter("Emailid"));
String userid = request.getParameter("ID");
if (userid == null || userid.isEmpty())
{
dao.addUser(bean);
} else
{
bean.setID(Integer.parseInt(userid));
dao.updateUser(bean);
}
RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
request.setAttribute("users", dao.getAllUsers());
view.forward(request, response);
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("erro occuring in update code");
}
}
}
You're getting a NumberFormatException when trying to convert the empty string "" into an Integer...
You get a NumberFormatException, if you do not pass a valid number to Integer.parseInt()
int userId = Integer.parseInt(request.getParameter("userid"));
Try to print the value of request.getParameter("userid") and check.
The page you are forwarding on might have some string to integer conversions that might be creating the error
Before parsing a string you should do null check and trim then parse. If NumberFormatException occurs handle it.
Whenever you get into trouble like this, put debug statements and analyse
what actually causing exception. null or empty or whitespace or string? Then you can handle it easily.
Integer userId= parseToNumber(request.getParameter("userId"));
//check for not null and proceed
// returns null if receivedParam = "", "some string", null or number with space
private Integer parseToNumber(String receivedParam)
{
System.out.println("received param:"+receivedParam);
if (receivedParam != null && !receivedParam.trim().isEmpty())
{
try
{
return Integer.parseInt(receivedParam.trim());
}
catch (NumberFormatException nfe)
{
System.out.println("received param is not a number");
return null;
}
}
else
{
System.out.println("received param is null or empty");
return null;
}
}
In file user.jsp and listuser.jsp. you used space for URL Rewriting.
you should use
<tr>
<td><%=user.getID()%></td>
<td><%=user.getName()%></td>
<td><%=user.getPassword()%></td>
<td><%=user.getEmailID()%></td>
<td><%=user.getPhoneo()%></td>
<td><a href="ControllerTest?action=edit&userId=<%=user.getID()%>" >Update</a></td>
<td>Delete</td>
</tr>
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>