Servlet does not print messages on console - java

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?

Related

How to fix Error 404: The origin server did not find a current representation for the target resource

So I'm new to servlets and jsp, and was following along to the Hello World post-process example from https://stackoverflow.com/tags/servlets/info. When I tried to run it using Tomcat v9.0 in Eclipse, I get
After doing some additional research, and poking around, I haven't found a working solution or an explanation of what is happening. I had basically copied the code from the example, so I'm pretty confused as to why it isn't working. I also don't really have the proficiency yet to figure out exactly what is wrong, so any help would be great. My only hunch so far is that I probably messed up the directories or something. Here is a picture:
The only discrepancy I could find was where my HelloServlet.class was located, which was in
apache-tomcat-9.0.19/webapps/hello/build/classes/com/example/controller/HelloServlet.class
instead of
/WEB-INF/classes/com/example/controller/HelloServlet.class
as stated in the example. I assumed this was because Eclipse, by default, had compiled the class file where it is now, but just to be sure, I copied the class folder into WEB-INF so it would match the example, but it still didn't work. So that is where I'm stuck. If anyone could point out my mistake or even help at all, that would be very much appreciated. I have included my hello.jsp, web.xml, and HelloServlet.java files below just in case there's any issues with them.
hello.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Servlet Hello World</title>
<style>.error { color: red; } .success { color: green; }</style>
</head>
<body>
<form action="hello" method="post">
<h1>Hello</h1>
<p>
<label for="name">What's your name?</label>
<input id="name" name="name" value="${fn:escapeXml(param.name)}">
<span class="error">${messages.name}</span>
</p>
<p>
<label for="age">What's your age?</label>
<input id="age" name="age" value="${fn:escapeXml(param.age)}">
<span class="error">${messages.age}</span>
</p>
<p>
<input type="submit">
<span class="success">${messages.success}</span>
</p>
</form>
</body>
</html>
web.xml
<web-app
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"
metadata-complete="true">
</web-app>
HelloServlet.java
package com.example.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
#WebServlet("/hello")
public class HelloServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Preprocess request: we actually don't need to do any business stuff, so just display JSP.
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Postprocess request: gather and validate submitted data and display the result in the same JSP.
// Prepare messages.
Map<String, String> messages = new HashMap<String, String>();
request.setAttribute("messages", messages);
// Get and validate name.
String name = request.getParameter("name");
if (name == null || name.trim().isEmpty()) {
messages.put("name", "Please enter name");
} else if (!name.matches("\\p{Alnum}+")) {
messages.put("name", "Please enter alphanumeric characters only");
}
// Get and validate age.
String age = request.getParameter("age");
if (age == null || age.trim().isEmpty()) {
messages.put("age", "Please enter age");
} else if (!age.matches("\\d+")) {
messages.put("age", "Please enter digits only");
}
// No validation errors? Do the business job!
if (messages.isEmpty()) {
messages.put("success", String.format("Hello, your name is %s and your age is %s!", name, age));
}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
You need to allow cross origin
private void setAccessControlHeaders(HttpServletResponse resp) {
resp.setHeader("Access-Control-Allow-Origin", "http://localhost:9000");
resp.setHeader("Access-Control-Allow-Methods", "GET");
}

JSP Form Not Connecting with Servlet 404-Error

