“HTTP Status 404 The requested resource is not available” - java

I'm newbie to servlet programming. I have checked various other links about the Http 404 error but nothing helped me. So I'm posting my code here.
I have three html forms in WebContent/ folder form1.html, form2.html,form3.html, all these forms have same url pattern because accessing three different forms in the same Http session.
form1.html
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 1</h1>
<form action="./reg" method="get">
<table>
<tr><td>NAME:</td><td><input type="text" name="id"/></td></tr>
<tr><td>F_NAME:</td><td><input type="text" name="name"/></td></tr>
<tr><td>M_NAME:</td><td><input type="text" name="email"/></td></tr>
<tr><td><input type="submit" name= "NEXT"> </td></tr>
</table>
<input type="hidden" name="fno" value="1">
</form>
</body>
</html>
form2.html
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 2</h1>
<form action="./reg" method="get">
<table>
<tr><td>CONTACT:</td><td><input type="text" name="id"/></td></tr>
<tr><td>EMAIL:</td><td><input type="text" name="name"/></td></tr>
<tr><td>ADDRESS:</td><td><textarea rows ="10" cols="5" name="address"></textarea></td></tr>
<tr><td><input type="submit" name= "NEXT"> </td></tr>
</table>
<input type="hidden" name="fno" value="2">
</form>
</body>
</html>
<html>
<head>
<title>Adhar Registration Form</title>
</head>
<body style="background-color:orange">
<h1>FORM 3</h1>
<form action="./reg" method="get">
<table>
<tr><td>QUALIFICATION:</td><td><input type="text" name="id"/></td></tr>
<tr><td>PAN NO:</td><td><input type="text" name="name"/></td></tr>
<tr><td><input type="submit" name= "Register"> </td></tr>
</table>
<input type="hidden" name="fno" value="3">
</form>
</body>
</html>
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Adhar</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>container.RegistrationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/reg</url-pattern>
</servlet-mapping>
</web-app>
RegistrationServlet.java
package container;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class RegistrationServlet
*/
#WebServlet("/reg")
public class RegistrationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static final String URL = "jdbc:mysql://localhost/db";
public static final String USER = "root";
public static final String PASSWORD = "12345";
public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
/**
* #see HttpServlet#HttpServlet()
*/
public RegistrationServlet() {
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
PrintWriter out = response.getWriter();
HttpSession hs = request.getSession();
String fno = request.getParameter("fno");
if(fno.equals("1")){
String name = request.getParameter("name");
String f_name = request.getParameter("f_name");
String m_name = request.getParameter("m_name");
hs.setAttribute("name", name);
hs.setAttribute("f_name", f_name);
hs.setAttribute("m_name", m_name);
response.sendRedirect("./Form2.html");
}
if(fno.equals("2")){
String contact = request.getParameter("contact");
String email = request.getParameter("email");
String address = request.getParameter("address");
hs.setAttribute("contact", contact);
hs.setAttribute("email", email);
hs.setAttribute("address", address);
response.sendRedirect("./Form3.html");
}
if(fno.equals("3")){
String qual = request.getParameter("qual");
String pan = request.getParameter("pan");
String name = (String)hs.getAttribute("name");
String f_name = (String)hs.getAttribute("f_name");
String m_name = (String)hs.getAttribute("m_name");
String contact = (String)hs.getAttribute("contact");
String email = (String)hs.getAttribute("email");
String address = (String)hs.getAttribute("address");
try {
Class.forName(DRIVER_CLASS);
System.out.println("Loaded the driver");
Connection con = DriverManager.getConnection(URL,USER,PASSWORD);
PreparedStatement ps = con.prepareStatement("INSERT into adharReg values(?,?,?,?,?,?,?,?)");
ps.setString(1, name);
ps.setString(2, f_name);
ps.setString(3, m_name);
ps.setString(4, contact);
ps.setString(5, email);
ps.setString(6, address);
ps.setString(7, qual);
ps.setString(8, pan);
int i = ps.executeUpdate();
if(i!=0){
out.println("<h1>REGISTRATION SUCCESS</h1>");
}
else{
out.println("<h1>REGISTRATION FAILED</h1>");
}
} catch (Exception e) {
// TODO: handle exception
out.println("<h1>REGISTRATION FAILED" + e.getMessage() + " </h1>");
}
}
}
}
I'm using tomcat server 8.0. I checked this Link and my tomcat server has exact same settings. And followed this link for any possible mistakes but, I don't know the exact reason why i'm getting Http 404 error. Help me out why i'm getting this error.
Thanks.

