I have created a registration form. And I don't know why now it doesn't work anymore.
Now I receive a 404 error:
Type Status Report
Message /HotelReservation/Registration
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
This is my
Registration.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hotel;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author OOPs
*/
public class Registration extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String s1 = request.getParameter("ename");
String s2 = request.getParameter("nname");
String s3 = request.getParameter("pname");
String s4 = request.getParameter("usid");
String s5 = request.getParameter("gm");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code.
out.println(s1);
out.println(s2);
out.println(s3);
out.println(s4);
out.println(s5);*/
// out.println(s1);
//concetivity...............
Class.forName("com.mysql.jdbc.Driver");
out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/HotelReservation","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
out.println("conncetion successfull");
st.executeUpdate("insert into register (email,name,pass) values ('"+s1+"','"+s2+"','"+s3+"')");
out.println("<h1> Register sucsefulltttt </h1>");
response.sendRedirect("thankyou.jsp");
}catch(Exception e){
out.println("nahiiiiiiiiiiiii" +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
And this is my
registration.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
<style>
#import url( css/default.css);
</style>
</head>
<body>
<div id="container">
<div id="nav">
Home
Prenotazione
Camere
Login
Registrazione
</div>
<script>
function validate()
{
if(document.getElementById("ename").value=="")
{
alert("blank");
return false;
}
return true;
}
</script>
<h2>Registrazione</h2>
<form action="Registration" method="post" onsubmit="return validate();">
<div class="gender">
<label id="icon" for="name"><i class="icon-envelope "></i></label>
<input type="text" name="ename" id="ename" placeholder="Email" required/>
<br>
<br>
<label id="icon" for="name"><i class="icon-user"></i></label>
<input type="text" name="nname" id="nname" placeholder="Name" required/>
<br>
<br>
<label id="icon" for="name"><i class="icon-shield"></i></label>
<input type="password" name="pname" id="pname" placeholder="Password" required/>
<br>
<input class="button" type="submit" value="Sign UP" name="b1"> </input>
<input class="button" type=button onClick="location.href='login.jsp'" value="Login" name="b" > </input>
</form>
<div id="footer">
<h4>Hotel Reservation </h4>
Viale Marco Polo, 81 Roma
tel: +39 01 0000000 | info#hotelreservation.it
P.IVA 000000001
</div>
</div>
</body>
</html>
How can I solve it in your opinion? Thanks
EDIT:
This is my :
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Hotelbooking</display-name>
<servlet>
<servlet-name>Hotelbooking</servlet-name>
<servlet-class>hotel.Hotelbooking</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hotelbooking</servlet-name>
<url-pattern>/hotelbooking</url-pattern>
</servlet-mapping>
<display-name>Login</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>hotel.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<display-name>Logout</display-name>
<servlet>
<servlet-name>Logout</servlet-name>
<servlet-class>hotel.Logout</servlet-class>
</servlet>
<display-name>Registration</display-name>
<servlet>
<servlet-name>Registration</servlet-name>
<servlet-class>hotel.Registration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registration</servlet-name>
<url-pattern>/registration</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
</web-app>
HTTP Status 404 – Not Found
Type Status Report
Message /HotelReservation/Registration
Description The origin server did not find a current representation
for the target resource or is not willing to disclose that one exists.
myProject
Write your doGet method to forward at registration.jsp like this
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/registration.jsp").forward(request, response);
}
Another thing in error message map showing /HotelReservation/Registration
but in web.xml file servlet mapping is /registration. So hit correct url
Related
I'm working on one web app. I have problem when I want to test my servlet.
When I run my servlet error pops up -
HTTP Status 404 - Not Found.
I search another similar problems but i can't find solution. I think that there is no connection between my servlet and jsp file. Below my code:
GetServletController
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Adam
*/
public class GetServletController extends HttpServlet {
// private HandsDBUtil handsDBUtil;
//
// private ServletConfig config = getServletConfig();
// private ServletContext context = config.getServletContext();
//
// private String user = null;
// private String pass = null;
// private String c_name = null;
// private String url = null;
// #Override
// public void init() throws ServletException {
// super.init();
// Enumeration enumeration = context.getInitParameterNames();
// while (enumeration.hasMoreElements()) {
// String name = (String) enumeration.nextElement();
// switch (name) {
// case "url":
// url = context.getInitParameter(name);
// break;
// case "pass":
// pass = context.getInitParameter(name);
// break;
// case "user":
// user = context.getInitParameter(name);
// break;
// case "c_name":
// c_name = context.getInitParameter(name);
// break;
// }
// }
//
// handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
//
// }
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain; charset=ISO-8859-2");
PrintWriter out = response.getWriter();
out.println("WOW");
HandsDBUtil handsDBUtil;
ServletConfig config = getServletConfig();
ServletContext context = config.getServletContext();
String user = null;
String pass = null;
String c_name = null;
String url = null;
Enumeration enumeration = context.getInitParameterNames();
while (enumeration.hasMoreElements()) {
String name = (String) enumeration.nextElement();
switch (name) {
case "url":
url = context.getInitParameter(name);
break;
case "pass":
pass = context.getInitParameter(name);
break;
case "user":
user = context.getInitParameter(name);
break;
case "c_name":
c_name = context.getInitParameter(name);
break;
}
}
handsDBUtil = new HandsDBUtil(user, pass, c_name, url);
out.println("wow");
out.println(user);
try {
//listHands(request, response);
List<Hand> hands = handsDBUtil.getHands();
System.out.println(hands);
request.setAttribute("HAND_LIST", hands);
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
dispatcher.forward(request, response);
} catch (Exception ex) {
throw new ServletException(ex);
}
}
// private void listHands(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception {
//
// List<Hand> hands = handsDBUtil.getHands();
//
// request.setAttribute("HAND_LIST", hands);
//
// RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
// dispatcher.forward(request, response);
//
// }
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
jsp
<%#page import="java.util.*, Servlets.GetServletController, Servlets.Hand" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Poker Hands List</title>
</head>
<form action="GetServletController"/>
<%
List<Hand> theHands = (List<Hand>) request.getAttribute("HAND_LIST");
%>
<body>
<%= theHands %>
<div id="wrapper">
<div id="header">
<h2>
Poker Hands List
</h2>
</div>
</div>
<div id="container">
<div id="content">
</div>
</div>
</body>
</html>
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">
<context-param>
<param-name>url</param-name>
<param-value>jdbc:derby://localhost:1527/lab</param-value>
</context-param>
<context-param>
<param-name>c_name</param-name>
<param-value>org.apache.derby.jdbc.ClientDriver</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>lab</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>lab</param-value>
</context-param>
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>Servlets.ServletTest</servlet-class>
</servlet>
<servlet>
<servlet-name>GetServletController</servlet-name>
<servlet-class>Servlets.GetServletController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/ServletTest</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GetServletController</servlet-name>
<url-pattern>/GetServletController</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>getHands.jsp</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>mainMenu.jsp</welcome-file>
</welcome-file-list>
</web-app>
Request dispatcher is used to dispatch request to any resources,such as HTML, Image, JSP, Servlet on the server. If you want to forward your request to a jsp you need to define like below
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands.jsp");
In your case you are forwarding the request to a servlet.
RequestDispatcher dispatcher = request.getRequestDispatcher("getHands");
There is no such servlet defined in your web.xml
That's why you are getting 404 error
Situation: In the code below I'm attempting to learn how to use form parameters specifically redirecting Java servlets by propagating string query parameters.
Problem: I can't seem to figure out why I'm facing a problem with re-directing the user from the form i.e. index.html using the desired string query paramters to the correct page.
Below are the steps I took before posting this up:
I made sure the URL pattern for the #WebServlet annotation is correct
i.e. in my case /CityManagerWebStarter/mainmenuresponder.do
I made sure my content-root when looking at the URL is correct i.e.
/CityManagerWebStarter and I can confirm this as when I launch the
following URL http://localhost:8080/CityManagerWebStarter/ it
displays the index.html page as expected.
Below is my servlet code and following that is my index.html code and ListCities.html is an example of a page I'm attempting to re-direct the user to:
servlet code:
package company.citymanagerweb.servlets;
import java.io.IOException;
import java.io.PrintWriter;
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 MainMenuResponder
*/
#WebServlet("/CityManagerWebStarter/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MainMenuResponder() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userChoiceSelect = request.getParameter("menuChoice");
String[] userOptionsCBox = request.getParameterValues("adminoptions");
StringBuilder params = new StringBuilder();
String queryStringParams = params.toString();
if(userOptionsCBox != null) {
boolean isFirst = true;
for(int i = 0; i < userOptionsCBox.length; i++) {
// Build URL with string query parameters i.e. URL + ? + PARAM1 + AMAPERSAND + PARAM2
// Arguments is value of the value attribute
if(!isFirst) {
params.append("&");
} else {
params.append("?");
}
if(userOptionsCBox[i].equalsIgnoreCase("useDB")) {
// append() argument is value of the value attribute belonging to the input attribute
params.append("useDB=1");
} else if(userOptionsCBox[i].equalsIgnoreCase("sendEmail")) {
params.append("sendEmail=1");
}
isFirst = false;
}
queryStringParams = params.toString();
}
if(userChoiceSelect.equals("1")) {
response.sendRedirect("ListCities.html" + queryStringParams);
} else if(userChoiceSelect.equals("2")) {
response.sendRedirect("AddCity.html" + queryStringParams);
} else if(userChoiceSelect.equals("3")) {
response.sendRedirect("DeleteCity.html" + queryStringParams);
} else {
response.sendRedirect("index.html");
}
}
}
index.html:
<html>
<head>
<title>Welcome to the City Manager</title>
</head>
</html>
<body>
<form id="form1" method="post"
action="/CityManagerWeb/mainmenuresponder.do">
<table style="width:100%">
<tr>
<td style="width:100%" align="center">
<h1>Welcome to the World City Manager</h1>
</td>
</tr>
<tr>
<td>
<h3>What would you like to do today?</h3>
</td>
</tr>
<tr>
<td>
<select id="menuChoice" name="menuChoice">
<option id="1" value="1">
List Cities
</option>
<option id="2" value="2">
Add a new city
</option>
<option id="3" value="3">
Delete a city
</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="adminoptions" id="optionDatabase" value="useDB" />Use Database<br>
<input type="checkbox" name="adminoptions" id="optionEmail" value="sendEmail" />Send Confirmation<br>
</td>
</tr>
<tr>
<td>
<input name="chooser" type="submit" value="Choose" />
</td>
</tr>
</table>
</form>
</body>
ListCities.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Listing Cities</title>
</head>
<body>
<table style="width:450px;">
<tr>
<td style="width:150px;"><b>COUNTRY</b></td>
<td style="width:300px;"><b>CITY</b></td>
</tr>
<tr>
<td>Russia</td>
<td>Moscow</td>
</tr>
<tr>
<td>England</td>
<td>London</td>
</tr>
<tr>
<td>United States</td>
<td>Washington, D.C.</td>
</tr>
</table>
</body>
</html>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>CityManagerWebStarter</display-name>
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks for any suggestions/help.
A fairly common problem I'm seeing these days is that people are using the latest IDE tooling that generates their web projects using the Servlet 3.0 specification i.e. the files generated use the new #WebServlet, #WebFilter etc. annotations way of doing things against the traditional deployment descriptor web.xml. But, they follow these old Servlet 2.x tutorials online and end up configuring the same servlet twice; once with the annotations and once again in the web.xml. This would lead to your server responding in undefined ways and must be avoided.
So, you can safely get rid of the following from your web.xml:
<servlet>
<servlet-name>citymanagerwebstarter</servlet-name>
<servlet-class>company.citymanagerweb.servlets</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>citymanagerwebstarter</servlet-name>
<url-pattern>/citymanagerwebstarter/mainmenuresponder.do</url-pattern>
</servlet-mapping>
The next issue is that your web application's context root is never a part of your servlet or filter's url-pattern. So, your annotation should be like
#WebServlet("/mainmenuresponder.do")
public class MainMenuResponder extends HttpServlet {
Lastly, though it works as is, your form's action attribute shouldn't hard code the context root like that. I suggest you use a relative URL there as well.
<form id="form1" method="post" action="mainmenuresponder.do">
Notice, that unlike the servlets, you can't put a leading / in the action here.
If citymanagerwebstarter is the content root. It should not be part of the url parttern in web.xml and #WebServlet annotation.
I'm starting off in NetBeans, and implementing a form which, when you press the "submit" button, performs validation and tells you if the data entered is correct. I haven't gotten to the validation part yet, for the moment all I'm trying to do is, when the "submit" button is clicked, a message pops up. I'm having trouble here, I have a feeling its a quick simple fix but I'm not finding anything on message boards or documentation.
EDIT - Thanks guys! was missing the "form" tag. I figured it would be simple, thanks again for your help everyone!
Here's my index.html file:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Client Information</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div><h1>Client Information</h1><table border="1">
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="FirstName" value="" size="50" /></td>
<td>Surname</td>
<td><input type="text" name="Surname" value="" size="50"/></td>
</tr>
<tr>
<td>Age</td>
<td><input type="number" name="Age" value="" min="0" max="120"/></td>
<td>Gender</td>
<td><input type="text" name="Gender" value="" size="1" maxlength="1"/></td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" name="validation" />
</div>
</body>
</html>
And here is the ClientInformationServlet.java file, most important is the processRequest method, and if (request.getParameter("validation")!= null) line is where I am trying to have the action take place.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package clientInformation;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author nicolasdubus
*/
#WebServlet(name = "ClientInformationServlet", urlPatterns = {"/clientinformationservlet"})
public class ClientInformationServlet extends HttpServlet {
/*
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Client Information</title>");
out.println("</head>");
out.println("<body>");
String sfirst = request.getParameter("FirstName");
String ssecond = request.getParameter("SurName");
String sAge = request.getParameter("Age");
String sGender = request.getParameter("Gender");
try {
Integer age = Integer.parseInt(sAge);
if (request.getParameter("validation") != null) {
System.out.println("<h1>Client information is valid</h1>");
out.println("<h1>Client</h1>");
System.exit(0);
}
} catch (IllegalArgumentException e) {
out.println("<h1>Client information is invalid, please verify entries</h1>");
}
out.println("<body>");
out.println("</html");
/* */
out.close();
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The HTML specification states
The elements used to create controls generally appear inside a FORM
element, but may also appear outside of a FORM element declaration
when they are used to build user interfaces. This is discussed in the
section on intrinsic events. Note that controls outside a form cannot
be successful controls.
A <input> element for submit is a control. Therefore, if it appears outside a <form>, as you currently have it, clicking it won't do anything.
Nest your <input> elements (and whatever other display elements) within a <form> which specifies the action and method to use to submit your data.
You should add
<body><form action="/clientinformationservlet" method="POST">
....
</form></body>
inside the body.
If you want to submit then you should have a <form> in your htmml
e.g.
<form name="input" action="/clientinformationservlet" method="POST">
// your inputs
</form>
I am trying to enter a new user into my database with servlets.
I have a problem when I click submit button i registraion form. I get "The requested resource is not available." error. I cant figure it out.
Can you guys help me?
register.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sign Up</title>
</head>
<body>
<h1>Enter your information</h1>
<form method = "POST" action="RegisterServlet">
Username <br/>
<input type="text" name="username"/><br/>
Password <br/>
<input type="password" name="password"/><br/>
Email <br/>
<input type="text" name="email"/><br/>
First name <br/>
<input type="text" name="fname"/><br/>
Last name <br/>
<input type="text" name="lname"/><br/>
<input type="submit" value="Confirm" />
</form>
</body>
RegisterServlet doPost() method
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
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(name = "RegisterServlet", urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String admin = "no";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mobmelbaza", "root", "");
String query = "insert into korisnici(user, pass, email, ime, prezime, admin)"
+ "values ('" + username + "','" + password + "','" + email + "','" + fname + "','" + lname + "', '" + admin + "')";
Statement st = con.createStatement();
boolean done = st.execute(query);
if (done == true) {
out.print("Sign Up sucessfull");
} else {
out.print("Failed");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
As you said you are using annotation better remove the mapping from the web.xml
You can either have annotation based mapping like
#WebServlet(name = "RegisterServlet", urlPatterns = {"/RegisterServlet"})
or
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
you cannot have both at once
I'm trying to write a servlet using generated HTML code, rather then printing out static HTMLs.
I'm using Eclipse-EE Europa and Tomcat 6.
I tried to use the flowing tips from HERE
But instead of printing the desired attribute It seems that the jsp ignoring the attribute or the attribute is empty.
Here is the servlet:
package com.serv.pac;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
/**
* Servlet implementation class for Servlet: testServlet
*
*/
public class testServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#HttpServlet()
*/
public testServlet() {
super();
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "doGet response";
request.setAttribute("message", message);
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
PrintWriter out = response.getWriter();
out.println("the servlet");
}
/* (non-Java-doc)
* #see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("first servlet");
}
}
Here is the JSP
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
And the following is the :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>servlet1_test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>index1.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>testServlet</display-name>
<servlet-name>testServlet</servlet-name>
<servlet-class>com.serv.pac.testServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>testServlet</servlet-name>
<url-pattern>/testServlet</url-pattern>
</servlet-mapping>
</web-app>
And that is what I'm getting in the browser:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: </p>
</body>
</html>
As one may see there is nothing after the "Message" in the html body, as if the message attribute is empty.
Thank You
The only way I can see this happenning is you aren't actually accessing your Servlet.
You've declared a <welcome-file>
<welcome-file>index1.jsp</welcome-file>
So if you try to hit
localhost:8080/YourContextPath
the default Servlet will render and send you that jsp with a missing message attribute.
If you want to hit your actual Servlet, you need to use
localhost:8080/YourContextPath/testServlet
Note that you need to change
request.getRequestDispatcher("/testServlet/WEB-INF/index1.jsp").forward(request, response);
to
request.getRequestDispatcher("/WEB-INF/index1.jsp").forward(request, response);
and move your file under WEB-INF.