i've been calling servlet by a HTML page and my servlet code goes like this:
import java.sql.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
public class validation extends HttpServlet
{
static PrintWriter pw = null;
public void doPost(HttpServletResponse response, HttpServletRequest request) throws ClassNotFoundException, SQLException, IOException, ServletException
{
pw = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
RequestDispatcher rd = request.getRequestDispatcher("new.html");
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/timetabledb", "root","`");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select password from users where username = '"+username+"';");
if(rs.next()==false)
{
pw.println("No such user found!");
}
else
{
if(password.equals(rs.getString("password")))
{
rd.forward(request, response);
}
else
{
pw.println("Invalid credentials!");
}
}
rs.close();
}
}
and my html page is this:
<!DOCTYPE html>
<html>
<head>
<title>Login Page - SGMS</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
<div id = "container">
<div class = "welcome-head">
Welcome
</div>
<div class = "sw-head">
Semi-Automatic Schedule Generator & Maintenance Software
</div>
<span class="logo">
<img src="logo.gif" alt="Logo"/>
</span>
<div class = "form">
<form method="POST" action="validation">
<label for="inp-usr" class="inp">
<input type="text" name="username" id="inp-usr" placeholder=" " required="required">
<span class="label">Username</span>
<span class="border"></span>
</label>
<br>
<label for="inp-pwd" class="inp">
<input type="password" name="password" id="inp-pwd" placeholder=" " required="required">
<span class="label">Password</span>
<span class="border"></span>
</label>
<br><br><br>
<button class="validate-btn" onclick="show();">
Validate
</button>
</form>
</div>
</div>
</body>
</html>
but the problem is that whenever i run all this, the application server says, that POST method isn't supported by this url.
I've experienced this error frequently, please explain why all this happens.
I've mapped the servlet in my web.xml
Thanks in advance.
You have made a mistake in your doPost method. You have declared it as this:
void doPost(HttpServletResponse response, HttpServletRequest request)
throws ClassNotFoundException, SQLException, IOException, ServletException
but the correct signature is this:
void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Notice the different parameter order ....
Since your method doesn't have the correct signature, it is not overriding the inherited version. That means that your version never gets called. Instead, a POST requests calls the inherited method ... and the behavior of that is to say "POST not supported".
Solution:
Correct your doPost method's signature. (The exceptions will need fixing too!)
Add an #Override annotation to this ... and any other override methods in this class.
Get into the habit of always using #Override wherever you intend to override a method ... so that the Java compiler can point out your mistakes to you.
Related
I was trying to add a servlet to my Maven project and when I run the application and access its URL it gives me this error.
I leave you the servlet code and the index.html.
When I access http://localhost:8090/ServletSaludo / I get the error This application has no explicit mapping for / error, so you are seeing this as a fallback. I don't see the fault, I think I have created it and done everything right.
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet("/ServletSaludo")
public class ServletSaludo extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hola Mundo!</TITLE></HEAD>");
out.println("<BODY>");
String nombre = (String) request.getParameter("nombre");
if (nombre != null) {
out.println("Hola " + nombre + "<br>");
}
out.println("</BODY></HTML>");
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet( request,response );
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlets</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"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Contenido -->
<div class="container" id="contenedor-principal">
<h2>Formulario GET Saludar</h2>
<form action="ServletSaludo" method="get">
<div class="form-group">
<label for="nombre-get">Nombre</label>
<input type="text" class="form-control" name="nombre" id="nombre-get">
</div>
<button type="submit" class="btn">Enviar</button>
</form>
<h2>Formulario POST</h2>
<form action="ServletSaludo" method="post">
<div class="form-group">
<label for="nombre-post">Nombre</label>
<input type="text" class="form-control" name="nombre" id="nombre-post">
</div>
<button type="submit" class="btn">Enviar</button>
</form>
</div>
</body>
</html>
I replicated your application and it worked for me. Please see the folder structure on whether you've kept it correctly or not.
And one more thing, since you added a tag for Spring boot, you can use #RestController or #Controller to create endpoints for your project.
I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");
PersonalInfoOutput.java servlet is using the doPost method. The user logs in at index.html. From index.html, the request is sent to Login.java servlet.
From there, the user is directed to the PersonalInfoOutput.java servlet.
Now, consider another page called ChangePassAdmin.html. In this html code, one of these goes to PersonalInfoOutput.java. But when I click on it from that page,
I get HTTP Status 405 - HTTP method GET is not supported by this URL.
Can someone please help me as to how I should solve this problem?
I tried changing PersonalInfoOutput.java to doGet instead of doPost but then Login.java servlet will return HTTP Status 405 - HTTP method POST is not supported by this URL. So it seems I need both doGet and doPost for this PersonalInfoOutput.java servlet.
PersonalInfoOutput.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String employeeid = "";
if(session != null) {
employeeid = (String)session.getAttribute("employeeid");
}
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 employeeID, FirstName, LastName, Admin, DOB, Address, Email, HourlyRate, Gender, ALeaveBalance, SLeaveBalance, ActiveStatus, Role, BSB, BankName, AccNumber, SuperNumber, SuperCompany from payroll_system.employee_info where employeeID = ?");
ps.setString(1, employeeid);
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
etc... (rest of the code isn't relevant to question)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<title>Login</title>
</head>
<body>
<form action="Login" method="post">
<h1>
Login
</h1>
<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");
HttpSession session = request.getSession();
session.setAttribute("employeeid", employee_id);
if(ValidateLogin.user(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("PersonalInfoOutput");
rs.forward(request, response);
}
else
{
out.print("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
ChangePassAdmin.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<link rel = "stylesheet" type = "text/css" href = "sidebar.css">
<title>Change Password</title>
<style>
table { border-collapse: collapse; width: 50%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2}
tr:hover {background-color: #e2f4ff;}
</style>
</head>
<body>
<ul>
<li><a href=PersonalInfoOutput>View Personal Information</a></li>
<li><a href=PersonalInfoOutput>View Expense Claims</a></li>
<li><a href=PersonalInfoOutput>View Payslips</a></li>
<li><a class=active >Change Password</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Tax Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Payroll Items</a></li>
<li><a href=PersonalInfoOutput>Maintain Timesheet</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Expenses</a></li>
<li><a href=PersonalInfoOutput>Run Payroll</a></li>
<li><a href=PersonalInfoOutput>Generate Reports</a></li>
</ul>
<div style=margin-left:25%;padding:1px;>
</div>
<div id="container">
<h1>Change Password</h1>
<form action ="NewPassword" method = post>
<table border ="1">
<tr>
<td>Existing Password:</td>
<td><input type = "password" name = "oldpassword" size = "20"></td>
</tr>
<tr>
<td>New Password:</td>
<td><input type = "password" name = "newpassword" size = "20"></td>
</tr>
<tr>
<td>Confirm New Password</td>
<td><input type = "password" name = "confirmpassword" size = "20"></td>
</tr>
</table>
<br>
<br>
<input type = "submit" value = "Update Password">
</form>.
</div>
</body>
</html>
In ChangePassAdmin.html, double quotes around post are missing.
Both of your Servlet should have doPost method as your form is using "post" action.
<form action ="NewPassword" method = "post">
Additionally you will need two methods in this case. Add both doGet and doPost in your servlet. doPost will be used by form and doGet by links. By default all links are GET.
You can do it like:
Edit:
public class PersonalInfoOutput extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Your servlets code should be here
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
doPost() method to receive form based request. doGet() method to receive href based request. But in both cases processRequest() method will be called.
I believe the problem is that you're using the PersonalInfoOutput servlet in two ways:
Forwarding from Login servlet, which by forwarding keeps using POST method
And by href from the HTML, which by default uses method GET
Wouldn't a possible solution be for you to refactor your code, which would be good for you to do anyway, so that you implement both doGet() and doPost() in the PersonalInfoOutput servlet without repeating a lot of code?
Or you could refactor the employee database retrieval to an external class, that would be called from Login without the need to redirect from one servlet to another, and implement GET instead of POST in PersonalInfoOutput.
This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}
I am new here and have been working on this all evening. I know this should be simple and I am just missing something silly. I have a jsp page and a servlet (code below). I am trying to search out a customer from my database, which works. However, if the customer is not found I want to post an error message on the same jsp page so that the user can possibly re-enter the phone number in case they made a mistake. I am unsure how to do this. I can forward to the new "customer" page just fine and I have tried successfully to redirect back to the same page, but I don't know how to put the message there. Help please!
jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false" %>
<%# page import="java.util.*" %>
<%# include file="staticpages/pageHeader.html" %>
<br />
<hr />
<br />
<form name="custform" method="POST" action="ChooseCustomer.do" >
<span class="sectionheader">Look Up Customer by Phone Number:</span>
<input type="text" name="phone1" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone2" size="3" maxlength="3" onKeyUp="checklen(this)" />
<input type="text" name="phone3" size="4" maxlength="4" onKeyUp="checklen(this)" />
<input type="submit" name="formaction" value="Search" />
<input type="submit" name="formaction" value="Enter New Customer" />
</form>
<%# include file="staticpages/pageFooter.html" %>
servlet code:
package pizzapkg;
import java.io.IOException;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ChooseCustomer
*/
#WebServlet("/ChooseCustomer")
public class ChooseCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
/** #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Customer c = null;
if (request.getParameter("formaction").equals("Search")) {
Database db = (Database) getServletContext().getAttribute("db");
/* Search Database for existing customer */
String searchPhone = request.getParameter("phone1")
+ request.getParameter("phone2")
+ request.getParameter("phone3");
String sql = "SELECT * FROM customers WHERE cust_phone=\"" + searchPhone + "\";";
ResultSet rs;
try {
rs = db.runSqlQuery(sql);
rs.next();
c = new Customer(rs.getString("cust_id"), rs.getString("cust_fname"),
rs.getString("cust_lname"), rs.getString("cust_address"),
rs.getString("cust_city"), rs.getString("cust_state"),
rs.getString("cust_zip"), rs.getString("cust_phone"),
rs.getString("cust_notes"));
} catch (Exception e) { e.printStackTrace(); }
request.setAttribute("customer", c);
}
RequestDispatcher rd = request.getRequestDispatcher("/customer.jsp");
rd.forward(request, response);
}
}
PS This the the first time I have built a servlet so this is all new to me. I love examples so any help you can give will be greatly appreciated.
You may set a flag in request object inside your servlet, if the customer is not found e.g.
request.setAttribute("customerFound", "No");
In your JSP, put a JSP scriptlet to check the request attribute and print the message wherever you want e.g. if you want the message after your <HR/> then:
<hr />
<% if("No".equals(request.getAttribute("customerFound")) { %>
<div style="color: red">No customer found</div>
<% } %>
<br />
I am sharing the very basic way of achieving your desired result.