I am trying to handle input from a basic HTML form in Java. However, whenever I click the submit button on the form I get this error: "The requested URL /formHandler was not found on this server."
Following are the form and the Java servlet, both of which live in the same directory, along with all the other files for this site. Any ideas why the servlet is not being found?
FORM
<form method="post" action="formHandler">
<label for="name">Name: </label>
<input name="name" defaultValue="name"/><br/>
<label for="email">Email: </label>
<input name="email" defaultValue="email"/><br/>
<label for="details">Further Details or Comments</label><br/>
<input name="details" defaultValue="details"/><br/><br/>
<input type="submit" value="Submit"/>
</form>
SERVLET
#WebServlet("/formHandler")
public class FormHandler extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String details = request.getParameter("details");
PrintWriter writer = response.getWriter();
String htmlRespone = "<html>";
htmlRespone += "<h2>Thank you " + name + ", a confirmation email will be sent to " + email + " shortly.</h2>";
htmlRespone += "</html>";
writer.println(htmlRespone);
}
}
Related
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");
I am creating an online bank. On login, it created a session for that user. The user than has options to click on different transaction types.So when the user clicks on open an account button, it will go to openAccount.jsp page. I also have a form with a users first name, last name, and email in the openAccount.jsp. When the user clicks on the open account button and is redirected to the openAccount.jsp, I want the form to be prefilled from the database based. I am not sure how? Here is my code so far:
home-page.jsp
<div class="col-md-4">
<form name = "OpenAccount" action="open-account.jsp" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
open-account.jsp
<!DOCTYPE html>
<html>
<head>
<title>Open Account</title>
</head>
<body>
<h3>Please fill in the details</h3>
<form name="predifinedFields">
First Name: <input type="text" name="firstname" value= <%= request.getAttribute("firstname") %> > <br/><br/>
Last Name: <input type="text" name="lastname" value= <%= request.getAttribute("lastname") %>> <br/><br/>
Email: <input type="text" name="email" value= <%= request.getAttribute("email") %>> <br/><br/>
</form>
<form name="openAccount" action="OpenAccount" method="POST">
Select the type of account:
<select name="accounttype">
<option>Checking</option>
<option>Saving</option>
</select> <br/><br/>
Initial Deposit: $<input type="text" name="deposit"> <br/><br/>
Please check the box if everything above is complete:
Agree <input type="radio" name="agree" value="Agree">
Disagree <input type="radio" name="agree" value="Disagree">
<br/><br/>
<input type="submit" value="submit" name="Submit">
</form>
</body>
</html>
OpenAccount.java
public class OpenAccount extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = "";
HttpSession session = request.getSession(false);
if(session != null)
{
username = (String) session.getAttribute("username");
Users users = new Users();
users = DBConnection.getUsers(username);
request.setAttribute("firstname", users.getFirstName());
request.setAttribute("lastname", users.getLastName());
request.setAttribute("email", users.getEmail());
//request.setAttribute("username", users.getUsername());
}
// String firstName = (String) request.getParameter("firstname");
// String lastname = (String) request.getParameter("lastname");
String email = (String) request.getParameter("email");
String accountType = (String) request.getParameter("accounttype");
String accept = (String) request.getParameter("agree");
String deposit = (String) request.getParameter("deposit");
if(accept.equals("Agree"))
{
if(accountType.equals("Checking"))
{
DBConnection.newCheckingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
else if(accountType.equals("Saving"))
{
DBConnection.newSavingAccount(email, deposit);
RequestDispatcher dispatcher = request.getRequestDispatcher("home-page.jsp");
dispatcher.forward(request, response);
}
}
else
{
System.out.println("Please modify the changes");
RequestDispatcher dispatcher = request.getRequestDispatcher("open-account.jsp");
dispatcher.forward(request, response);
}
}
}
Database.java
public static Users getUsers(String username)
{
Users user = new Users();
try
{
DBConnection.connectToDB();
String query = "SELECT * FROM userlogin where username=?";
stmt = DBConnection.conn.prepareStatement(query);
stmt.setString(1,username);
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
user.setFirstName(rs.getString("firstname"));
user.setLastName(rs.getString("lastname"));
user.setEmail(rs.getString("email"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
}
}
catch(Exception e)
{
System.out.println(e);
}
return user;
}
In your case (basic servlet), you should follow this logic :
->browser
->servlet which loads and prepares required data from database into request attributes as you have done and finally forwards to open-account.jsp
->open-account.jsp use request attributes to render dynamically fields with your data retrieved from your database.
For other use cases, try to keep this simple logic :
->browser
->servlet processing ....
->jsp rendering ....
Your form in home-page.jsp should post to the servlet (controller) :
<div class="col-md-4">
<form name = "OpenAccount" action="/OpenAccount" id="openaccount">
<p>
<button type="submit" class="btn btn-primary btn-lg">Open Account</button>
</p>
</form>
</div>
You should rename OpenAccount to OpenAccountServlet (keeping conventions is better) and configure correctly the servlet of OpenAccountServlet in your web.xml (or with annotations).
If you use web.xml file for the servlet configuration, the url posted in the previous jsp (action="/OpenAccount") should match with the value in <url-pattern>/OpenAccount</url-pattern>
The forward should do like that :
getServletContext().getRequestDispatcher("yourRequiredPath/open-account.jsp ").forward(request, response);
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 have a java upload servlet and jsp form. the upload portion is working fine but i cannot get the regular form values in the upload servlet java code so that i can use these. Right now, I am trying to get the form data with request.getParameter("name"); but it is return null values. I am able to get the field values using item.getFieldName() and item.getFieldValue() but these are not really usable in additional processes in the item.iterator but these are not usable in further operations. For example, I want to pull in the email address field value so that I can send an email at the end of my upload servlet. I cannot use this data if I cannot make it into a string or variable which is where I am having issues. Any advice?
jsp file:
jsp form:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Username: <input type="text" name="username" value="username"/><br>
E-mail: <input type="email" name="email" autocomplete="on"><br>
<br>
Select file to upload:<input type="file" name="uploadFile" /><br>
<input type="submit" value="Upload" />
</form>
Java file:
UploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("username");
System.out.println(id); //returns null value
String password = request.getParameter("email");
System.out.println(password);//returns null value
For using file upload you get value only in form field.
request method not work in file upload
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multipart) {
if (!item.isFormField();
{
//Your upload file code.
}
if (item.isFormField()) {
if (item.getFieldName().equals("username")) {
String id = item.getString();
}else if (item.getFieldName().equals("email")) {
String password = item.getString();
}
}
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 7 years ago.
Hey I am quite new to servlet environment. Here I am trying to post a form to my servlet with something like this:
<form action="OnlineExam?q=saveQuestion" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Question</legend>
<textarea class="questionArea" id="question" name="question">Enter Question.</textarea>
<br class="clearFormatting"/>
Attach File<input type="file" name="file" />
<input class="optionsInput" value="Option A" name="A" onfocus = "clearValues('A')" onblur = "setValues('A')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option B" name="B" onfocus = "clearValues('B')" onblur = "setValues('B')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option C" name="C" onfocus = "clearValues('C')" onblur = "setValues('C')"/>
<br class="clearFormatting"/>
<input class="optionsInput" value="Option D" name="D" onfocus = "clearValues('D')" onblur = "setValues('D')"/>
<br/>
<input type="submit" value="Save" />
<input type="reset" value="Cancel" />
<button style="display: none" onclick="return deleteQuestion()" >Delete</button>
</fieldset>
</form>
And the servlet is something like this:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("q").equals("saveQuestion")){
saveQuestion(request);
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public void saveQuestion(HttpServletRequest request){
Enumeration enum = request.getParameterNames();
while (enum.hasMoreElements()) {
String pName = (String) enum.nextElement();
String[] pValues = request.getParameterValues(pName);
System.out.print("<b>"+pName + "</b>: ");
for (int i=0;i<pValues.length;i++) {
System.out.print(pValues[i]);
}
out.print("<br>");
}
}
But it is printing only the q parameter not the other form fields.
I also tried to get them with the request.getParameter("question") but this was also not working. So where i am going wrong. actually i am from PHP background and recently started coding in java so please help.
Thanks in advance
When you use enctype="multipart/form-data" you can not access request parameter as you normally do[that is request.getParameter("question")]. You have to use MultipartRequest object.
And also you submit form in POST and then in servlet you redirect it to doGet. Why so? Why don't directly use GET as a method in form submit.
Demo to use MultipartRequest:
String ph="images\\";
MultipartRequest req=new MultipartRequest(request, ph);
String question=req.getParameter("question");
System.out.println("Question: "+question);
why is your form action looking like a GET request with the ?q=saveQuestion, while the form type is POST? maybe the GET parameter is ignored on this call.