Browser showing nothing while calling servlet - java

I am trying this for a while but every time when i try to run on browser it shows nothing, not even an error.
"index.html" file
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
"web.xml" file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
"Register.java" file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
This image is after i entered the details, and there is no data stored in my database
This is the error showing in cmd
I am using JDK 9 which have no "ext" file in the JRE so i included JDBC driver file through command line.
I have created database 'db' in mysql and table name 'student'.
I don't know where is the problem. Please help me!!

You do not close Connection and PreparedStatement.
Best use try-with-resources for that. There was a space in the connection URL.
The other problem was already mentioned.
try (Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student (name,email,pass) values(?,?,?)")) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
ps.executeUpdate();
} catch(Exception se) {
se.printStackTrace();
}

Your form method is post:
<form method="post" action="register">
And in your servlet you only have a doGet.
Change your form method to get:
<form method="get" action="register">
Servlet doGet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student (name,email,pass) values(?,?,?);");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
ps.executeUpdate();
}catch(Exception se){
se.printStackTrace();
}
//redirect user back to index
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request,response);
}
}

Related

Tomcat/Java - Insert into a mysql database

package mycode;
import java.sql.*
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;
public class Login extends HttpServlet {
private static final long serialVersionUID = -4546189621945422719L;
String URL = "jdbc:mysql://127.0.0.1";
String USER = "root";
String PASS = "1234";
#Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException{
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Connection con = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO cloud.cloud_table (Username,Password)" +
"VALUES (?, ?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
pst.executeUpdate();
out.println("<html><body>");
out.println("THANKS FOR CREATING AN ACCOUNT");
out.println("</body></html>");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
<?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">
<display-name>Login</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>mycode.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
+----------+----------+
| Username | Password |
+----------+----------+
| | |
+----------+----------+
<form action="login" method="GET">
<div>
<h4>Please enter your password and username</h4>
</div>
<div>
Username <input name="username" type="text" />
</div>
<div>
Password <input name="password" type="text" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Using java and tomcat, I have a simple form that takes in a username and password. I want to be able to retrieve the username and password from the form and insert it into a mysql database. However, right now after clicking the submit button on the form, nothing happens and the database is not updated. The database connection is working fine so I am not sure what the problem is right now. Any help would be appreciated.
You are calling your GET method from the HTML form.
Change your action to POST.
<form action="login" method="POST">

HTTP Status 405 - HTTP method GET is not supported by this URL.The specified HTTP method is not allowed for the requested resource

Help me here guys...I have added servlet jar file and mysql connector jar file but it's showing the error like HTTP Status 405 - HTTP method GET is not supported by this URL.The specified HTTP method is not allowed for the requested resource.I have attempted every possible solution but i am getting the same error.
Regform.java
package com.servlet.info;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.Driver;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Regform extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String fNM = request.getParameter("firstName");
String lNM = request.getParameter("lastName");
String eID = request.getParameter("emailID");
String uNM = request.getParameter("userName");
String pass = request.getParameter("password");
try{
//loading drivers for mysql
com.mysql.jdbc.Driver mySqlDriverClassRef = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(mySqlDriverClassRef);
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_form?&useSSL=false", "j2ee" ,"j2ee");
PreparedStatement ps=con.prepareStatement
("insert into student values(?,?,?,?,?);");
ps.setString(1, fNM);
ps.setString(2, lNM);
ps.setString(3, eID);
ps.setString(4, uNM);
ps.setString(5, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
index.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form action="/register" method="POST" >
firstName:<input type="text" name="firstName" /><br/>
lastName:<input type="text" name="lastName" /><br/>
emailID :<input type="text" name="email" /><br/>
userName:<input type="text" name="userName" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Regform</servlet-name>
<servlet-class>com.servlet.info.Regform</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Regform</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
Try adding below to your Java and see if it works
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException,
ServletException {
doPost(request, response);
}
I recommend that you always write the codes you defined in the doPost and doGet methods in the doProcess method.

Basics of this web application development [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am creating a payroll system. I have a database which contains employee_id and password. My index.html is the login page, where you enter an employee_id and password and the database checks to see if the details are correct and if it is, then the Welcome.java servlet takes you to a page which prints "Welcome user".
What I want is, when an employee logs in, it takes them to a page with the following buttons instead of a screen which simply says "Welcome user":
View personal information, View payslip information, change password
I do not know how to do this.
Below are my files.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login" method="post">
<h3>
Employee Login
</h3>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
if(Validate.checkUser(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Validate.java (class file)
import java.sql.*;
public class Validate
{
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?");
ps.setString(1, employee_id);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Welcome user");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You have to change one line of code of login servlet RequestDispatcher rs = request.getRequestDispatcher("Welcome"); as RequestDispatcher rs = request.getRequestDispatcher("Options");
and create a html file of creating 3 buttons.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Options</title>
</head>
<body>
<form action="Mainservlet" method="post">
<h3>
Options
</h3>
<input type="submit" value="Personalinformation" name="pi">
<br>
<br>
<input type="submit" value="PayslipInformation" name="psi">
<br>
<br>
<input type="submit" value="ChangePassword" name="cp">
<br>
<br>
</form>
</body>
</html>
In mainservlet
if(request.getParameter("pi") != null) {
// Invoke PersonalInformation's job here.
} else if (request.getParameter("psi") != null) {
// Invoke PayslipInformation's job here.
}else if (request.getParameter("cp") != null) {
// Invoke ChangePassword's job here.
}
Create an html or jsp page with your buttons and other content, then redirect from login servlet to your page instead of welcome servlet through request dispatcher or just by response.sendRedirect() method.

Why Servlet is not outputting this html?

I am learning to connect my servlet to database. I have two columns in my db (Username,Password). I want to create a program that access the database compares the User/Pass (send via the user form html ) with the values in db columns. When i try to login , nothing shows up on screen .
Files:
LoginServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.sql.*;
public class LoginServlet extends HttpServlet{
public void init(){}
Connection con;
Statement st;
ResultSet rs;
public void service(HttpServletRequest req, HttpServletResponse res){
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><body>");
out.println("<p>Servlet is loading</p>");
String TheUser=req.getParameter("username");
String ThePass=req.getParameter("password");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","pass");
st=con.createStatement();
rs=st.executeQuery("select Username,Password from AllUsers");
String compareUser=rs.getString(1);
String comparePass=rs.getString(2);
if(TheUser.equals(compareUser)||ThePass.equals(comparePass)){
out.println("<p>You are logged in as " + compareUser+" </p>");
}
else
out.println("Wrong Combination");
}
}catch(Exception e){}
}catch(ClassNotFoundException|IOException|ServletException f){
f.printStackTrace();
}
out.println("</html></body>");
out.close();
}
public void destroy(){}
}
This File Compiles and deployed.
web.xml:
<web-app>
<servlet>
<servlet-name>SignUpServlet</servlet-name>
<servlet-class>SignUpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignUpServlet</servlet-name>
<url-pattern>/SignUp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
log.html:
<html>
<body>
<form name='loginForm' method='post' action='login'>
Enter Username:
<input type='text' name='username'>
</br>
Enter Password:
<input type='password' name='password'>
</br>
<input type="submit" value="Submit">
</form>
</body>
</html>
P.S: Servlet is loading. The <p>Servlet is loading </p> tag shows up on browser.
Ok so i did it. After many hours of hit n try. I figured out that the db cursor was never on the first records of the table , that's why it didnt show up.
I wrapped the code in a while statement:
rs=st.executeQuery("select Username,Password from AllUsers");
while(rs.next()){
String compareUser=rs.getString(1);
String comparePass=rs.getString(2);
if(TheUser.equals(compareUser)||ThePass.equals(comparePass)){
out.println("<p>You are logged in as " +compareUser+"</p>");
rs.close();
st.close();
con.close();
}
else{
out.println("<p>Wrong Combination</p>");
out.println("</br><a href='log.html'>Login</a></p>");
rs.close();
st.close();
con.close();
}
}
}catch(Exception e){
e.printStackTrace();
}
I hope if anyone else runs into this problem, this could help.

Calling servlet from HTML form, but no response from servlet [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling servlet from HTML form, but servlet is never invoked
I'm calling servlet from html form, servlet takes the form data and it will insert that form data into database.But when i click the submit button error page is coming. Please help whats wrong in my servlet code.
My html code:
<html>
<head>
<title> Sign Up </title>
</head>
<body>
<form action="servlet/Loginservlet" method="post" >
<font size='5'>Create your Account:</font><br/><br>
<label for="username" accesskey="u" style="padding-left:3px;">User Name: </label>
<input type="text" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;margin-top:6px;padding-right:85px;" id="username" name="username" tabindex="1"><br/><br>
<label for="password" accesskey="p" style="padding-left:4px;">Password: </label>
<input type="password" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;padding-right:85px;" id="password" name="pasword" tabindex="2"><br/><br>
<input type="submit" value="Submit" style="margin-left:164px;"/>
<input type="reset" value="Reset" style="margin-left:17px;"/>
</form>
</body>
</html>
My servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Loginservlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("login servlet");
String connectionURL = "jdbc:mysql://localhost:3306/mysql";
Connection connection = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = req.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "root");
String sql = "insert into signup values (?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
int numRowsChanged = pst.executeUpdate();
out.println(" Data has been submitted ");
pst.close();
} catch (ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
} catch (SQLException e) {
out.println("SQLException caught: " + e.getMessage());
} catch (Exception e) {
out.println(e);
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ignored) {
out.println(ignored);
}
}
}
}
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
I think, mistake is here: <form action="servlet/Loginservlet"
Try this <form action="/<your-app-name>/login"
since in form action you have given servlet/Loginservlet . you should map same in web.xml like
<url-pattern>/servlet/Loginservlet</url-pattern>
or change in the form like
action='login'
you can do any one of above.
try this
<form action="login" method="post" >
you servlet url is
<url-pattern>/login</url-pattern>
When you run your web application for local host then the url like
localhost:8080/test
then the test is the name of your application name which contain your web application into the web dir. Now suppose you create the index file then it will run index file from this only and another page url like
localhost:8080/test/page1.html
now from page1.html you start your login page then the link looks like for servlet is
localhost:8080/test/login
as define the url pattern for specific servlet that url you have to set for calling the specific servlet like above. this url will hide the actual servlet for the client you can set anything in url pattern

Categories