The issue is caused by a conflict between web.xml configuration and the WebServlet annotation. The web.xml is delcaring a servlet called login that target to the /reg url, but also in the RegistrationServlet there is a declaration throught #WebServlet annotation that reference to the same url /reg.
One possible solution is to remove the servlet declaration from the web.xml, that means that the web.xml content should be like this.
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Adhar</display-name>
<welcome-file-list>
<welcome-file>form1.html</welcome-file>
</welcome-file-list>
</web-app>
Just let the Servlet declared by annotation only. Hope this helps.

check web.xml is exist into WEB-INF folder.
and use servlet mapping into web.xml
And register the servlet instead in web.xml like this:
<servlet>
<servlet-name>yourServlet</servlet-name>
<servlet-class>com.example.YourServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>yourServlet</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
for more refer bellow link :-
http://www.beingjavaguys.com/2013/08/jsp-servlet-hello-world-example.html
https://www.javatpoint.com/servlet-with-annotation

Related

Why am I getting a blank page in my servlet program

I am using netbeans 8.2 and using Apache Tomcat server. Whenever I run the program I get to the registration page. But when I submit the information I am supposed to get an output. But I always get a blank page.I am using the database present in JAVA. Please Help I have to submit my java project;_;. I still need to create a login page.
Thanks in Advance.
Jsp Program
<%--
Document : registeration
Created on : Mar 12, 2019, 10:24:50 AM
Author : Pranav Sharma
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div align="center">
<form action="Registeration" method="POST">
User Name:<input type="text" name="user" required="required"><br>
Password : <input type="password" name="password"
required="required"><br>
Age : <input type="text" name="age" required="required" /><br>
Gender : <select name="gender">
<option>Male</option>
<option>Female</option>
<option>Transgender</option>
</select><br>
Event : <select name="event" multiple="multiple">
<option>Mr.Tanwar Body Building</option>
<option>Fashion Show</option>
<option>Dance</option>
<option>Singing</option>
<option>Coding</option>
</select><br>
<input type="submit" value="REGISTER" />
<input type="reset" value="RESET" />
</form>
</div>
</body>
Servlet Program
package jdbc;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
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="Registeration", urlPatterns={"/Registeration"})
public class Registeration extends HttpServlet
{
private static final long serialVersionUID = 1L;
public Registeration(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
try {
String name = request.getParameter("user");
String password = request.getParameter("password");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String event = request.getParameter("event");
String sql = "insert into
registeration(name,password,age,gender,event) values(?,?,?,?,?)";
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/RegForm","pranav","sharma");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,name);
ps.setString(2,password);
ps.setString(3,age);
ps.setString(4,gender);
ps.setString(5,event);
ps.executeUpdate();
PrintWriter out = response.getWriter();
out.println("You have successfully registered!");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
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>Registeration</servlet-name>
<servlet-class>jdbc.Registeration</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registeration</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
I have create a java-servlet project which uses sql server as a database. Underline project takes input from the ui and persist into database.
After inserting data into database, it will show up is records inserted successfully or not.
Change the DBConnectionUtils according to your database
String url = "jdbc:mysql://localhost:3306/";
String dbName = "root";
String driver = "com.mysql.jdbc.Driver";
This is the link for the project on github https://github.com/rosmahajan/java-servlet
Otherwise please post more information like any exception or error you are getting to investigate what is wrong with your code.
Hope this helps you !!

Tomcat/Java - Insert into a mysql database

package mycode;
import java.sql.*
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;
public class Login extends HttpServlet {
private static final long serialVersionUID = -4546189621945422719L;
String URL = "jdbc:mysql://127.0.0.1";
String USER = "root";
String PASS = "1234";
#Override
protected void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException,ServletException{
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Connection con = DriverManager.getConnection(URL, USER, PASS);
String sql = "INSERT INTO cloud.cloud_table (Username,Password)" +
"VALUES (?, ?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
pst.executeUpdate();
out.println("<html><body>");
out.println("THANKS FOR CREATING AN ACCOUNT");
out.println("</body></html>");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
<?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>Login</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>mycode.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</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>
+----------+----------+
| Username | Password |
+----------+----------+
| | |
+----------+----------+
<form action="login" method="GET">
<div>
<h4>Please enter your password and username</h4>
</div>
<div>
Username <input name="username" type="text" />
</div>
<div>
Password <input name="password" type="text" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Using java and tomcat, I have a simple form that takes in a username and password. I want to be able to retrieve the username and password from the form and insert it into a mysql database. However, right now after clicking the submit button on the form, nothing happens and the database is not updated. The database connection is working fine so I am not sure what the problem is right now. Any help would be appreciated.
You are calling your GET method from the HTML form.
Change your action to POST.
<form action="login" method="POST">

HTTP Status 405 - HTTP method GET is not supported by this URL.The specified HTTP method is not allowed for the requested resource

Help me here guys...I have added servlet jar file and mysql connector jar file but it's showing the error like HTTP Status 405 - HTTP method GET is not supported by this URL.The specified HTTP method is not allowed for the requested resource.I have attempted every possible solution but i am getting the same error.
Regform.java
package com.servlet.info;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.Driver;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Regform extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String fNM = request.getParameter("firstName");
String lNM = request.getParameter("lastName");
String eID = request.getParameter("emailID");
String uNM = request.getParameter("userName");
String pass = request.getParameter("password");
try{
//loading drivers for mysql
com.mysql.jdbc.Driver mySqlDriverClassRef = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(mySqlDriverClassRef);
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/student_form?&useSSL=false", "j2ee" ,"j2ee");
PreparedStatement ps=con.prepareStatement
("insert into student values(?,?,?,?,?);");
ps.setString(1, fNM);
ps.setString(2, lNM);
ps.setString(3, eID);
ps.setString(4, uNM);
ps.setString(5, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
index.html
<html>
<head>
<title>Register form</title>
</head>
<body>
<form action="/register" method="POST" >
firstName:<input type="text" name="firstName" /><br/>
lastName:<input type="text" name="lastName" /><br/>
emailID :<input type="text" name="email" /><br/>
userName:<input type="text" name="userName" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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" >
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Regform</servlet-name>
<servlet-class>com.servlet.info.Regform</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Regform</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
Try adding below to your Java and see if it works
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
IOException,
ServletException {
doPost(request, response);
}
I recommend that you always write the codes you defined in the doPost and doGet methods in the doProcess method.

Basics of this web application development [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am creating a payroll system. I have a database which contains employee_id and password. My index.html is the login page, where you enter an employee_id and password and the database checks to see if the details are correct and if it is, then the Welcome.java servlet takes you to a page which prints "Welcome user".
What I want is, when an employee logs in, it takes them to a page with the following buttons instead of a screen which simply says "Welcome user":
View personal information, View payslip information, change password
I do not know how to do this.
Below are my files.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login" method="post">
<h3>
Employee Login
</h3>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Login.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
if(Validate.checkUser(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Validate.java (class file)
import java.sql.*;
public class Validate
{
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?");
ps.setString(1, employee_id);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Welcome.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("Welcome user");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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" >
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You have to change one line of code of login servlet RequestDispatcher rs = request.getRequestDispatcher("Welcome"); as RequestDispatcher rs = request.getRequestDispatcher("Options");
and create a html file of creating 3 buttons.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Options</title>
</head>
<body>
<form action="Mainservlet" method="post">
<h3>
Options
</h3>
<input type="submit" value="Personalinformation" name="pi">
<br>
<br>
<input type="submit" value="PayslipInformation" name="psi">
<br>
<br>
<input type="submit" value="ChangePassword" name="cp">
<br>
<br>
</form>
</body>
</html>
In mainservlet
if(request.getParameter("pi") != null) {
// Invoke PersonalInformation's job here.
} else if (request.getParameter("psi") != null) {
// Invoke PayslipInformation's job here.
}else if (request.getParameter("cp") != null) {
// Invoke ChangePassword's job here.
}
Create an html or jsp page with your buttons and other content, then redirect from login servlet to your page instead of welcome servlet through request dispatcher or just by response.sendRedirect() method.

Unsuccessful redirecting of servlet based using string query parameters

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.

Categories