I'm having a little issue connecting with my servlet so that I can pass some data to a mysql database. I've read a bunch of the threads here, but have had no luck with suggestions to other members.
I have a jsp page named "insertData.jsp" On that page there is a form where the action points to a servlet named "UpdateData". When I click submit on the web page, I get a 404 error stating that the requested resource is not available. I have also updated my web xml file to try to point to the right direction.
So here's my folder setup:
The UpdateData.java is in the controller package of the source packages folder. The name of the project is "RukertContainerTracker".
Here's my jsp page:
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data Into Container Records</h1>
<H1>The Rukert Terminals Container Tracker </H1>
<form name="Insert Record" action="/UpdateData" method="Post">
Container Number: <input type="text" name="containerNumber"> <br />
Full Out: <input type="date" name="fullOut" /> <br/>
Empty In: <input type="date" name="emptyIn" /> <br/>
Empty Out <input type="date" name="emptyOut" /> <br/>
Full In: <input type="date" name="fullIn" /> <br/>
Comments: <input type="text" name="comments" /> <br/>
<input type="submit" value="Submit" />
</form>
<div>
<a href="javascript:history.back();">
<span class="categoryLabelText">HOME</span>
</a>
</div>
</body>
</html>
My servlet:
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateData extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//Get container data from the JSP page
String container=request.getParameter("containerNumber");
String fullOutDate=request.getParameter("fullOut");
String emptyInDate=request.getParameter("emptyIn");
String emptyOutDate=request.getParameter("emptyOut");
String fullInDate=request.getParameter("fullIn");
String comments=request.getParameter("comments");
//Print the above got values in console
System.out.println("The username is" +container);
System.out.println("\nand the password is" +fullOutDate);
String connectionparams="jdbc:mysql://localhost:3306/rukerttracker";
String db="rukerttracker";
String uname="root";
String psword="Colorado1982";
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("com.mysql.jdbc.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection
(connectionparams, uname, psword);
//Add the data into the database
String sql = "insert into containerinventory values (?,?,?,?,?,?)";
try (PreparedStatement prep = connection.prepareStatement(sql)) {
prep.setString(1, container);
prep.setString(2, fullOutDate);
prep.setString(3, emptyInDate);
prep.setString(4, emptyOutDate);
prep.setString(5, fullInDate);
prep.setString(6, comments);
prep.executeUpdate();
}
}catch(Exception E){
System.out.println("The error is=="+E.getMessage());
}
finally{
connection.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/insertData")) {
// TODO: Implement category request
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And finally my web.xml page:
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/chooseLanguage</url-pattern>
<url-pattern>/viewTracker</url-pattern>
<url-pattern>/editTracker</url-pattern>
<url-pattern>/addToCart</url-pattern>
<url-pattern>/viewCompany</url-pattern>
<url-pattern>/category</url-pattern>
<url-pattern>/updateCart</url-pattern>
<url-pattern>/purchase</url-pattern>
<url-pattern>/viewCart</url-pattern>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateData</servlet-name>
<servlet-class>controller.UpdateData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
I have two servlets, I don't know if this matters, but I couldn't get the application to work in the controller servlet, so I created the Update Data servlet.
Any help as to why I keep getting this 404 error would be greatly, greatly appreciated. Thanks for taking the time to look at this.
I think in form you are using POST method and your servlet does not have post method. please check it.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{...}
not available.

Using Tomcat 7 on Ubuntu 12.04 server and Eclipse EE: servlet won't run a class file

Clicking the submit button on my form produces a save dialog box (asking me to save the .class file that is supposed to run as called from POST) instead of a new page with the form partially filled out.
As stated above I am trying to use Tomcat 7.0.40 with my web application called Demonstration. I have been programming the quite simple pages in Eclipse then compiling them and setting up my own .war file for Tomcat. This didn't work after many, many tries so I let Eclipse do the construction of the .war file for me. Still didn't work.
Here is what I think are the relevant pieces of code.
The first file that runs is this HTML stored as webapps\Demonstration\index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="SurveyMark.css">
<meta charset="ISO-8859-1">
<title>SurveyMark - Input Job</title>
</head>
<body>
<form id="job_input_form" action="JobMade" method=POST>
<h1><img id="logo" alt="TJH Logo" src="logo_small.jpg" align="middle"><b> -
SurveyMark - Input Job INDEX.HTML</b></h1>
<div id="job_div" style="width:250px;float:left">
<h3>Job Details</h3>
<label for="job_number">Job Number</label>
<input type="text" name="job_number" id="job_number">
<label for="addendum">Addendum</label>
<input type="text" name="addendum" id="addendum">
<label for="development_name">Development Name</label>
<input type="text" name="development_name" id="development_name">
<label for="job_type">Job Type</label>
<input type="text" name="job_type" id="job_type">
<label for="date_recieved">Date Recieved</label>
<input type="text" name="date_recieved" id="date_recieved">
</div>
<div id="job_location_div" style="width:250px;float:left">
<h3>Job Location</h3>
<label for="unit_number">Unit Number</label>
<input type="text" name="unit_number" id="unit_number">
<div id="legal_street_number_div" style="width:120px;float:left">
........
........Lots more fields all on the same page, displaying properly
</div>
<input type="submit" value="Add Job">
</form>
</body>
</html>
Which attempts to POST's to the following file \webapps\Demonstration\WEB-INF\classes\Demonstration\JobMade.class
(That compiles from this JobMade.java file)
package Demonstration;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
#WebServlet("/JobMade")
public class JobMade extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//String title = "Job Data that has Been Entered";
out.println("<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<link rel=\"stylesheet\" type=\"text/css\" href=\"SurveyMark.css\">" +
"<meta charset=\"ISO-8859-1\">" +
"<title>SurveyMark - Input Job JOBMADE FILE</title>" +
"</head>" +
"<body>" +
"<form id=\"job_input_form\" action=\"AddedJob.html\" method=\"post\">" +
"<input type=\"submit\" value=\"Add Job\">" +
"<h1><img id=\"logo\" alt=\"TJH Logo\" src=\"logo_small.jpg\" align=\"middle\"> - " +
"SurveyMark - Added Job as Follows</h1>");
#SuppressWarnings("rawtypes")
Enumeration paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("<I>No Value</I>");
else
out.print(paramValue);
} else {
out.println("<UL>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
I have lloked at the catalina log files and can't find anything untoward but if there is something specific that would help I am all ears.
Here is the brief yet important web.xml file stored under the WEB-INF directory.
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Demonstration</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-list>
</web-app>
Thank you in advance for your help.
You did not map that servlet anywhere. Neither in the web.xml file, nor using an annotation.

Simple servlet project (HTTP Status 404 error)

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.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet [duplicate]

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

Categories