request.getParameter returns null in JSP - java

Form.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Form</title>
<body bgcolor="#FFFFFF" text="#000000">
<h1>Please enter your details</h1>
<form name="RegistrationForm" action="NewUser" method="post">
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First Name:</td>
<td><input type="text" name="NewFirstName"></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td><input type="text" name="NewLastName"></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><input type="text" name="EmailAddress"></td>
</tr>
<tr>
<td align="right">Phone Number:</td>
<td><input type="text" name="Phone Number"></td>
</tr>
<tr>
<td align="right">Semester</td>
<td><input type="text" name="Semester"></td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</body>
</html>
NewUser.java(Servlet Class)
package com.seria.quiz;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class NewUser
*/
#WebServlet("/NewUser")
public class NewUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public NewUser() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn = null;
try {
String FirstName = request.getParameter("firstName");
System.out.println("Your firstname: " + FirstName);
String LastName = request.getParameter("lastName");
System.out.println("Your LastName: " + LastName);
String Emailid = request.getParameter("email");
String PhoneNumber = request.getParameter("phoneNumber");
String Semester = request.getParameter("semester");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/seriaquiz", "root", "root");
PreparedStatement pst = (PreparedStatement) conn
.prepareStatement("insert into formdetails(firstName,lastName,email,phoneNumber,semester) values(?,?,?,?,?)");// try2
// the
// name
pst.setString(1, FirstName);
System.out.println("Your firstname1: " + FirstName);
pst.setString(2, LastName);
System.out.println("Your LastName1: " + LastName);
pst.setString(3, Emailid);
pst.setString(4, PhoneNumber);
pst.setString(5, Semester);
int i = pst.executeUpdate();
String msg = " ";
if (i != 0) {
msg = "Record has been inserted";
pw.println("<font size='6' color=blue>" + msg + "</font>");
} else {
msg = "failed to insert the data";
pw.println("<font size='6' color=blue>" + msg + "</font>");
}
pst.close();
} catch (Exception e) {
pw.println(e);
}
}
}
As the title says request.getParameter is returning null every time. I put sysout statements after requestParameter, and it shows null value. Any help will be appreciated. Sorry for any inconvenience, I'm new here.

The parameter names in servlet need to match them in the JSP
so
String FirstName = request.getParameter("firstName");
should be
String FirstName = request.getParameter("NewFirstName");

you are asking for wrong parameters
you should always ask for same id/name as described in your html
request.getParameter("NewFirstName");

From w3.org section 17.2 Controls
Users interact with forms through named controls.
A control's "control name" is given by its name attribute. The scope of the name attribute for a
control within a FORM element is the FORM element.
When a form is submitted for processing, some controls have their name paired with their current
value and these pairs are submitted with the form.
Example of control is your
<input type="text" name="NewFirstName">
So when the form gets submitted, it contains a control name=value e.g.
NewFirstName=YourFirstName
In your JSP, you should do access it using the the control name
String FirstName = request.getParameter("NewFirstName");
Reference: http://www.w3.org/TR/html401/interact/forms.html

Get the exact value of a form parameter try this....
String FirstName = request.getParameter("NewFirstName");
because ..
you specify name attribute by 'NewFirstName'...

Related

Java DB Inserting Data Into Table

