I want to create a servlet project.
My Java class is called AzpanaServlet.java, and it contains an inner class. (When I compile it, I have 2 class files).
My project is a simple application that receives a string input and does some stuff with it (not relevant).
When I press on the "submit" button I receive the following error:
HTTP Status 404 - /AzpanaServlet
Type Status report
Message /AzpanaServlet
Description The requested resource (/AzpanaServlet) is not available.
Apache Tomcat/6.0.18
Please help me if you can, I can't solve this much time.
this is my Java code:
public class AzpanaServlet extends HttpServlet {
//
//Some functions
//
//Inner class: public class oneChar{...}
//
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
/*
* Set the content type(MIME Type) of the response.
*/
response.setContentType("text/html");
String str = "";
PrintWriter out = response.getWriter();
ArrayList<Integer> list = new ArrayList<Integer>();
try {
list = mainmanu(name); //not relevant function.
} catch (Exception e) {
str = e.toString();
e.printStackTrace();
}
/*
* Write the HTML to the response
*/
out.println("<html>");
out.println("<head>");
out.println("<title> this is your answers</title>");
out.println("</head>");
out.println("<body>");
if(str != ""){
out.println(str);
}
else{
for(int i = 0;i<=40;i++){
out.println(list.get(i));
out.println("<br>");
}
}
out.println("<a href='form.html'>"+"Click here to go back to input page "+"</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy() {
}
}
My web.xml code:
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>AzpanaServlet</servlet-name>
<servlet-class>com.example.AzpanaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AzpanaServlet</servlet-name>
<url-pattern>/AzpanaServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/form.html</welcome-file>
</welcome-file-list>
</web-app>
My form.html code:
<html>
<head>
<title>Zeev's Project</title>
</head>
<body>
<h1>Just Enter String</h1>
<form method="POST" action="AzpanaServlet">
<label for="name">Enter String</label>
<input type="text" id="name" name="name"/><br><br>
<input type="submit" value="Submit Form"/>
<input type="reset" value="Reset Form"/>
</form>
</body>
</html>
The hierarchy of the Folder is following:
ROOT[
WEB-INF[
web.xml
classes[
com[
example[
AzpanaServlet.class
AzpanaServlet$oneChar.class
]
]
]
lib[
AzpanaServlet.java
]
]
META-INF[
MANIFEST.MF
]
form.html
]
Copied your exact code and just commented out the Servlet code to be
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* Get the value of form parameter
*/
String name = request.getParameter("name");
System.out.println("Parameter name : "+name);
Works like a charm.
In my server console
Parameter name : helloo
There is no problem with your configuration. You might want to clean your browser cache and try again.
The problem may be that you are using IDE to run the Tomcat Server and deployed to the root application context. Try to use some app context for your application in deployment. For example /myapp.
Have a look at your IDE console or your tomcat log, did your web application ever started successfully?
It might didn't start for some reason.
Related
I've tried all methods available on StackOverflow and the internet, but nothing seems to workout as intended, below's a list of what I've tried doing:
All declared methods in my java files are protected named doPost()
I tried using sendRedirect() method instead of RequestDispatcher()
I also tried using another method and calling it in doPost()
I also tried creating another web project in Eclipse, but that too didn't work
Any help would be appreciated, thanks!
Here is my login.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="auth" method="post">
<table>
<tr>
<td>Email ID:</td>
<td><input type="email" name="userEmail"></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="userPassword"></td>
</tr>
<tr>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
authenticate.java
package newAuthentication;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class authenticate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userEmail = request.getParameter("userEmail");
String userPassword = request.getParameter("userPassword");
if (validateUser.checkUser(userEmail, userPassword))
{
HttpSession session = request.getSession();
session.setAttribute("userEmail", userEmail);
RequestDispatcher dispatch = request.getRequestDispatcher("home");
dispatch.forward(request, response);
}
else
{
out.println("Incorrect authentication credentials, please try again!");
RequestDispatcher dispatch = request.getRequestDispatcher("login.html");
dispatch.include(request, response);
}
}
}
validateUser.java
package newAuthentication;
import java.sql.*;
public class validateUser
{
public static boolean checkUser(String userEmail, String userPassword)
{
boolean state = false;
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/wad","root","root");
PreparedStatement fetchData = connect.prepareStatement("select * from studentData where email = ? and password = ?");
fetchData.setString(1, userEmail);
fetchData.setString(2, userPassword);
ResultSet data = fetchData.executeQuery();
state = data.next();
}
catch (Exception err)
{
err.printStackTrace();
}
return state;
}
}
home.java
package newAuthentication;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class home extends HttpServlet
{
protected void doPost(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException
{
doGet(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String userEmail = (String)session.getAttribute("userEmail");
out.println("Welcome user " + userEmail);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>newAuth</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>newAuthentication.authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/auth</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Home</servlet-name>
<servlet-class>newAuthentication.home</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Home</servlet-name>
<url-pattern>/home</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>
Why you have this problem in the first place:
This chunk of code is MUCH TOO LONG to try all in one step. Especially if you don't have experience working with servlets. If you are not yet sure if your servlets and basic mappings work, start small - a single servlet, a single GET mapping - that you can try in the browser, without any HTML. Just two files in the entire project: web.xml and MyServlet.java - and just leave the doGet method empty.
Right now, your code is so long, that you simply cannot guess the problem once you hit it - there's too many places to verify!
The magic formula is: "try just one thing at a time".
Solution:
Remove the doGet(request, response) call in your doPost method.
You don not provide your own doGet method, so it defaults to what's in the superclass. It so happens, that the default doGet method throws an exception stating that the GET method is not supported. Since you call it from your doPost, the propagating exception makes container think (rightly so) that it's your doPost that is throwing, and so that it is POST that is unsupported.
Also, the call makes no sense.
BTW: Notice that you would find this error in 5 seconds, if you first tried with the suggested two class approach: you would only have this one thing to verify.
sorry for silly mistakes I have made. I am following example from "java for web with servlets, jsp and ejb" book
So I have the following problem. I have a servlet. The function of the servlet is very simple - just retrieve request parameters and print them on console.The servlet is called from inside index.html file.
The code for the index.html file is
<html>
<head>
<title> sending a request</title>
</head>
<body>
<form action=RequestDemoServlet method="POST">
<br> <br>
Author: <input type="TEXT" name="author">
<input type="SUBMIT" name="submit">
<input type="RESET" value="reset">
</form>
</body>
</html>
The code for the servlet is following
import javax.servlet.*;
import java.util.Enumeration;
import java.io.IOException;
public class RequestDemoServlet implements Servlet
{
public void init(ServletConfig config)
throws ServletException
{}
public void destroy()
{}
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException
{
System.out.println("Server port: "+request.getServerPort());
System.out.println("Server name: "+request.getServerName());
System.out.println("Protocol: "+request.getProtocol());
System.out.println("Char encoding: "+
request.getCharacterEncoding());
System.out.println("Constent length: "+
request.getContentLength());
System.out.println("Remote address: "+
request.getRemoteAddr());
System.out.println("remote Host: "+request.getRemoteHost());
Enumeration parameters=request.getParameterNames();
while(parameters.hasMoreElements())
{
String parameterName=(String)parameters.nextElement();
System.out.println("Parameter name: "+parameterName);
System.out.println("Parameter value: "+
request.getParameter(parameterName));
}
}
public String getServletInfo()
{
return null;
}
public ServletConfig getServletConfig()
{
return null;
}
}
I compiled the RequestDemoSevlet.java with javac as in
javac -cp $CATALINA_HOME/lib/servlet-api.jar -d ./classes RequestDemoServelt.java
The .class file for the servlet is put into the classes directory of my application.
Then I edited web.xml file
<?xml version ="1.0" encoding ="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns.xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:/java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Chapter 2</display-name>
<description> Apress</description>
<servlet>
<servlet-name>RequestDemo</servlet-name>
<servlet-class>RequestDemoServlet</servlet-class>
</servlet>
</web-app>
I suppose that I made a mistake either in web.xml or index.html files. Can somebody help me with the problem?
I was trying this small HttpSession program as a demo for my project.
This program just checks whether the user is new, if it is then displays a form, if the user is not new, then it displays the name of the user, the color he selected and the total no. of visits.
When i run my program, it works only for the first time. That means when i run another instance of my program, it displays a blank web page.
What is wrong in the code that is causing this problem???
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Integer hitCount;
HttpSession s = request.getSession(true);
if(s.isNew()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<form method=get action=SessionServlet>");
out.println("<h3>Please sleect a Color</h3>");
out.println("<input type=radio name=color />Red");
out.println("<br /><input type=radio name=color />Green");
out.println("<br /><input type=text name=txtName />");
out.println("<br /><input type=submit name=Submit value=Submit />");
out.println("</form>");
out.println("</body>");
out.println("</html>");
} else if(!s.isNew()){
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
hitCount = new Integer(1);
s.setAttribute("Name", name);
s.setAttribute("color", color);
s.setAttribute("HitCount", hitCount);
if((name != null) && (color != null)) {
out.println("Name: " + s.getAttribute("Name"));
hitCount = (Integer)s.getAttribute("HitCount");
hitCount = hitCount++;
s.setAttribute("HitCount", hitCount);
//out.println("<body bgcolor=" + s.getAttribute("color") + ">");
out.println("you selected" + s.getAttribute("color"));
out.println("Total visits=====>" + s.getAttribute("HitCount"));
}
}
}
}
}
The second time you run this code, the session already exists, so the program goes through else branch- but the "old" request object (from the first run of the application) and its parameters (color and name) are already gone at that time. Request is destroyed by container right after the response from the first application run was sent back to the client.
In your code
String name = (String) request.getParameter("txtName");
String color = (String) request.getParameter("color");
you are trying to get non existing parameters. Parameters txtName and color do not exist in request anymore. Therefore they are null and the next condition
if((name != null) && (color != null))
is always false. And nothing is written into out Writer.
What you should do in order to make this work is to read the parameters from the session object (this is what the sessions are made for anyway) where you should put them in the first application run. This code won't work. And your hitCount will always be 1 (please see HttpSessionListener interface). This code is wrong on so many levels- you should re-write everything after the else if branch which should be only else anyway.
TLDR:
Your question was why it is not working: the answer is - you are reading non existing parameters. You have to put the parameters into session object in the first application run and read them from it.
edit after your question from December 31st:
Here is what I would do. Assume following directory structure of this simple project named SessionServlet. This structure will be used in whole answer. To simplify things I won't list every directory, you surely get the idea from this. This is not the real-life example of directory structure, it is simplified for the purposes of this tutorial example.
<path-to-project>/SessionServlet/src/com/example/session
<path-to-project>/SessionServlet/WebContent/META-INF
<path-to-project>/SessionServlet/WebContent/WEB-INF
Create an html file, for example start.html. It should contain the input fields which values you need to store in the session. The file goes here
<path-to-project>/SessionServlet/WebContent/start.html
Its contents
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start page</title>
</head>
<body>
<form method="get" action="MySessionServlet">
<h3>Please select a Color</h3>
<input type="radio" name="color" value="red" />Red<br>
<input type="radio" name="color" value="green" />Green<br>
<input type="text" name="txtName" /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
In your servlet example you forgot the value attribute in radiobutton input, therefore whichever radiobutton you would check, the value would be on, not the color name.
Next you have to create the servlet class SessionServlet.java, which will be slightly different from your original idea. It goes here:
<path-to-project>/SessionServlet/src/com/example/session/SessionServlet.java
Its contents
package com.example.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
private static final long serialVersionUID = -3808675281434686897L;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String requestColor = null;
String requestTxtName = null;
PrintWriter out = response.getWriter();
MySessionListener listener = new MySessionListener();
HttpSession session = request.getSession();
if (session.isNew()) {
//these are request parameters sent from html form
requestColor = request.getParameter("color");
requestTxtName = request.getParameter("txtName");
//save the attributes in session in order to use them later
session.setAttribute("sessionColor", requestColor);
session.setAttribute("sessionTxtName", requestTxtName);
}
else {
//get the previously stored attributes from session
String color = (String) session.getAttribute("sessionColor");
String name = (String) session.getAttribute("sessionTxtName");
//session info
out.println("session already existed");
if (color != null && name != null) {
out.println("Name: " + name);
out.println("Color: " + color);
out.println("Session count: " + listener.getSessionCount());
}
}
}
}
I think the servlet's code is pretty much self-explanatory. However, if you have any particular questions, please ask.
In order to count the active sessions, you need to create a SessionListener class and count the sessions. For the purposes of this example I put the class into the same directory as servlet class. Please do not do this in real project. You'd create a big mess. This is only simplified Java Enterprise Hello world example. The file is here
<path-to-project>/SessionServlet/src/com/example/session/MySessionListener.java
Its contents are
package com.example.session;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener {
private static int sessionCount;
#Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Creating session with id: " + se.getSession().getId());
sessionCount++;
}
#Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Destroying session id: " + se.getSession().getId());
sessionCount--;
}
public int getSessionCount() {
return sessionCount;
}
}
The listener class for counting active sessions must implement HttpSessionListener interface. We call the method getSessionCount() in SessionServlet class as you already noticed.
The last thing to do is to create a deployment descriptor xml in order to tell the container what to do with those classes we created.
the file must be named web.xml and it must be placed in WEB-INF directory.
<path-to-project>/SessionServlet/WebContent/WEB-INF/web.xml
Its contents are
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID"
version="3.1">
<display-name>SessionServlet</display-name>
<welcome-file-list>
<welcome-file>start.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>my Session Servlet</servlet-name>
<servlet-class>com.example.session.SessionServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>my Session Servlet</servlet-name>
<url-pattern>/MySessionServlet</url-pattern>
</servlet-mapping>
<!-- set session timeout to 30 minutes -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- register listener class -->
<listener>
<listener-class>com.example.session.MySessionListener</listener-class>
</listener>
</web-app>
And that's all. Lastly my two cents- you should first acquaint with Standard Edition Java. This is an example from Enterprise world which is way over your head yet. There are plenty of tutorials on the web. Give it some time, you won't regret it.
Regarding the servlets- you should (must) first understand the basic concepts of request, response, session, client and container (who is who, the lifecycle, managing, etc.) before you start making real projects. The best book I've seen about this is Head First - Servlets and JSP, which should be a starting point in understanding this topic.
You set response.setContentType("text/html;charset=UTF-8") ....
But in your section if(!s.isNew()){.... the output is not HTML, but is plain text. ("Name:", etc...)
My bet is that the content is there, but your browser is not displaying it.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling servlet from HTML form, but servlet is never invoked
I'm calling servlet from html form, servlet takes the form data and it will insert that form data into database.But when i click the submit button error page is coming. Please help whats wrong in my servlet code.
My html code:
<html>
<head>
<title> Sign Up </title>
</head>
<body>
<form action="servlet/Loginservlet" method="post" >
<font size='5'>Create your Account:</font><br/><br>
<label for="username" accesskey="u" style="padding-left:3px;">User Name: </label>
<input type="text" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;margin-top:6px;padding-right:85px;" id="username" name="username" tabindex="1"><br/><br>
<label for="password" accesskey="p" style="padding-left:4px;">Password: </label>
<input type="password" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;padding-right:85px;" id="password" name="pasword" tabindex="2"><br/><br>
<input type="submit" value="Submit" style="margin-left:164px;"/>
<input type="reset" value="Reset" style="margin-left:17px;"/>
</form>
</body>
</html>
My servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Loginservlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
System.out.println("login servlet");
String connectionURL = "jdbc:mysql://localhost:3306/mysql";
Connection connection = null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username = req.getParameter("username");
String password = req.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "root");
String sql = "insert into signup values (?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
int numRowsChanged = pst.executeUpdate();
out.println(" Data has been submitted ");
pst.close();
} catch (ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
} catch (SQLException e) {
out.println("SQLException caught: " + e.getMessage());
} catch (Exception e) {
out.println(e);
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException ignored) {
out.println(ignored);
}
}
}
}
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
I think, mistake is here: <form action="servlet/Loginservlet"
Try this <form action="/<your-app-name>/login"
since in form action you have given servlet/Loginservlet . you should map same in web.xml like
<url-pattern>/servlet/Loginservlet</url-pattern>
or change in the form like
action='login'
you can do any one of above.
try this
<form action="login" method="post" >
you servlet url is
<url-pattern>/login</url-pattern>
When you run your web application for local host then the url like
localhost:8080/test
then the test is the name of your application name which contain your web application into the web dir. Now suppose you create the index file then it will run index file from this only and another page url like
localhost:8080/test/page1.html
now from page1.html you start your login page then the link looks like for servlet is
localhost:8080/test/login
as define the url pattern for specific servlet that url you have to set for calling the specific servlet like above. this url will hide the actual servlet for the client you can set anything in url pattern
This question already has answers here:
HTTP Status 405 - HTTP method is not supported by this URL
(2 answers)
Closed 1 year ago.
I am having trouble getting the page to work. I have my form method to post and my servlet implements doPost(). However, it keeps showing me that I am not supporting the POST method.
I am just trying to do a simple website and insert values into my MySQL DB.
*type Status report
message HTTP method POST is not supported by this URL
description The specified HTTP method is not allowed for the requested resource (HTTP method POST is not supported by this URL).*
the static page:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHTML Mobile Profile Document</title>
<!--
Change href="style.css" below to the file name and
relative path or URL of your external style sheet.
-->
<link rel="stylesheet" href="index.css" type="text/css"/>
<!--
<style> document-wide styles would go here </style>
-->
</head>
<body>
<h1> Register Here </h1>
<form action="regSuccess.do" method = "POST">
UserName: <input type="text" name="txtregUsername" size="15" maxlength="15">
<br/>
Password: <input type="password" name="txtregPassword" size="15"
maxlength="15"><br/>
Name: <input type="text" name="txtregName" size="20" maxlength="30"><br/>
Email: <input type="text" name="txtregEmail" size="20" maxlength="30">
<br/><br/>
<input type="submit" name="btnRegister" value="Register Me"/>
</form>
</body>
</html>
the servlet:
package core;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class handlingReg extends HttpServlet {
//database parameters
private static final String db_server = "localhost/";
private static final String db_name ="bus_guide";
private Connection con = null;
//init of connection to dabatase
public void init(ServletConfig config) throws ServletException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch (Exception e) {
System.out.println("Exception in init(): unable to load JDBC DriverA");
}
try {
con = DriverManager.getConnection("jdbc:mysql://"+ db_server + db_name , "root" , "");
System.out.println("conn: "+con);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
//end init()
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response handling
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//handling request
String enteredUsername = request.getParameter("txtregUsername");
String enteredPw = request.getParameter("txtregPassword");
String enteredName = request.getParameter("txtregName");
String enteredEmail = request.getParameter("txtregEmail");
//inserting values into database
try {
Statement stmnt = con.createStatement();
stmnt.executeUpdate("INSERT INTO regUsers VALUES('"+enteredUsername+"','"+enteredPw+"','"+enteredName+"','"+enteredEmail+"')");
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
//output html out.println("");
out.println("<?xml version = \"1.0\" encoding =\"utf-8\"?>");
out.println("<!DOCTYPE html PUBLIC \"-//WAPFORUM/DTD XHTML Mobile 1.0//EN\"");
out.println(" \"http://www.wapforum.org/DTD/xhtml-mobile10.dtd\">");
out.println("<html xmlns=\"http://www.w3.org/1000/xhtml\">");
out.println("<head>");
out.println("<title></title>");
out.println("</head>");
out.println("<body>");
out.println("Register Success!");
out.println("<a href = \"index.xhtml\"> Click here to go back to main page.
</a>");
out.println("</body>");
out.println("</html>");
}
}
web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<!--Self declared servlet mapping starts here-->
<servlet>
<servlet-name>handleRegister</servlet-name>
<servlet-class>core.handlingReg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>handleRegister</servlet-name>
<url-pattern>/regSuccess.do</url-pattern>
</servlet-mapping>
<!--Self declared servlet mapping ends here-->
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
<mime-mapping>
<extension>xhtml</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jad</extension>
<mime-type>text/vnd.sun.j2me.app-descriptor</mime-type>
</mime-mapping>
<mime-mapping>
<extension>jar</extension>
<mime-type>application/java-archive</mime-type>
</mime-mapping>
</web-app>
edit:removed doGet(request,response);
It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.
if you are using tomcat you may try this
<servlet-mapping>
<http-method>POST</http-method>
</servlet-mapping>
in addition to <servlet-name> and <url-mapping>
It says "POST not supported", so the request is not calling your servlet. If I were you, I will issue a GET (e.g. access using a browser) to the exact URL you are issuing your POST request, and see what you get. I bet you'll see something unexpected.
This happened to me when:
Even with my servlet having only the method "doPost"
And the form method="POST"
I tried to access the action using the URL directly, without using the form submitt. Since the default method for the URL is the doGet method, when you don't use the form submit, you'll see # your console the http 405 error.
Solution: Use only the form button you mapped to your servlet action.
If you're still facing the issue even after replacing doGet() with doPost() and changing the form method="post". Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!
For best practices, please follow this link.
https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html