JSP not showing results [duplicate] - java

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm having issues with my Java servlet and application. I'm pulling my hair out trying to understand how to make these servlets work correctly and output in the browser. I have attached my code below, please point me in the direction to get this program to work correctly. I understand sample code vs being told what to do. I'm not looking for you to do my work, just need help visually. All help is greatly appreciated.
Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class FormPost3 extends HttpServlet{
private static final long serialVersionUID = 1L;
Connection con = null;
public void Form3(){
init();
}
public void init(){
try{
Class.forName ("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:7070:XE", "student2", "pass");
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE MYTABLE (FNAME VARCHAR2(20),LNAME VARCHAR2(40), PHONE VARCHAR2(20))");
stmt.close();
}
catch (Exception e){
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<form action='" + request.getRequestURL() + "' method='post' >");
out.println("First Name:");
out.println("<input type='text' name='FNAME' />");
out.println("<br>");
out.println("Last Name:");
out.println("<input type='text' name='LNAME' />");
out.println("<br>");
out.println("Phone:");
out.println("<input type='text' name='PHONE' />");
out.println("<input type='submit' value='Submit' />");
out.println("</form>");
out.println("</body></html>");
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
try{
if (con != null)
init();
String fname = request.getParameter("FNAME");
String lname = request.getParameter("LNAME");
String phone = request.getParameter("PHONE");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO MYTABLE VALUES('" + fname + "', '" + lname + "', '" + phone + "')");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
ResultSet rset = stmt.executeQuery("SELECT * FROM MYTABLE");
while (rset.next()){
out.print("<pre>");
out.print("First Name: " + rset.getString(1));
out.print("</pre>");
out.println();
out.print("<pre>");
out.print("Last Name: " + rset.getString(2));
out.print("</pre>");
out.println();
out.print("<pre>");
out.print("Phone: " + rset.getString(3));
out.print("</pre><br>");
out.println();
out.println();
}
out.println("</body></html>");
out.close();
stmt.close();
}
catch (Exception e){
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println(e.getMessage());
out.println("</body></html>");
out.close();
}
}
}
Web.xml
<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">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>FormPost3</servlet-name>
<servlet-class>FormPost3</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FormPost3</servlet-name>
<url-pattern>/FormPost3</url-pattern>
</servlet-mapping>
</web-app>
index.html
<html>
<head>
</head>
<body>
<h3 align="center">Storing Employee Details</h3>
<form action="/WFormPost3" method="post">
<div align="center">
Empno: <input type="text" size="20" name="empno"/>
<br><br>
Ename <input type="text" size="20" name="ename"/>
<br><br>
Salary <input type="text" size="20" name="sal"/>
<br><br>
<input type="submit" value="insert" />
<div>
</form>
</body>
</html>

Change your form action in index.html to
<form action="WFormPost3" method="post">
Make sure by debugging that there does not exists any exception in your doPost method of WFormPost3.java servlet.

Related

Browser showing nothing while calling servlet

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);
}
}

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.

Ajax not working with JSP in username availability

I am trying to check database for username availability. I don't know where it went wrong but it just keep saying "Checking availability" and never returns the answer. Below is my code.
index.jsp;
<html>
<head>
<title>Username Availability</title>
<style type="text/css">
.flable {
color: gray;
}
.status {
font-family: verdana;
font-size: 12px;
}
.uname {
color: blue;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js "></script>
<script type="text/javascript">
$(document).ready(function(){
$(".uname").change(function(){
var uname = $(this).val();
if(uname.length >= 3){
$(".status").html("<img src='images/loading.gif'><font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "check",
data: "uname="+ uname,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
</head>
<body>
<div>
<label class="flable">User Name :</label> <input type="text" class="uname" /> <span class="status"></span>
</div>
</body>
</html>
CheckAvailibilty.java:
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String connectionURL = "jdbc:mysql://localhost:3306/quora"; // students is my database name
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
String uname = request.getParameter("uname");
PreparedStatement ps = connection.prepareStatement("select username from users where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
web.xml:
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>com.amzi.servlets.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
You don't need ajaxComplete, when you get a msg just feed it to html()
success: function(msg){
$(".status").html(msg);
}

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