I am having trouble trying to insert data into a table in my database in netbeans, below is my code:
public class NewUser extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
String [] query = new String[5];
query[0] = (String)request.getParameter("username");
query[1] = (String)request.getParameter("password");
query[2] = (String)request.getParameter("confPassword");
query[3] = (String)request.getParameter("name");
query[4] = (String)request.getParameter("address");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else {
jdbc.insert(query);
request.setAttribute("message", query[0]+" has been registered successfully!");
}
This is in a class "NewUser.java". The insert method is in a class "jdbc" and is as follows:
public void insert(String[] str){
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
ps.setString(1, str[0].trim());
ps.setString(2, str[1]);
ps.setString(3, str[3]);
ps.setString(4, str[4]);
ps.executeUpdate();
ps.close();
System.out.println("1 row added.");
} catch (SQLException ex) {
Logger.getLogger(Jdbc.class.getName()).log(Level.SEVERE, null, ex);
}
}
The "CUSTOMER" table looks as follows:
# | Username | Password | Name | Address | ID
('ID' is the primary key which is auto incremented)
The JSP where the user inputs the information is as follows:
<%#page import="model.Jdbc"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User</title>
</head>
<body>
<h2>User's details:</h2>
<%! int i = 0;
String str = "Register";
String url = "NewUser.do";
%>
<%
if ((String) request.getAttribute("msg") == "del") {
str = "Delete";
url = "Delete.do";
}
else
{
str = "Register";
url = "NewUser.do";
}
%>
<form method="POST" action="<%=url%>">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td><input type="password" name="confPassword"/></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td> <input type="submit" value="<%=str%>"/></td>
</tr>
</table>
</form>
<%
if (i++ > 0 && request.getAttribute("message") != null) {
out.println(request.getAttribute("message"));
i--;
}
%>
</br>
<jsp:include page="foot.jsp"/>
</body>
</html>
The SQL statement used to create the database:
CREATE TABLE Customer (
username varchar(20),
password varchar(20),
name varchar(20),
address varchar(60),
id INT primary key GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1)
);
The code doesn't throw any errors however, when I check the database to see if the data has been added it never gets added and I cannot figure out why (I think it's something to do with the "insert" method?). I have looked around for solutions however, I still get the same outcome and could really use some help.
Cheers,
For Oracle you need to specify column for auto generated columns:
ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)", new String[]{"ID"})
For ID column
You forgot to replace prepareStatement.return.. to Statement.return..ps = connection.prepareStatement("INSERT INTO CUSTOMER VALUES (?,?,?,?)",Statement.RETURN_GENERATED_KEYS,new String[]{"ID"});

The request content-type is not a multipart/form-data in Servlet

HTML form
<html>
<!--// This the client html page that receive data and uploads it.>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<body>
<center>
<h1>Task It User profile page</h1><br></br>
<form action="Upload" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Servlet
package net.codejava.upload;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/Upload")
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUpload extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/appdb";
private String dbUser = "root";
private String dbPass = "asdf";
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
// ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
}
The second code is the servlet code that i am trying to use to store data from client into the appdb
javax.servlet.ServletException: The request content-type is not a multipart/form-data is the error that i am getting.
I am very new this so if there is a trivial mistake, still answer the question

Getting null value when passing the variable from jsp to servlet

