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.
Related
This is my structure of the project:-
[1]: https://i.stack.imgur.com/ootY1.png
My problem is that whenever I am running my project on the server, there is an HTTP Status 404 Error.
This is the error I am getting by the server:-
The requested resource [/Doctor_Appointment_Application/Regis] is not available
I am using annotations to register my servlets and there is only a welcome file in my web.xml.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<display-name>User Login</display-name>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/JSP/login.jsp</welcome-file>
</welcome-file-list>
</web-app>
My Register Servlet:-
package com.servlet;
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;
import com.bean.RegisBean;
import com.dao.RegisDao;
#WebServlet("/Regis")
public class Regis extends HttpServlet {
private static final long serialVersionUID = 1L;
public Regis() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fullname=request.getParameter("fullname");
String email=request.getParameter("email");
String username=request.getParameter("username");
String password=request.getParameter("password");
long mobile= Long.parseLong(request.getParameter("mobile"));
String address=request.getParameter("address");
String identity=request.getParameter("radio");
String specialisation=request.getParameter("special");
String degree=request.getParameter("degree");
String exp=request.getParameter("exp");
String fees=request.getParameter("fees");
RegisBean regisBean=new RegisBean();
regisBean.setFullname(fullname);
regisBean.setEmail(email);
regisBean.setUsername(username);
regisBean.setPassword(password);
regisBean.setMobile(mobile);
regisBean.setAddress(address);
regisBean.setIdentity(identity);
if(identity.equals("Doctor")) {
regisBean.setSpecialiasation(specialisation);
regisBean.setDegree(degree);
regisBean.setExperience(exp);
regisBean.setFees(fees);
}
RegisDao dao=new RegisDao();
String userRegistered=dao.registerUser(regisBean);
if(userRegistered.equals("SUCCESS"))
request.getRequestDispatcher("/JSP/conf.jsp").forward(request, response);
else {
request.setAttribute("errMessage", userRegistered);
request.getRequestDispatcher("/JSP/register.jsp").forward(request, response);
}
}
}
EDIT 1:
Register.jsp:-
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration Page</title>
<style type="text/css">
<%-- <%#include file="/CSS/register.css"%> --%>
<%#include file="/CSS/regis.css"%>
</style>
<script src='https://kit.fontawesome.com/a076d05399.js'></script>
<script>
function validate() {
var password = document.form.password.value;
var confpassword = document.form.confpassword.value;
/* if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
} else */ if (password != confpassword) {
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
Full Name: <input type="text" name="fullname" required>
<br>
<br>
Email: <input type="text" name="email" required>
<br>
<br>
Username: <input type="text" name="username" required>
<br>
<br>
Password: <input type="password" name="password" required>
<br>
<br>
Confirm Password: <input type="password" name="confpassword" required>
<br>
<br>
Mobile Number: <input type="number" name="mobile" required>
<br>
<br>
Address: <input type="text" name="address" required>
<br>
<br>
Identity: Doctor <input type="radio" name="radio" value="Doctor" required>
<div class="reveal">
Specialisation: <select name="special" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="Allergist">Allergist</option>
<option value="Anesthesiologist">Anesthesiologist</option>
<option value="Cardiologist">Cardiologist</option>
<option value="Dermatologist">Dermatologist</option>
<option value="Endocrinologist">Endocrinologist</option>
<option value="Gastroenterologist">Gastroenterologist</option>
<option value="Hematologist">Hematologist</option>
<option value="Immunologist">Immunologist</option>
<option value="Internist">Internist</option>
<option value="Neurologist">Neurologist</option>
<option value="Pulmonologist">Pulmonologist</option>
<option value="Oncologist">Oncologist</option>
</select>
<br>
<br>
Degree: <select name="degree" class="require-if-active">
<option selected disabled>Choose...</option>
<option value="MBBS">MBBS</option>
<option value="BDS">BDS</option>
<option value="BAMS">BAMS</option>
<option value="BUMS">BUMS</option>
<option value="BHMS">BHMS</option>
<option value="BYNS">BYNS</option>
<option value="B.V.Sc & AH">B.V.Sc & AH</option>
</select>
<br>
<br>
Experience: <input type="number" name="exp" class="require-if-active">
<br>
<br>
Fees: <input type="number" name="fees" class="require-if-active">
</div>
Patient <input type="radio" name="radio" value="Patient" required>
<span style="color: red"><%=(request.getAttribute("errMessage") == null) ? "" : request.getAttribute("errMessage")%></span>
<br>
<br> <input type="submit" value="Register">
</form>
</body>
</html>
EDIT 2:
I just tried to do an experiment, what I did is I created another jsp file and a servlet to check if the problem is in my jsp and servlet files or not. So the same thing happened, the jsp file ran successfully but the server wasn't abl to find the servlet after submitting the form method.
Any kind of help is appreciated.
Hello to whosoever is seeing this,
I solved this query by removing the mysqljdbc.auth.dll from my build path. This solved my problem and it is working fine now. If you are having a problem with the mysqljdbc.auth.dll file, you just have to copy it in the JDK 8 bin folder and it will work fine.
Update (based on the update posted in the question):
Replace
<form name="form" action="<%=request.getContextPath() %>/Regis" method="post" onsubmit="return validate()">
with
<form name="form" action="Regis" method="post" onsubmit="return validate()">
as the paths in a JSP are already relative to the context path.
Original answer:
The reason why you are getting this error is that by default, the server gets the request as GET whereas you have not provided any implementation of doGet in your servlet. If you are calling this servlet from a JSP/HTML, make sure you mention method="POST". If you are trying to call the servlet directly, you can either rename doPost to doGet or provide an implementation of doGet e.g.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
This question already has answers here:
How can I retain HTML form field values in JSP after submitting form to Servlet?
(2 answers)
Closed 5 years ago.
So basically I have retrieved data from a database, have the values I need stored in an array. But I am having trouble setting the values in an HTML input field. I have three fields Welsh name, English name, and gender. So I need the welsh input field in the form to hold the welsh word and so on. How would I do this?
The HTML code;
<html>
<head>
<title>Academi Gymraeg</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Academi Gymraeg</h1>
<h2>Modify Vocabulary</h2>
<div class="login-form">
<div class="login-elements">
<br>
<form action="instructorServlet" name="searchVocab" method="post">
<input type="hidden" name="type" value="searchVocab" />
Word:
<input type="text" name="word" class="inputBox" required><br><br>
Language:<br>
<select name="language" class="dropDown">
<option value="English" selected>English</option>
<option value="Welsh">Welsh</option>
</select><br><br>
<button type="submit" class="button" name="search" value="search"
>Search</button><br><br>
</form>
<form action="instructorServlet" name="modifyVocab" method="get">
<input type="hidden" name="type" value="modifyVocab" />
Welsh Name:
<input type="text" name="welshName" class="inputBox" required><br><br>
English Name:
<input type="text" name="englishName" class="inputBox" required><br><br>
Gender:<br>
<select name="gender" class="dropDown">
<option value="Masculine" selected>Masculine</option>
<option value="Feminine">Feminine</option>
</select><br><br>
<button type="submit" class="subButton" name="modifyEntry" value="Modify Entry"
>Modify Entry</button>
<button type="reset" class="subButton" name="modifyEntry" value="Modify Entry"
>Reset</button>
</form><br>
<form action="instructorServlet" name="backToMenu" method="post">
<input type="hidden" name="type" value="backToMenu" />
<button type="submit" class="button" name ="backToMenu" value="backToMenu"
>Back To Menu</button>
</form>
</div>
</div>
</body>
The servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String form = request.getParameter("type");
if ("searchVocab".equals(form)) {
String searchFor = request.getParameter("search");
if (searchFor != null) {
String word = request.getParameter("word");
String language = request.getParameter("language");
String values[] = database.searchFor(word, language);
response.getOutputStream().println("<script> window.location = \"modify-vocab.html\";</script>");
response.getOutputStream().println("<script> document.getElementById(\"welshName\").value = " + values[0] + ";\n"
+ " document.getElementById(\"englishName\").value = " + values[1] + ";\n"
+ " document.getElementById(\"gender\").value = " + values[2] + "; </script>");
}
}
The form reloads, however, the values aren't put into the input fields they just load blank.
Your servlet should build the values you need and forward them to the JSP view.
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
// ... code to build your values
// Set the values
request.setAttribute("welshName", welshName);
request.setAttribute("englishName", englishName);
request.setAttribute("gender", gender);
// Ask the view to take care of the values
request.getRequestDispatcher("view.jsp").forward(request, response);
}
Your view.
<%
final String welshName = (String) request.getAttribute("welshName");
final String englishName = (String) request.getAttribute("englishName");
final String gender = (String) request.getAttribute("gender");
%>
Welsh Name: <input type="text" name="welshName" class="inputBox" value="<% out.print(welshName); %>"/>
English Name: <input type="text" name="englishName" class="inputBox" value="<% out.print(englishName); %>"/>
Gender:
<select name="gender" class="dropDown">
<option value="Masculine" <% out.print("masculine".equals(gender) ? "selected" : ""); %>>Masculine</option>
<option value="Feminine" <% out.print("feminine".equals(gender) ? "selected" : ""); %>>Feminine</option>
</select>
this is my first time attempting this kind of application I have a jsp file
<html>
<head>
<title>Flight booking</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css" type="text/css"
media="screen">`enter code here`
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("fname")%> !
</title>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel body" id="inner_panel_1">
<h4>
Welcome ,
<%=session.getAttribute("fname")%></h4>
</div>
<!--end panel 1 -->
<div class="panel body" id="inner_panel_2">
<form action="CustomerServlet" method="post">
<label for="viewClientInfo">View/Change
Client Information</label>
<input type="submit" name="viewClientInfo" id="viewClientInfo" class="btn btn-success"
data-toggle="collapse" data-target="#clientPanel">
</form>
<!-- end panel body -->
<div id="clientPanel" class="collapse">
<div
class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-xs-offset-0 col-sm-offset-0 col-md-offset-3 col-lg-offset-3 toppad">
<div class="panel panel-info">
<div class="panel-heading">
<h3 class="panel-title"></h3>
<td> <%=session.getAttribute("fname")%> </td>
<td> <%=session.getAttribute("lname")%> </td>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center">
<img alt="User Pic"
src="http://icons.iconarchive.com/icons/icons8/windows-8/128/Transport-Airplane-Takeoff-icon.png"
class="img-circle img-responsive">
</div>
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>First Name :</td>
<td><%=session.getAttribute("firstname")%></td>
</tr>
<tr>
<td>Last Name :</td>
<td><%=session.getAttribute("lastname")%></td>
</tr>
<tr>
<td>Apt Number:</td>
<td><%=session.getAttribute("aptNumber")%></td>
</tr>
<tr>
<td>Address</td>
<td><%=session.getAttribute("streetNum")%> <%=session.getAttribute("streetName")%>
</td>
</tr>
<tr>
<td>City, Country</td>
<td><%=session.getAttribute("city")%>, <%=session.getAttribute("country")%>
</td>
</tr>
<tr>
<td>Email</td>
<td><%=session.getAttribute("userEmail")%></td>
</tr>
<tr>
<td>Phone Number</td>
<td><%=session.getAttribute("phoneNum")%><br></td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-success" id="changePayment" data-toggle="collapse" data-target="#payment-panel">Change Payment Information</button>
</div>
</div>
</div>
</div>
</div>
<!--end panel 2 -->
</div>
<div id="payment-panel" class="collapse">
<div class="col-xs-12 col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Payment Details
</h3>
</div>
<div class="panel-body">
<form role="form" class="creditCard" action="CreditCardServlet" method="addCreditCard">
<div class="form-group">
<label for="cardNumber">
CARD NUMBER</label>
<div class="input-group">
<input type="text" class="form-control" id="cardNumber" placeholder="Valid Card Number"
required autofocus />
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
</div>
</div>
<div class="row">
<div class="col-xs-7 col-md-7">
<div class="form-group">
<label for="expiry">
EXPIRY DATE</label>
<div class="col-xs-6 col-lg-6 pl-ziro">
<input type="text" class="form-control" id="expiry" placeholder="MM/YYYY" required />
</div>
</div>
</div>
<div class="col-xs-5 col-md-5 pull-right">
<div class="form-group">
<label for="cvv">
CV CODE</label>
<input type="password" class="form-control" id="cvv" placeholder="CV" required />
</div>
</div>
</div>
</form>
<div class="col-md-4 text-center">
<button type="button" class="btn btn-success" id="submitPaymentInfo" >Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- end inner panel -->
<div class="panel body" id="inner_panel_3">
<button type="button" class="btn btn-success" id="viewBookings" data-toggle="collapse" data-target="#client-bookings-panel">View
Bookings</button>
</div>
<div id="client-bookings-panel" class="collapse">
<p>Client Bookings Dump for next Version</p>
</div>
<!--end panel 3 -->
<div class="panel body" id="inner_panel_4">
<button type="button" class="btn btn-success" id="bookFlightButton" data-toggle="collapse" data-target="#flight-booker-panel">Book
Flight for Next Version</button>
</div>
<div id="flight-booker-panel" class="collapse">Link to Flight Booker</div>
<!--end panel 4 -->
</div>
</div>
<!--end container -->
</body>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
I am trying to get the information of the user that just logged in from the db and by using the jsp above display it to them
public class UserInfoServlet {
public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException{
}
}
I know how to get information from jsp to java and save it to db but i do not know how to go to the oposite direction
You will need to connect to db then set the info in the session like this:
public class DatabaseAccess extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
//you can use your own connection thing in you don't like the below code
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";
static final String USER = "root";
static final String PASS = "password";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql;
sql = "YOUR QUERY. YOU SAID YOU ALREADY KNOW THIS";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
//Retrieve by column name
String fname = rs.getString("first");
String flast = rs.getString("last");
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
//get the session and set the values
HttpSession session = request.getSession();
session.setAttribute("fname", fname);
RequestDispatcher rd=req.getRequestDispatcher("/whateveristhejspname.jsp");
rd.forward(req, resp);
}
}
Make sure you have your mapping setup correctly in your web.xml file
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
public void doGet(HttpServletRequest request , HttpServletResponse response)throws ServletException {
HttpSession session = request.getSession();
//todo getSomeThing from DB
session.setAttribute("userInfo","yourMessage");
response.sendRedirect("your Page Location");
}
maybe you want this
I am using a form where i am adding an state into the database but now i want to use a server side validation for this form (like checking whether it is empty or not.) So please help me in this.
By the way i am new in jsp and want to learn server side validation in jsp page so plese let me know how to go about it.
String sql="insert into tblstate(fkCountry_Id,fldstate) "
+ "values('"+cou+"','"+sta+"')";
try{
conn.createStatement().executeUpdate(sql);
conn.setAutoCommit(true);
// New location to be redirected
String site = new String("add_state.htm");
response.setStatus(response.SC_MOVED_TEMPORARILY);
response.setHeader("Location", site);
}catch(Exception e){
e.printStackTrace();
}
%>
" method="POST">
<div class="control-group">
<label class="control-label" for="selectError">Country</label>
<select class="form-control" name="cou">
<option value="none">Select</option>
<%
String sql_cou = "select * from tblcountry";
PreparedStatement coun=conn.prepareStatement(sql_cou);
ResultSet rs_cou = coun.executeQuery(sql_cou);
while(rs_cou.next()){
out.println("<option value=" + rs_cou.getString("pkCountry_Id")+ "> " + rs_cou.getString("fldCountry")+"</option>");
}
%>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">State</label>
<input name="sta" type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Dzongkhag">
</div>
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Cancel</button>
</form>
</div>
I am trying to get info from option boxes from my JSP page. An example of those are:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Language" content="en" />
<title>Profile</title>
<link rel="shortcut icon" href="../favicon.png" />
<link rel="stylesheet" href="../reset.css" />
<link rel="stylesheet" href="app/claro.css" />
<link rel="stylesheet" href="app/theme/main.css" />
<script type="text/javascript">
// Configure application.
appConfig = {
// Get base url from current url.
baseUrl: location.href.substring(0,location.href.lastIndexOf("/")+1)
};
// Configure Dojo.
dojoConfig = {
parseOnLoad: true
};
</script>
<script type="text/javascript" src="http://cdn.devgrid.net/ajax/dojo/1.9.0/dojo/dojo.js"></script>
<script type="text/javascript">
// Load application.
require(
{
packages: [
{ name: 'app', location: appConfig.baseUrl + '/app/' }
]
},
[
"app"
]
);
</script>
</head>
<body class="claro">
<%
//allow access only if session exists
String user = null;
if(session.getAttribute("user") == null){
response.sendRedirect("login.jsp");
}else user = (String) session.getAttribute("user");
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<div class="appBorderContainer" data-dojo-type="dijit/layout/BorderContainer">
<div data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'top', splitter:false">
<center><IMG SRC="LogoPlaintech.png" width="30%"></center>
</div>
<div class="appLeadingAccordionContainer" data-dojo-type="dijit/layout/AccordionContainer" data-dojo-props="minSize:20, region:'leading', splitter:true">
<div data-dojo-type="dijit/layout/AccordionPane" title="Server status">
Server: RUNNING</br>
IP-address: 0.0.0.0</br>
Uptime: 12 hours 21 minutes 10 seconds </br>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Add a server">
<div data-dojo-type="dijit/form/Form" enctype="multipart/form-data" action="productServlet" method="post">
<div data-dojo-type="dojox/layout/TableContainer" data-dojo-props="cols:1">
<div data-dojo-type="dijit/form/TextBox" title="Name server:" name="name" value=""></div>
<select data-dojo-type="dijit/form/Select" title="Operating System:" name="os">
<option value="Windows">Windows Server 2012</option>
<option value="Ubuntu">Ubuntu 14.10</option>
<option value="Debian">Debian 7.7.0</option>
</select>
<select data-dojo-type="dijit/form/Select" title="Amount of cores:" name="cores">
<option value="1">1 core</option>
<option value="2">2 cores</option>
<option value="3">3 cores</option>
</select>
<select data-dojo-type="dijit/form/Select" title="RAM:" name="ram">
<option value="512">512 MB</option>
<option value="1024">1024 MB</option>
<option value="2048">2048 MB</option>
</select>
<select data-dojo-type="dijit/form/Select" title="HDD:" name="hdd">
<option value="20">20 GB</option>
<option value="35">35 GB</option>
<option value="50">50 GB</option>
<option value="75">75 GB</option>
</select>
</div>
<button id="btnSubmit" data-dojo-type="dijit/form/Button" type="submit" role="button">Submit</button>
</div>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Third pane">
Third pane content.
</div>
</div>
<div id="appCenterTabContainer" data-dojo-type="dijit/layout/TabContainer" data-dojo-props="splitter:true, region:'center'">
<div data-dojo-type="dijit/layout/ContentPane" title="Welcome">
<h3>Hi <%=userName %>, Login successful.</h3></br>
Welcome at your profile page <%=userName %>. </br>
We are happy to see you back.</br>
</br>
From this point it is possible to manage your VM('s), account info and backups.
</div>
<div data-dojo-type="dijit/layout/ContentPane" title="Connect to your server">
You can login to your server by SSH, with your credentials. </br>
IP-address: 0.0.0.0</br>
Port: 22</br>
Username: </br>
Password: </br>
</br>
<center>
<button data-dojo-type="dijit/form/Button" type="button" role="button">Connect
<script type="dojo/on" data-dojo-event="click" data-dojo-args="evt">
app.alert('You are now connecting to your server! Awesome ;-)');
</script>
</button>
</center>
</div>
</div>
<div class="appTrailingAccordionContainer" data-dojo-type="dijit/layout/AccordionContainer" data-dojo-props="minSize:20, region:'trailing', splitter:true">
<div data-dojo-type="dijit/layout/AccordionPane" title="Account info">
Fullname: </br>
${fullName}</br></br>
Email address: </br>
${email}</br></br>
Date of birth: </br>
${dateOfBirth}</br></br>
Phonenumber: </br>
${phoneNumber}</br></br>
<hr>
</br>
Company name: </br>
${companyName}</br></br>
Company email address: </br>
${companyEmail}</br></br>
Payment method: </br>
${paymentMethod}</br></br>
</br>
<button data-dojo-type="dijit/form/Button" type="button" role="button">
Change account info
</button>
</div>
<div data-dojo-type="dijit/layout/AccordionPane" title="Logout">
Are you sure you want to logout the user <%=userName %>?</br></br>
<div data-dojo-type="dijit/form/Form" id="LogoutServlet"
action="LogoutServlet" method="post">
<form action="LogoutServlet" method="post">
<table>
<tr>
<td><button data-dojo-type="dijit/form/Button" type="submit"
name="submitButton" value="Yes">Yes</button></td>
</tr>
</table>
<div data-dojo-type="dijit/form/Form" id="profile.jsp"
action="profile.jsp" method="post">
<form action="profile.jsp" method="post">
<table>
<tr>
<td><button data-dojo-type="dijit/form/Button" type="submit"
name="submitButton" value="No">No</button></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Now the problem is that I get an null pointer exception at line 32. So I guess the parameter Ram is empty or something? Am I trying todo this the wrong way? Please help me out here! thanks.
import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class productServlet extends HttpServlet {
public String name;
public String os;
public String hdd;
public String processor;
public String ram;
public String userName;
public ResultSet rs, rs1;
public PreparedStatement pstmt;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// haal info van de website.
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String Name = request.getParameter("name");
// zet de info van de website in public variables.
Name = name;
String[] OS = request.getParameterValues("os");
if(OS.equals("Windows")) {
os = "Windows";
} else if(OS.equals("Ubuntu")) {
os = "Ubuntu";
} else if(OS.equals("Debian")) {
os = "Debian";
}
String[] Processor = request.getParameterValues("cores");
if(Processor.equals("1")) {
processor = "1";
} else if(Processor.equals("2")) {
processor = "2";
} else if(Processor.equals("3")) {
processor = "3";
}
String[] Ram = request.getParameterValues("ram");
if(Ram.equals("512")) {
ram = "512";
} else if(Ram.equals("1024")) {
ram = "1024";
} else if(Ram.equals("2048")) {
ram = "2048";
}
String[] HDD = request.getParameterValues("hdd");
if(HDD.equals("20")) {
hdd = "20";
} else if(HDD.equals("35")) {
hdd = "35";
} else if(HDD.equals("50")) {
hdd = "50";
} else if (HDD.equals("75")) {
hdd = "75";
}
// test van OS
System.out.print(os);
}
Make sure your (comboboxes / option boxes) have between form tag start and close including your action button.
eg.
<form action="youraction" method="post/get">
//comboboxes / option boxes and your parameters
.........
.........
<button>.......submit/invoke button </button>
</form>