Not connecting to database through java - java

Actually I am trying to insert values from java servlet to postgres DB but they are not inserting.
Thanks in advance.
My html page is
<div class="container4">
<h2>Registration form</h2>
<form action="Register" method="get" >
<div class="form-group">
<label for="firstname">First Name:</label>
<input type="text" class="form-control" id="firstname" placeholder="Enter firstname" name="firstname">
</div><br><br>
<div class="form-group">
<label for="Username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div><br><br>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
</div><br><br>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd">
</div><br><br>
<div class="form-group">
<label for="address">Address:</label>
<input type="text" class="form-control" id="address" placeholder="Enter address" name="address">
</div><br><br>
<button type="submit" class="btn btn-default" id="submit">Submit</button>
</form>
</div>
My dbconnection page is
package dbConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
/**
*
* #author java2
*/
public class Dbconn {
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/classes","postgres", "admin123$");
System.out.println("db successfull");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("db not successfull");
}
return con;
}
}
Register.java
package register;
import dbConnection.Dbconn;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Register extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection con = null;
Statement st = null;
String n=request.getParameter("firstname");
String p=request.getParameter("username");
String e=request.getParameter("email");
String c=request.getParameter("pwd");
String d=request.getParameter("address");
try {
con = Dbconn.getConnection();
st = con.createStatement();
int i = st.executeUpdate(
"insert into register (firstname, username, email, pwd, address) values('"+n+"','"+p+"','"+e+"','"+c+"','"+d+"')");
con.commit();
System.out.println("hello successfull");
if (i == 0) {
response.sendRedirect("login.html?msg=success");
} else {
response.sendRedirect("register.html?msg=failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}}
When I run this program I am getting like
http://localhost:8088/trial/Register?firstname=jack&username=jack&email=jack%40gmail.com&pwd=jack&address=hyd
I am getting all the details in url and displays blank page without errors. I am not understanding where I went wrong.

Related

How to get an HTML data form to my web service?

I'm working on a project and I'm trying to get an HTML form data into my REST web service, so I can insert it into my database, I don't know where to get the HTML form data from.
This is my web service:
package hananepkg;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
/**
* REST Web Service
*
* #author mon pc
*/
#Path("generic")
public class GenericResource {
DBConnector db = new DBConnector();
#Context
private UriInfo context;
/**
* Creates a new instance of GenericResource
*/
public GenericResource() {
}
/**
* Retrieves representation of an instance of pkg.GenericResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.TEXT_HTML)
public String insert(#QueryParam ("name")String name,#QueryParam ("email")String email,#QueryParam ("password")String password,#QueryParam ("confirmpassword")String confirmpassword) {
//TODO return proper representation object
return "<html><body><h1>"+db.insertData(name,email,password,confirmpassord)+"</body></h1></html>";
}
/**
* PUT method for updating or creating an instance of GenericResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.TEXT_HTML)
public void putHtml(String content) {
}
}
This is my html page:
<section id="contact" class="contact3">
<div class="container" data-aos="fade-up">
<div class="section-title">
<h2>Sign In</h2>
</div>
<div class="col-lg-6 mt-5 mt-lg-0" data-aos="fade-left" data-aos-delay="100">
<form action="forms/contact.php" method="post" role="form" class="php-email-form">
<div class="form-row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Username" data-rule="minlen:4" data-msg="Please enter at least 4 chars" />
<div class="validate"></div>
</div>
<div class="col-md-6 form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" data-rule="email" data-msg="Please enter a valid email" />
<div class="validate"></div>
</div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="password" placeholder="Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="form-group">
<input type="password" class="form-control" name="subject" id="confirmpassword" placeholder="Confirm Password" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject" />
<div class="validate"></div>
</div>
<div class="text-center"><button id="submit" type="submit">Sign In</button></div>
</form>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/HananeTest/",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#name').val(),
"email": $('#email').val(),
"password": $('#password').val()
"password": $('#confirmpassword').val() });
};
</script>
Any suggestions how to get the input data into my web service so I can insert it to my database?
In your resource you have generic and in JS you have HananeTest as path. Make sure your are using the correct paths on both sides.
Your formToJSON function does not fill the parameter confirmpassword but has a duplicate entry for password. Make sure that all the parameters are set properly.
In JS you are currently using a JSON string and in your service you are referring to individual query parameters. To get JSON data to your method, you can annotate it with #Consumes({MediaType.APPLICATION_JSON}) and then use a simple POJO with the corresponding fields as attributes.
Example:
#Path("api/user")
public class YourResource {
#GET
#Consumes({MediaType.APPLICATION_JSON})
#Produces(MediaType.TEXT_HTML) // depending on what you want to return
public String insert(UserDTO user) {
// validation logic
// insert user into database
// return something
}
}
public class UserDTO {
private String username;
private String email;
private String password;
private String confirmpassword; // can possibly be removed if you check in JS whether the passwords match
// getters and setters
}

Connection between servlet and HTML form doesn't work

I encountered a problem in the connection between an HTML page and a servlet in Java. I already had this problem a few days ago but it was my mistakes in project management.
Now, it seems to me that I have done everything properly but I cannot deal with it.
In particular I'm creating an HTML page that contains a form with the action that call a servlet. My HTML page is on the "Web content" directory automatically created by Eclipse when I create a new Dynamic web project.
my WebServlet annotation is "#WebServlet(/UploadBook)" and the action on the form tag is "action=UploadBook".
When I click on the submit button the page this is the message that I receive:
Not Found
The requested URL /coltraneShop/Administrator/adminColtraneShop/WebContent/UploadBook was not found on this server.
I'm using Firefox on MacOS and apache webServer is started. I added, moreover, the Dynamic web project on server tomcat 9 from Eclipse and started it without problem.
This is my servlet Java code:
package insertion;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/UploadBook")
public class UploadBook extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out= response.getWriter();
Long productCode= (long) 0;
//Fetch data from HTML form method POST
String title= request.getParameter("Title");
String quantity= request.getParameter("Quantity");
String yearOfPublication= request.getParameter("yearOfPublication");
String genre= request.getParameter("Genre");
String numPages= request.getParameter("numPages");
String ISBN= request.getParameter("ISBN");
String publisher= request.getParameter("publisher");
String writerName1= request.getParameter("writerName1");
String writerSurname1= request.getParameter("writerSurname1");
String writerDateOfBirth1= request.getParameter("writerDateOfBirth1");
String writerGender1= request.getParameter("writerGender1");
Connection connection= null;
//Connect to DB
try {
connection= connectDB();
}
catch (ClassNotFoundException | SQLException ConnectionException) {
System.out.println("Error in connection!");
out.print("Connection to DB is not avaiable. " + ConnectionException.getMessage());
}
//Send query to DB
try {
//Preparing statement and query to DB
PreparedStatement statementProduct = connection.prepareStatement("INSERT INTO coltraneShop.Product (Category, `Title`, Quantity, `Year of publication`)"
+ "VALUES ('Book', ?, ?, ?);", Statement.RETURN_GENERATED_KEYS);
//Passing parameters
statementProduct.setString(1, title);
statementProduct.setInt(2, Integer.parseInt(quantity));
statementProduct.setInt(3, Integer.parseInt(yearOfPublication));
int affectedRows= statementProduct.executeUpdate();
if(affectedRows == 0)
throw new SQLException("Creating product failed, no rows affected.");
//Return ID of product insert in DB
ResultSet resultSet = statementProduct.getGeneratedKeys();
if(resultSet.next())
productCode= resultSet.getLong(1);
statementProduct.close();
out.print("<p>Added a product</p><br>");
PreparedStatement statementBook = connection.prepareStatement("INSERT INTO coltraneShop.Book VALUES (?, ?, ?, ?, ?);");
statementBook.setString(1, genre);
statementBook.setInt(2, Integer.parseInt(numPages));
statementBook.setLong(3, Long.parseLong(ISBN));
statementBook.setString(4, publisher);
statementBook.setLong(5, productCode);
int affectedRowsBook= statementBook.executeUpdate();
if(affectedRowsBook == 0)
throw new SQLException("Creating book failed, no rows affected.");
statementBook.close();
out.print("<p>Added a book</p><br>");
PreparedStatement statementWriter1 = connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementWriter1.setString(1, writerName1);
statementWriter1.setString(2, writerSurname1);
statementWriter1.setString(3, writerDateOfBirth1);
statementWriter1.setString(4, writerGender1);
int affectedRowswriter1= statementWriter1.executeUpdate();
if(affectedRowswriter1 == 0)
throw new SQLException("Creating writer failed, no rows affected.");
statementWriter1.close();
out.print("<p>Added a writer</p><br>");
int elementInRequest= request.getContentLength();
if(elementInRequest > 10) {
int numAdditionalWriter= (elementInRequest - 10) / 4;
for(int i=0; i<(numAdditionalWriter); i++) {
PreparedStatement statementAdditionalWriter= connection.prepareStatement("INSERT INTO coltraneShop. VALUES (?, ?, ?, ?);");
statementAdditionalWriter.setString(1, ("writerName" + (i+2)));
statementAdditionalWriter.setString(2, ("writerSurname" + (i+2)));
statementAdditionalWriter.setString(3, "writerDateOfBirth" + (i+2));
statementAdditionalWriter.setString(4, "writerGender" + (i+2));
int affectedRowsAdditionalWriter= statementAdditionalWriter.executeUpdate();
if(affectedRowsAdditionalWriter == 0)
throw new SQLException("Creating addtional writer failed, no rows affected.");
statementAdditionalWriter.close();
out.print("<p>Added a writer</p><br>");
}
}
}
catch (SQLException exceptionInQuery) {
System.out.println("Error in the query");
out.print("Error in statement or process of sending queries to the database. " + exceptionInQuery.getMessage());
}
try {
connection.close();
}
catch (SQLException closeConnectionException) {
System.out.println("Problem in closing connection");
out.print("Problem in closing connection. " + closeConnectionException.getMessage());
}
out.close();
}
private Connection connectDB() throws ClassNotFoundException, SQLException {
Connection connection= null;
Class.forName("com.mysql.cj.jdbc.Driver");
connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/coltraneShop?useTimezone=true&serverTimezone=UTC", "root", "");
return connection;
}
}
And This is my HTML form code:
<head>
<title>Insert book in the database</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<!--Bootstrap CSS-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="administrator.js"></script>
</head>
<body>
<form action="UploadBook" method="POST">
<div class="container">
<div class="form-group">
<label> <strong>Title:</strong> </label>
<input type="text" name="Title" class="form-control" placeholder="Title of book" maxlength="50" required>
</div>
<div class="form-group">
<label> <strong>Quantity:</strong> </label>
<input type="text" class="form-control" name="Quantity" placeholder="Max quantity in stock can be 999" maxlength="3" pattern="[0-9]{1,3}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Year of publication:</strong> </label>
<input type="text" class="form-control" name="yearOfPublication" placeholder="Year of publication" maxlength="4" pattern="[0-9]{1,4}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Genre:</strong> </label>
<select class="form-control" name= "Genre" required>
<option value="History" >History</option>
<option value="Fantasy">Fantasy</option>
<option value="Child">Child</option>
<option value="Art">Art</option>
<option value="Music">Music</option>
<option value="Thriller">Thriller</option>
<option value="Travel">Travel</option>
<option value="Biography">Biography</option>
<option value="Poetry">Poetry</option>
<option value="Romance">Romance</option>
<option value="Science">Science</option>
</select>
</div>
<div class="form-group">
<label> <strong>Number of pages:</strong> </label>
<input type="text" class="form-control" name="numPages" placeholder="Max length: 99.999 pages" maxlength="5" pattern="[0-9]{1,5}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>ISBN:</strong> </label>
<input type="text" class="form-control" name="ISBN" placeholder="13-digit code" maxlength="13" pattern="[0-9]{1,13}" onkeydown="return isNumberKey(event)" required></input>
</div>
<div class="form-group">
<label> <strong>Publisher:</strong> </label>
<input type="text" class="form-control" name="publisher" placeholder="The name of the publishing house" maxlength="30" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's name:</strong> </label>
<input type="text" class="form-control" name="writerName1" placeholder="The name of the Writer" maxlength="20" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's surname:</strong> </label>
<input type="text" class="form-control" name="writerSurname1" placeholder="The surname of the Writer" maxlength="20" pattern="[A-z]{1,20}" required></input>
</div>
<div class="form-group">
<label> <strong>Writer's date of birth:</strong> </label>
<input type="date" class="form-control" name="writerDateOfBirth1"></input>
</div>
<div class="form-group">
<label> <strong>Writer's gender:</strong> </label>
<input type="text" class="form-control" name="writerGender1" placeholder="Gender of writer: can be 'M' or 'F' or 'N(on defined)'" maxlength="1" pattern="^(M|F|N)" ></input>
</div>
<div class="form-group" id="containerWriters">
<button type="button" class="btn btn-outline-success" id="addWriterButton" onclick="addWriter()"> Add Writer </button>
<button type="button" class="btn btn-outline-danger" id="removeWriterButton" onclick="removeWriter()"> Remove Writer </button>
</div>
<!--Submit all data -->
<input type="submit" class="btn btn-primary btn-lg btn-block" value="Insert" id="submit"></input>
</div> <!--Container div-->
</form>
<!-- Bootstrap jQuery, Ajax and JavaScript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
Thank a lot for helping me.
It looks like you loaded file directly from file system and the tried to call this servlet. This is not correct. Load this HTML via your Tomcat, i.e. via URL like
http://localhost:8080/.../xxx.html.
If because of some reason you still want to use static HTML without Tomcat, then change servlet URL in your HTML to a full URL like following:
<form action="http://localhost:8080/.../UploadBook" method="POST">
If none of this is your case, then provide more info, how exactly are you loading HTML in you browser.

Using Jsoup to find an element with particular text

I want to select an element with specific text from the HTML using JSoup. The HTML is
<div class="logonContainer" style="padding-left: 300px; background-color: #3d5fa3; padding-top: 110px">
<div id="bglogodiv" style="background-image: url(15.0.847/themes/resources/ctslogo.jpg); border-radius: 25px; width: 800px">
<br />
<br />
<div id="lgnDiv" class="logonDiv" onkeypress="return checkSubmit(event)">
<div class="signInImageHeader" role="heading" aria-label="Outlook Web App ">
<img class="mouseHeader" src="/owa/auth/15.0.1263/themes/resources/owa_text_blue.png" alt="Outlook Web App " />
</div>
<div>
<div id="right" style="width: auto; float: right">
<div class="signInInputLabel" id="userNameLabel" aria-hidden="true">
User name:
</div>
<div>
<input id="username" name="username" class="signInInputText" role="textbox" aria-labelledby="userNameLabel" />
</div>
<div class="signInInputLabel" id="passwordLabel" aria-hidden="true">
Password:
</div>
<div>
<input id="password" onfocus="g_fFcs=0" name="password" value="" type="password" class="signInInputText" aria-labelledby="passwordLabel" />
</div>
<div>
<input id="passwordText" onfocus="g_fFcs=0" name="passwordText" value="" style="display: none;" class="signInInputText" aria-labelledby="passwordLabel" />
</div>
<div class="showPasswordCheck signInCheckBoxText">
<input type="checkbox" id="showPasswordCheck" class="chk" onclick="showPasswordClick()" />
<span>Show password</span>
</div>
</div>
I'm able to find the element using input id for username and password and pass my static credentials in to it using the below code. I want my code to find these elements dynamically during the runtime using some keywords and pass the static credentials. How would i do that. I may not know the element id, text or xpath during run time it can be anything. Kindly suggest how this can be done or help me with a working example.
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.w3c.dom.Document;
public class Dynamic_LoginPass {
public static final String Username = "admin";
public static final String Password = "admin";
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver","D:\\Eclipse\\workspace\\PopUp_Test\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nature.com/");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
String windowHandle = driver.getWindowHandle();
Assert.assertNotNull(windowHandle);
Thread.sleep(10000);
//driver.findElement(By.xpath("//*[#id=\"easycont\"]/div/div[2]/div[2]/div[2]/button")).click();
String html_content1 = driver.getPageSource();
// Jsoup makes DOM here by parsing HTML content
org.jsoup.nodes.Document doc1 = Jsoup.parse(html_content1);
System.out.println("Result:"+doc1);
int test= doc1.select("div:contains(signInInputLabel)").size();
System.out.println("testtesttesttest::"+test);
if(driver.findElement(By.cssSelector("input[id=username]")) != null){
driver.findElement(By.cssSelector("input[id=username]")).sendKeys(Username);
driver.findElement(By.cssSelector("input[id=password]")).sendKeys(Password);
driver.findElement(By.xpath("//*[#id=\"bglogodiv\"]/div[7]/div/span")).click();
System.out.println("#############clicked################");
} else if(driver.findElement(By.cssSelector("input[id=password]")) != null){
System.out.println("clicked in else if");
}
}
}
Thanks in advance
In my opinion the best way to use Jsoup FormElement class.
You can check how this should be done.
In this example
This practical approach use only jsoup. Therefore no need for WebDriver.

Insert query Database MySQL with registration form and servlet Java

I have problem accessing database with servlet java. I want to add users with an html registration form.
this is the html:
<form name="registration-form" action="RegisterUser" method="post">
<div class="form-group has-feedback">
<label class="control-label">Inserisci nome*</label>
<input type="text" class="form-control" name="name" id="inputName" placeholder="Nome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci cognome*</label>
<input type="text" class="form-control" name="surname" id="inputLastname" placeholder="Cognome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci email*</label>
<input type="email" class="form-control" name="email" id="inputEmail" placeholder="Email">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci password (compresa tra 6 e 30 caratteri)*</label>
<input type="password" class="form-control" name="password" id="inputFirstPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Reinserisci password*</label>
<input type="password" class="form-control" id="inputSecondPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<button id="submitBtn" class="btn btn-lg btn-primary btn-block" >Registrati!</button>
</form>
This is the java class (InsertUser.java):
import java.sql.*;
public class InsertUser {
public static void main(String name, String surname, String email, String password) {
PreparedStatement insert = null;
String queryString = "INSERT INTO Utente(Nome, "
+ "Cognome, Email, Password) VALUES (?, ?, ?, ?)";
Connection conn = null;
try {
new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/NoteDB";
String connectionUser = "root";
// String connectionPassword = "root";
conn = DriverManager.getConnection(connectionUrl, connectionUser, "");
conn.setAutoCommit(false);
insert = conn.prepareStatement(queryString);
insert.setString(1, name);
insert.setString(2, surname);
insert.setString(3, email);
insert.setString(4, password);
insert.executeUpdate();
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
This is the servlet (RegisterUser.java)
import java.io.IOException;
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 RegisterUser
*/
#WebServlet("/RegisterUser")
public class RegisterUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterUser() {
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
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String email = request.getParameter("email");
String password = request.getParameter("password");
//InsertUser myUser = new InsertUser();
InsertUser.main(name, surname, email, password);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
This is the error I get:
error page
I'm sorry that is a long question, but I am in despair :( Thanks everyone!
EDIT: in this picture you can see the mysql-connector.jar: mysqlconnector
Remove this line conn.setAutoCommit(false);
As Ramanlfc mentioned, you have to add mysql driver to your classpath.
You can do it natively via your ide, or use build managers, like maven, gradle or ant.
In maven, your pom.xml would look like:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.app</groupId>
<artifactId>mysql-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>

how get and pass values in servlet in java?

I have Java code like this,
package my.ebill.pro.db;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import newt.com.properties.*;
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 java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
#WebServlet("/BG_Form")
public class BG_Form extends MyDbConn {
/**
*
*/
private static final long serialVersionUID = -2319984741700546377L;
static Statement st,st1;
public BG_Form() throws Exception {
super();
st=con.createStatement();
st1=con.createStatement();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String poNumberBas=request.getParameter("poNo");
String fromPoBas=request.getParameter("toAddress");
String toPoBas=request.getParameter("toWhomname");
String[] productsBas = request.getParameterValues("product");
String[] pricesBas= request.getParameterValues("price");
String[] qtysBas= request.getParameterValues("qty");
String[] linetotalsBas = request.getParameterValues("linetotal");
System.out.println("Product"+productsBas);
/*out.println( poNumber + fromPo+toPo+products+prices+qtys+linetotals+"Adress");*/
PoGet poget=new PoGet();
poget.setFromPo(fromPoBas);
poget.setToPo(toPoBas);
poget.setProducts(productsBas);
poget.setPrices(pricesBas);
poget.setPoNumber(poNumberBas);
poget.setQtys(qtysBas);
poget.setLinetotals(linetotalsBas);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
here getter and setter;
public class PoGet {
private String poNumber;
private String fromPo;
private String toPo;
private String[] products;
private String[] prices;
private String[] qtys;
private String[] linetotals;
}
and jsp code is
<html>
<head>
<%#include file="includes/headscript.jsp" %>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</head>
<body>
<form id="validationform" name="validationform" method="get" action="BG_Form">
<input type="text" style="border-right-width: 2px; margin-right: 0px; margin-left: 33px; margin-top: -15px;" id="F_Date" class="dateRagePicker leftPick1 hasDatepicker" maxlength="20" size="20">
<table class="order-list" style="margin-left: 228px;">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product"></td>
<td><input type="text" name="price">
</td><td><input type="text" name="qty"></td>
<td><input type="text" readonly="readonly" name="linetotal"></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td style="text-align: center;" colspan="5">
<input type="button" value="Add Product" name="addrow" id="addrow">
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Rs<span id="grandtotal"></span>
</td>
</tr>
<tr>
<td>
In Words <span id="inworDs" ></span>
</tr>
<tr>
<td>
<input type="submit"/>
</tr>
</tfoot>
</table>
</form>
<script>
$("#addrow").click(function(){
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product"/></td>';
cols += '<td><input type="text" name="price"/></td>';
cols += '<td><input type="text" name="qty"/></td>';
cols += '<td><input type="text" name="linetotal" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="qty"]').val();
row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal(f) {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
</body>
</html>
from jsp i am getting the multiple values String array,
can any one tell me how can i retrive and set the values which i am sending from javascript.
i need to get values has to pass it to database.
String[] productsBas = request.getParameterValues("product");
String[] pricesBas= request.getParameterValues("price");
String[] qtysBas= request.getParameterValues("qty");
for(int i=0;i<productsBas.length;i++){
get values here using
productsBas[i] & pricesBas[i] and qtysBas[i] then save it
}

Categories

Resources