I am trying to get a value from jsp to sevlet.First the variable value is taken by session setArribute(), getAttribute() then I need to pass that particular variable from jsp to servlet but I am getting null value for that variable.
Here below I am sharing my code, can anyone findout how can I solve this issue?
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<form>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="delete"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="print"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="send mail"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
</tr>
</table>
</form>
</table>
<%
}
%>
</body>
</html>
from the above code I have set the session variable as surveyid
and I can get it from the below code.It is working properly
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit survey</title>
</head>
<body>
<%
ResultSet resultSet;
String surveyId = (String) session.getAttribute("surveyid");
out.println("check"+surveyId);
request.setAttribute("surveyid", surveyId);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ surveyId ;
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(query);
while(rset.next()){
%>
<form name="Editsurveyform" method="post" action="EditSurvey">
<table>
<tr><td>Family name:</td><td><input type="text" name="familyName" value='<%=rset.getString(2)%>'></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstName" value='<%=rset.getString(3)%>'></td></tr>
<tr><td>Middle name:</td><td><input type="text" name="middleName" value='<%=rset.getString(4)%>'></td></tr>
<tr><td>Gender:</td>
<td>
<%
if(rset.getString(5).equals("male")){
%>
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<%}
else{
%>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female" checked>Female
<%
}
%>
</td>
</tr>
<tr><td>Birthday:</td><td><input type="date" name="dob" value='<%=rset.getString(6)%>'></td></tr>
<tr><td>Income : A?B?C?D?</td><td><input type="text" name="income" value='<%=rset.getString(7)%>'></td></tr>
<tr><td>Complete Address:</td><td><input type="text" name="address" value='<%=rset.getString(8)%>'></td></tr>
<tr><td>Coordinates:</td><td><input type="text" name="coordinates" value='<%=rset.getString(9)%>'></td></tr>
<tr><td>Mobile number:</td><td><input type="tel" name="mobileno" value='<%=rset.getString(10)%>'></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email" value='<%=rset.getString(11)%>'></td></tr>
<tr><td>Present internet provider:</td><td><input type="text" name="iprovider" value='<%=rset.getString(12)%>'></td></tr>
<tr><td>Positive comments with present provider:</td><td><textarea name="comments" cols="40" rows="5"><%=rset.getString(13)%></textarea></td></tr>
<tr><td>Negative remarks with present provider:</td><td><textarea name="remarks" cols="40" rows="5"><%=rset.getString(14)%></textarea></td></tr>
<tr><td><input type="submit" name="editsurvey" value="update survey details"></td><td><input type="reset" name="cancel" value="cancel"></td></tr>
</table>
</form>
<%}
//response.sendRedirect("EditSurvey?surveyId="+surveyId);
%>
</body>
</html>
But I encounter the problem in below java
package com.survey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* Created by rajee on 2/18/15.
*/
public class EditSurvey extends HttpServlet {
public String familyName;
public String firstName;
public String middlename;
public String gender;
public String dateOfBirth;
public String income;
public String completeAddress;
public String coordinates;
public String mobileno;
public String emailAddress;
public String presentIP;
public String comment;
public String remark;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String surveyId = (String) request.getAttribute("surveyid");
System.out.println(surveyId);
familyName = request.getParameter("familyName");
firstName = request.getParameter("firstName");
middlename = request.getParameter("middleName");
gender = request.getParameter("sex");
dateOfBirth = request.getParameter("dob");
income = request.getParameter("income");
completeAddress = request.getParameter("address");
coordinates = request.getParameter("coordinates");
mobileno = request.getParameter("mobileno");
emailAddress = request.getParameter("email");
presentIP = request.getParameter("iprovider");
comment = request.getParameter("comments");
remark = request.getParameter("remarks");
System.out.println(familyName);
System.out.println(firstName);
System.out.println(middlename);
System.out.println(gender);
System.out.println(dateOfBirth);
System.out.println(income);
System.out.println(completeAddress);
System.out.println(coordinates);
System.out.println(mobileno);
System.out.println(emailAddress);
System.out.println(presentIP);
System.out.println(comment);
System.out.println(remark);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="surveysample";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
// try{
//
//
// Class.forName(driver).newInstance();
// conn = DriverManager.getConnection(url + dbName, "root", "root");
// PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into surveysample.surveydetail(familyname,firstname,middlename,gender,dateofbirth,income,complete_address,coordinates,mobilenumber,emailaddress,presentiprovider,comments,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
//
// pst.setString(1,familyName);
// pst.setString(2,firstName);
// pst.setString(3,middlename);
// pst.setString(4,gender);
// pst.setString(5,dateOfBirth);
// pst.setString(6,income);
// pst.setString(7,completeAddress);
// pst.setString(8,coordinates);
// pst.setString(9,mobileno);
// pst.setString(10,emailAddress);
// pst.setString(11,presentIP);
// pst.setString(12,comment);
// pst.setString(13,remark);
//
//
// int i = pst.executeUpdate();
// //conn.commit();
// String msg=" ";
// if(i!=0){
// msg="Record has been inserted";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
//
//
// }
// else{
// msg="failed to insert the data";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
// }
// pst.close();
// }
// catch (Exception e){
// pw.println(e);
// }
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
code
If your problem is for surveyId being null is servlet, it is normal because you try to get it from request :
String surveyId = (String) request.getAttribute("surveyid");
As you put it in session, you should read it from there :
String surveyId = (String) request.getSession().getAttribute("surveyid");
You can try below code in your servlet as :
HttpSession session = request.getSession(false);
String surveyId = (String) session.getAttribute("surveyid");
this method request.getSession(false) will not create new session if session object is already exists. it will simply return old session object if its there otherwise it will return null.

How to fetch an id from the database after record inserted in db [duplicate]

This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 8 years ago.
How to fetch id from db using JSP servlet. This is my JSP servlet code and I need code for display id through alert message box and in my db I will gave id as auto-increment in data base. I am trying this for last two days .
How to fetch a id from the database after record inserted in db?
Kindly help me out for displaying an id like "registration is suss-your id is ........."
package controller;
import java.io.IOException;
import java.io.PrintWriter;
javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
#WebServlet("/Register")
public class Register extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2945154063362413961L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
/*String fname=request.getParameter("firstname");
String lname=request.getParameter("lastname");*/
//pw.println("Firstname is" +fname);
//pw.println("Firstname is" +lname);
/*System.out.println("first=="+fname);
System.out.println("last==="+lname);
*/
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="Registrationform";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
try{
String Fname = request.getParameter("firstname");
String Lname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String email= request.getParameter("email");
Class.forName(driver).newInstance();
System.out.println("welcome");
conn = DriverManager.getConnection(url+dbName,dbUserName, dbPassword);
System.out.println("Connection created");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into event (firstname,lastname,dob,email) values(?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Lname);
pst.setString(3,dob);
pst.setString(4,email);
int i = pst.executeUpdate();
System.out.println("Query updated");
PreparedStatement pstr =(PreparedStatement) conn.prepareStatement("select * from event(id);");//try2 is the name of the table
//conn.commit();
String msg=" ";
if(i!=0){
msg="You Are Succesfully Register For The Event Meet";
//alert("You Are Succesfully Register For The E;vent Meet")
// response.sendRedirect("reg.jsp");
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
else{
msg="Failed to insert the data";
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
java script code
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="reg.css">
<title>Event Registration From</title>
</head>
<body class= "main">
<script type="text/javascript">
function register(registerform)
{
if(registerform.firstname.value == "") {
alert("Please enter your Firstname");
registerform.firstname.focus();
return false;
}
if(registerform.lastname.value == "") {
alert("Please enter your Lastname");
registerform.lastname.focus();
return false;
}
if(registerform.dob.value == "") {
alert("Please select your DOB");
registerform.dob.focus();
return false;
}
if(registerform.email.value == "") {
alert("Please enter your Email-id");
registerform.email.focus();
return false;
}
/* var x=document.forms["form"]["email_id"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
} */
return true;
}
</script>
<form name="registerform" action ="Register" method = "post">
<div>
<h3> Event Registration Form </h3>
<div>
<label for ="first" class ="label" > First Name </label>
<input type="text" id="first" name="firstname" class="text" />
</div>
<div>
<label for ="last" class ="label">Last Name</label>
<input type="text" id="last" name="lastname" class="text">
</div>
<div>
<label for ="dob" class ="label">Date Of Birth </label>
<input type="text" id="dob" name="dob" class="text">
</div>
<div>
<label for ="email" class ="label">Email_Id</label>
<input type="text" id="email" name="email" class="text">
</div>
<div><input type="submit" value ="submit" class="button" onclick="register(registerform)"></div>
</div></form>
</body>
</html>
You can try something like this with MySQL:
PreparedStatement ps = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
// Get generated key.
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
int key = rs.getInt(1);
}
Where ps is the PreparedStatement and you retrieve the key from the ResultSet object.
To get the last generated auto-increment id you can use the MySql function LAST_INSERT_ID().
Another option would be to use the MAX aggregation function to return the maximum value for the id field. Since the last inserted id is always the max MAX(id).
Because this is a standard way, this has been added to a constant, so doing:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, Statement.RETURN_GENERATED_KEYS);
For some JDBC drivers like Oracle you have to specify the columns explicitly:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, new String[]{"USER_ID"});

I want to automatically increase table row after clicking button

Hi, my problem is increasing the table row automatically. Actually, when I click GET button the product type and product name values are getting from database. Here, after getting those values, I will give another id based on that id again for values will come. But it was not setting in another row. Here is my java code and jsp:
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
Statement st =con.createStatement();
String query="select * from product where ProductType_v='"+a+"' and ProductId_v='"+b+"'";
ResultSet rs = (ResultSet)st.executeQuery(query);
int i=0;
while(rs.next())
{
i++;
request.getSession().setAttribute("edit","success");
request.getSession().setAttribute("proType ", rs.getString("ProductType_v"));
request.getSession().setAttribute("proId", rs.getString("ProductId_v"));
request.getSession().setAttribute("strength", rs.getString("Strength_v"));
request.getSession().setAttribute("proName", rs.getString("ProductName_v"));
request.getSession().setAttribute("brand", rs.getString("BrandName_v"));
request.getSession().setAttribute("generic", rs.getString("GenricName_v"));
request.getSession().setAttribute("uom", rs.getString("UOM_v"));
request.getSession().setAttribute("formE", rs.getString("FormE_v"));
request.getSession().setAttribute("presReqd", rs.getString("PresReqd_v"));
}
if(i==0)
{
request.getSession().setAttribute("edit", "fail");
}
}
catch(Exception e)
jsp code
<tr>
<td>
<input class="textfield-form-date-req" type="text" id="pro_type">
</td>
<%
if(editStatus =="success")
{
%>
<script type="text/javascript">
document.getElementById("pro_type").value='<%=session.getAttribute("proType")%>';
</script>
<%
}
<td>
<input class="textfield-form-date-req" type="text" id="pro_id">
</td>
<%
if(editStatus =="success")
{
%>
<scripttype="text/javascript">
document.getElementById("pro_id").value='<%=session.getAttribute("proName")%>';
</script>
<%
}
%>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
I have created a sample for you with ajax. It gets the data from the server side and append it , in the existing table.
The jar files I have used is ,
jackson-all-1.9.0.jar - to convert the java object to json format
servlet-api-2.4.jar - for servlet
My TableAppend.jsp will be,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
//alert("DOM is ready");
});
function sendData() {
$.ajax({
type : 'POST',
url : "TableAppend",
data : "name=" + $('#name').val() + "&age=" + $('#age').val()
+ "&sid=" + new Date(),
dataType : 'html',
success : function(result) {
//alert("Result ::::>>> "+result);
if(result != null && $.trim(result) != "" && result != undefined){
var json = JSON.parse(result);
//alert(json.name);
//alert(json.age);
appendToTable(json.name, json.age);
}
},
error : function(e) {
alert('Error in Processing');
}
});
}
function appendToTable(name, age) {
var tr = "<tr><td>" + name + "</td><td>" + age + "</td></tr>"
$('#mytable').append(tr);
}
</script>
</head>
<body>
Name :
<input type="text" id="name" name="name" /> Age :
<input type="text" id="age" name="age" />
<input type="button" value="Append to table" onclick="sendData()">
<br></br>
<br></br>
<br></br>
<table id="mytable" border="1">
<tbody>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>HumanBeing</td>
<td>25</td>
</tr>
<tr>
<td>Saideep</td>
<td>26</td>
</tr>
</tbody>
</table>
</body>
</html>
My TableAppend.java servlet will be,
public class TableAppend extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public TableAppend() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setCharacterEncoding("UTF-8");
response.setContentType("UTF");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
String age = request.getParameter("age");
String json ="";
System.out.println("-----------------");
if(name != null && age != null){
TableAppendPojo obj = new TableAppendPojo();
obj.setName(name);
obj.setAge(age);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(obj);
System.out.println("json : "+json);
}
out.println(json);
}
}
Then java class will be,
public class TableAppendPojo {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
Note : Please apply the above logic in your code . In your case , you don't need to give the data from the UI. You retrieves the data from the database in the servlet.So please convert the retrieved data from the database to the json format and append it to the table.
Hope this helps.

Categories

Resources