[java] insert data into database using servlet and jsp in eclipse

I am trying to add or insert values into table of database using servlet and jsp and MySQL Workbench as database. These are the following details:

1.> Register.java

package register.com;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
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.*;
import javax.servlet.*;
* Servlet implementation class Register
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;

 * @see HttpServlet#HttpServlet()
public Register() {
    // TODO Auto-generated constructor stub

     * @see Servlet#init(ServletConfig)
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub

     * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse  response)
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method 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

            PrintWriter pw = response.getWriter(); 
            //String connectionURL = "jdbc:mysql://";// newData is the database  
            //Connection connection;  
            Connection conn=null;
            String url="jdbc:mysql://localhost:3306/";
            String dbName="userlogindb";
            String driver="com.mysql.jdbc.Driver";
        //String dbUserName="root";
        //String dbPassword="root";

          String Fname = request.getParameter("fname");  
          String Mname = request.getParameter("mname");  
          String Lname = request.getParameter("lname");  
          String Uname = request.getParameter("username");  
          String Emailid = request.getParameter("emailid");  
          String Mobno = request.getParameter("mobno");  
          String Address = request.getParameter("address");  
          String Password1 = request.getParameter("password1");  
          String Password2 = request.getParameter("password2");  

          conn = DriverManager.getConnection(url+dbName,"root", "root");
          PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into 'userlogindb'.'registerutable'(fname,mname,lname,username,emailid,mobno,address,password1,password2) values(?,?,?,?,?,?,?,?,?)");//try2 is the name of the table  


          int i = pst.executeUpdate();
          String msg=" ";
            msg="Record has been inserted";
            pw.println("<font size='6' color=blue>" + msg + "</font>");  

            msg="failed to insert the data";
            pw.println("<font size='6' color=blue>" + msg + "</font>");
        catch (Exception e){  



2.> index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"                    "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<form name="registrationform" action="register" method="post">
Enter your first name: <input type="text" name="fname"><br>
Enter your middle name: <input type="text" name="mname"><br>
Enter your last name: <input type="text" name="lname"><br>
Enter username: <input type="text" name="username"><br>
Enter email id: <input type="text" name="emailid"><br>
Enter mobile number: <input type="text" name="mobno"><br>
Enter address: <textarea rows="5" cols="5" name="address"></textarea><br>
Enter the password: <input type="password" name="password1"><br>
Reenter the password: <input type="password" name="password2"><br>
<input type="submit">

3.> web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<description>Register Servlet</description>

4.> I have added mysql-connector-java-5.0.8-bin.jar and servlet-api-3.0.jar is anything else needed to add it. I have created a connection to database in Data Source Explorer.

When I m compiling or debuging it shows no error. During runtime also there is no error. When I fill in the form and submit it shows only blank screen :( No output is displayed. :( Also in the database values are not updated.

Please help me. I m getting hangover with this snippet.

This question is related to java mysql xml jsp servlets

The answer is

In your JSP at line <form> tag, try this code

<form name="registrationform" action="Register" method="post">

Remove conn.commit from Register.java

In your jsp change action to :<form name="registrationform" action="Register" method="post">

String user = request.getParameter("uname");
String pass = request.getParameter("pass");
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";

Can you check value of i by putting logger or println(). and check with closing db conn at the end. Rest your code looks fine and it should work.

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 

int i=stm.executeUpdate(st2);

I had a similar issue and was able to resolve it by identifying which JDBC driver I intended to use. In my case, I was connecting to an Oracle database. I placed the following statement, prior to creating the connection variable.

DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to mysql

Implement specialization in ER diagram How to post query parameters with Axios? PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' phpMyAdmin - Error > Incorrect format parameter? Authentication plugin 'caching_sha2_password' is not supported How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Connection Java-MySql : Public Key Retrieval is not allowed How to grant all privileges to root user in MySQL 8.0 MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to servlets

Google Recaptcha v3 example demo Difference between request.getSession() and request.getSession(true) init-param and context-param java.lang.NoClassDefFoundError: org/json/JSONObject how to fix Cannot call sendRedirect() after the response has been committed? getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? Create a simple Login page using eclipse and mysql Spring get current ApplicationContext insert data into database using servlet and jsp in eclipse What is WEB-INF used for in a Java EE web application?