Servlet not displaying anything neither showing any error - java

<link rel="stylesheet" href="res/Site.css"/>
<body style="height: 800px">
<pre>
<!-- <h1 class="black"><center>Registration Detail<img src="res/login.png"/></center></h1>-->
<h3>Cast Your Vote To The Right Persion</h3>
<form width="200" action ="regservlet" method="POST">
<legend><i>Fill Up Your Details</i></legend>
Voter Name :<input placeholder="Enter Name" type="text" name="vname">
Voter ID :<input placeholder="Enter VoterID" type="text" name="vid">
Email :<input placeholder="Enter Email" type="text" name="vemail">
Age :<input placeholder="Enter Age(>18)" type="text" name="vage">
Address :<input placeholder="Enter Address" type ="text" name="vaddress">
Pin Code :<input placeholder="Enter PIN" type ="text" name="vpin">
State :<input placeholder="Enter State"type ="text" name="vstate">
<input type="Submit" class="button Green" value="Submit"/> <input type="Reset" class ="button red" value="Reset"/>
</form>
<h4>Already Registered Login Here</h4>
<%-- ${requestScope.msg1}
${requestScope.msg2}
${requestScope.msg3}--%>
</pre>
</body>
servlet
/*
* 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 web1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jdbc.DAOLayer;
/**
*
* #author 1405075
*/
public class regservlet 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();
String name=request.getParameter("vname");
String id=request.getParameter("vid");
String mail=request.getParameter("vemail");
String age=request.getParameter("vage");
String add=request.getParameter("vaddress");
String pin=request.getParameter("vpin");
String state=request.getParameter("vstate");
String q = "select * from voter where vid ='"+id+"';";
ResultSet rs = DAOLayer.selectData(q);
try{
if(rs.next())
{ RequestDispatcher rd = request.getRequestDispatcher("Registration.jsp");
rd.include(request,response);
out.println("<font color='Red'><h3>Please enter valid voter ID</h3></font><br>");
out.println("<font color='Red'><h3>This Voter ID is already registered with us.</h3></font>");
}
else
//if(p.equals(cp))
{
String query = "insert into voter(vname,vid,vage,vaddress,vpin,vstate,vemail) values('"+name+"','"+id+"','"+age+"','"+add+"','"+pin+"','"+state+"','"+mail+");";
int ur = DAOLayer.updateData(query);
if(ur>0){
RequestDispatcher rd = request.getRequestDispatcher("Registration.jsp");
rd.include(request,response);
out.print("<h3><font color= 'Green'>Registered Successfully</font></h3>");
}
}
}catch(Exception e)
{
out.print(e);
}
}
// <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>
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
Loginservlet
web1.Loginservlet
Registrationservlet
web1.Registrationservlet
<servlet>
<servlet-name>regservlet</servlet-name>
<servlet-class>web1.regservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Registrationservlet</servlet-name>
<url-pattern>/rs</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Loginservlet</servlet-name>
<url-pattern>/Loginservlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>regservlet</servlet-name>
<url-pattern>/regservlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
On running my servlet it doesnt display anything neither showing any error.

Your approach is wrong. You are passing queries as parameters to DAOLayer. When you are passing query as String the corresponding values of variables are not sent. It is just a String = "select * from voter where vid ='"+id+"'"; .The value of varible id is not sent here. Instead of it define queries within methods in DAOLayer and receive values of variables there. The correct MVC approach to do this is using Beans. Create a simple Registration Bean like this :-
public class RegistrationBean {
private String name;
private String id;
private String age;
private String address;
private String pin;
private String state;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Modify your servlet code to set the bean properties like this :-
RegistrationBean rb=new RegistrationBean();
rb.setName(name);
rb.setId(id);
rb.setAge(age);
rb.setAddress(add);
rb.setPin(pin);
rb.setState(state);
For checking the existing user, modify your selectData method in DAOLayer to receive just id and call it like this :-
ResultSet rs = DAOLayer.selectData(id);
Use rd.forward(request,response); instead of rd.include(request,response); . After execution of this statement control will be transferred to Registration.jsp and these statements :-
out.println("<font color='Red'><h3>Please enter valid voter ID</h3></font><br>");
out.println("<font color='Red'><h3>This Voter ID is already registered with us.</h3></font>");
will not be executed. This is another error in your code. For insert operation modify your updateData method to receive RegistrationBean. Receive value of variables there using getter methods of bean that is like this :-
public int updateData(RegistrationBean rb){
String name=rb.getName();
String id=rb.getId();
String age=rb.getAge();
String address=rb.getAddress();
String pin=rb.getPin();
String state=rb.getState();
.
.
rest of your code. Execute insert query here.
}
Here transferring the control to Registration.jsp is meaning less. Create a HTML page named Success.html which shows success message for transaction. Create another page named Failure.Html which shows failure message and call it like this :-
if(ur>0){
response.sendRedirect("success.html");
}else{
response.sendRedirect("failure.html");
}
Hope it will help. Mark the problem solved by clicking right mark on top left side of my answer if it does. If not, let me know. Happy Coding :)

Related

Estado HTTP 500 – Internal Server Error, Netbeans ide 13 tomcat 8.5.78

I am doing a login with servlet but I get this error:
I don't know if it's a tomcat problem or why it will be but I already tried with netbeans 13 and netbeans 8.2 and jdk 18, jdk 8 and I still get the same error
The connection works correctly because I already checked it with a code
The mistake is:
Type: Status Report
Description: The requested resource is not available.
sometimes i get this too
exception
javax.servlet.ServletException: Error instantiating servlet class [controlador.Validar]
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:882)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:750)
root cause
java.lang.ClassNotFoundException: controlador.Validar
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1420)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1228)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:543)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:698)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:367)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:639)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:882)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1647)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:750)
note The full trace of the cause of this error is in the server log files.
index.jsp
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<div class="container center-block" >
<div class="row justify-content-center">
<div class="card" style="width: 18rem;">
<img src="logo.png" class="card-img-top" alt="...">
<div class="card-body">
<form method="POST" action="Validar">
<div class="form-group">
<label>No de Documento</label>
<input type="text" class="form-control" name="txtusuario">
<small id="emailHelp" class="form-text text-muted">Ingrese su documento sin espacios ni puntos</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Contraseña</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="txtpassword">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Permanecer loggeado</label>
</div>
<button type="submit" class="btn btn-primary" name="accion" value="Ingresar">Ingresar</button>
</form>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
</body>
</html>```
----------------------------------------------------------------------------
Controlador.java
/*
Servlet Controlador
*/
package Controlador;
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;
#WebServlet(name = "Controlador", urlPatterns = {"/Controlador"})
public class Controlador 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 {
String menu = request.getParameter("menu");
//Redirecciona a las paginas según la opción seleccionada agregando los casos respectivos
if(menu.equals("Principal")){
request.getRequestDispatcher("Principal.jsp").forward(request, response);
}
if(menu.equals("Productos")){
request.getRequestDispatcher("Productos.jsp").forward(request, response);
}
if(menu.equals("Empleados")){
request.getRequestDispatcher("Empleados.jsp").forward(request, response);
}
if(menu.equals("Clientes")){
request.getRequestDispatcher("Clientes.jsp").forward(request, response);
}
if(menu.equals("Ventas")){
request.getRequestDispatcher("Ventas.jsp").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>
}
----------------------------------------------------------------------------
validar.java
/*
Servlet Validar
*/
package controlador;
import java.io.IOException;
import java.io.PrintWriter;
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;
import Modelo.Usuario;
import Modelo.UsuarioDAO;
#WebServlet(name = "Validar", urlPatterns = {"/Validar"})
public class Validar extends HttpServlet {
Usuario usuario = new Usuario();
UsuarioDAO usuarioDAO = new UsuarioDAO();
/**
* 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");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Validar</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Validar at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
String accion = request.getParameter("accion");
if (accion.equalsIgnoreCase("Ingresar")) {
int documento = Integer.parseInt(request.getParameter("txtusuario"));
String pass = request.getParameter("txtpassword");
try {
usuario = usuarioDAO.Validar(documento, pass);
} catch (SQLException ex) {
Logger.getLogger(Validar.class.getName()).log(Level.SEVERE, null, ex);
}
if (usuario.getNombre() != null) {
request.setAttribute("usuario", usuario);
request.getRequestDispatcher("Controlador?menu=Principal").forward(request, response);
} else {
request.getRequestDispatcher("index.jsp").forward(request, response);
}
} else {
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
----------------------------------------------------------------------------
usuario.java
package Modelo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Usuario {
int id;
int documento;
String nombre, correo, estado, password, rol;
public Usuario() {
}
public String getRol() {
return rol;
}
public void setRol(String rol) {
this.rol = rol;
}
public Usuario(int id, int documento, String nombre, String correo, String estado, String password, String rol) {
this.id = id;
this.documento = documento;
this.nombre = nombre;
this.correo = correo;
this.estado = estado;
this.password = password;
this.rol = rol;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getDocumento() {
return documento;
}
public void setDocumento(int documento) {
this.documento = documento;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getCorreo() {
return correo;
}
public void setCorreo(String correo) {
this.correo = correo;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
----------------------------------------------------------------------------
UsuarioDAO.java
package Modelo;
import Config.Conexion;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class UsuarioDAO {
Connection con;
PreparedStatement ps;
ResultSet rs;
Conexion cn = new Conexion();
public Usuario Validar(int documento, String password) throws SQLException {
Usuario usuario = new Usuario();
String consulta = "SELECT * FROM usuarios WHERE documento = ? AND password = ?";
con = cn.Conexion();
try {
ps = con.prepareStatement(consulta);
ps.setInt(1, documento);
ps.setString(2, password);
rs = ps.executeQuery();
rs.next();
do {
usuario.setId(rs.getInt("id"));
usuario.setDocumento(rs.getInt("documento"));
usuario.setNombre(rs.getString("nombre"));
usuario.setPassword(rs.getString("password"));
usuario.setCorreo(rs.getString("correo"));
usuario.setEstado(rs.getString("estado"));
usuario.setRol(rs.getString("rol"));
} while (rs.next());
} catch (SQLException ex) {
Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return usuario;
}
}
`

java web Restful HTTP 404 Not Found

the java web client.
this is index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Calcular factorial</title>
</head>
<body>
<div align="center">
<form action="calcular.do" style="font-family:arial">
Numero :<br>
<input type="text" name="base" style="text-align:right"/><br><br>
<input type="submit" value="calcular" name="Calcular" />
<br><br>
Resultado:<br>
<input type="text" name="resultado" value="${result}"
style="text-align:right"/><br><br>
</form>
</div>
</body>
</html>
this is the Calcular.java
package controlador;
import Webservicce.ClientRest;
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 x2010s
*/
#WebServlet(name = "Calcular", urlPatterns = {"/calcular.do"})
public class Calcular 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 {
ClientRest rest = new ClientRest();
String base = request.getParameter("base");
String factorial = rest.factorial(base);
request.setAttribute("factorial",factorial);
request.getRequestDispatcher("index.jsp").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>
}
in the servlet, the factorial method must be called from the restful, to calculate the factorial with the entered number
this is the imported RESTful Java Client
package Webservicce;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
public class ClientRest {
private WebTarget webTarget;
private Client client;
private static final String BASE_URI = "http://localhost:8080/SimpleRESTweb/webresources";
public ClientRest() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("factorial");
}
public String factorial(String base) throws ClientErrorException {
WebTarget resource = webTarget;
if (base != null) {
resource = resource.queryParam("base", base);
}
return resource.request().get(String.class);
}
public void close() {
client.close();
}
}
When I enter the number and click on calculate it appears
HTTP Status 500 - Internal Server Error
type Exception report
message Internal Server Error
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.ws.rs.NotFoundException: HTTP 404 Not Found
errors appear in the java web client. I can not find the error, because it does not calculate the factorial

HTTP Status 404 - Not Found - Servlet and JSP

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

Java servlets resource not found

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

Request Attributes not clearing after request is over

I am having a problem with request attributes in my jsp, I am using the mvc pattern and setting a request attribute and forwarding to a jsp from the servlet. The application is a banking application, the goal is to use the customer id to get the customer by customer id pass it to the Account class to collect all of the accounts of the user. I have this problem solved I can get the account information and process it without any issue. The problem I am having is when I close the page and run again from the beginning I find that when I get to the table it is still putting in the information from the previous request as well as the new information that I am requesting. Like So:
()
My code is as follows for the servlet that directs me to the jsp and the jsp that I use the information into.
AccountServlet.java:
package com.ChattBank.controller;
import com.ChattBank.business.Account;
import com.ChattBank.business.Accounts;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author AARONS
*/
public class AccountServlet 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");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AccountServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AccountServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
//HttpSession session = request.getSession();
String action = request.getParameter("action");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
} else if (action.equals("view")) {
Accounts acct = new Accounts();
ArrayList<Account> list = new ArrayList();
try {
acct.setCustAccounts(request.getParameter("id"));
list.addAll(acct.getCustAccounts());
System.out.println(request.getParameter("id"));
} catch (SQLException ex) {
Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("acctList", list);
request.getServletContext().getRequestDispatcher("/accounts.jsp").forward(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 {
String action = request.getParameter("action");
String custId = request.getParameter("custID");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
accounts.jsp:
<%--
Document : accounts
Created on : Jun 25, 2014, 12:24:38 AM
Author : Richard Davy
--%>
<%#page import="java.util.ArrayList"%>
<%#page import="com.ChattBank.business.Account"%>
<%#page import="com.ChattBank.business.Accounts"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Your Accounts</title>
</head>
<body>
<%
ArrayList<Account> list = new ArrayList();
list.addAll((ArrayList)request.getAttribute("acctList"));
for (Account custAccount : list) {
System.out.println("From JSP: " + custAccount.getCustId() + " " + custAccount.getAcctNo() + " " + custAccount.getAcctType() + " " + custAccount.getBalance());
System.out.println("Getting Object From Section");
}
%>
<h1>You Made It Here!</h1>
<table border="1" width="2" cellspacing="5" cellpadding="2">
<thead>
<tr>
<th colspan="10">Your Chatt Accounts</th>
</tr>
</thead>
<tbody>
<% for (int i = 0; i < list.size(); i++){ %>
<tr>
<td colspan="2">Account: </td>
<td colspan="2"><%= list.get(i).getCustId() %></td>
<td colspan="2"><%= list.get(i).getAcctNo() %></td>
<td colspan="2"><%= list.get(i).getAcctType() %></td>
<td colspan="2"><%= list.get(i).getBalance() %></td>
</tr>
<% } %>
<% list.clear(); %>
</tbody>
</table>
<p>Thank you for your business!</p>
</body>
</html>
I am not really sure what is going on I started with session attributes and thought that was my issue, so I turned to using request attributes. But I am still facing the same issue. I was under the impression that the request attribute only lasted per that request but it seems that the information is still being carried through. Any suggestions?
The funny thing about this issue is that it wasn't anything to do with the request attribute variables. Since I was instantiating a list of objects in a class that list of objects was persisting and just being added to. I think this is mostly because I was using an ArrayList which is able to be appended to. Instead of re-writing the entire class to figure out some work around I included a try{}finally{} statement like so:
package com.ChattBank.controller;
import com.ChattBank.business.Account;
import com.ChattBank.business.Accounts;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* #author AARONS
*/
public class AccountServlet 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");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet AccountServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet AccountServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <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 {
//HttpSession session = request.getSession();
String action = request.getParameter("action");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(request, response);
} else if (action.equals("view")) {
Accounts acct = new Accounts();
ArrayList<Account> list = new ArrayList();
try {
acct.setCustAccounts(request.getParameter("id"));
list.addAll(acct.getCustAccounts());
System.out.println(request.getParameter("id"));
//This was moved into the try block itself
request.setAttribute("acctList", list);
request.getServletContext().getRequestDispatcher("/accounts.jsp").forward(request, response);
} catch (SQLException ex) {
Logger.getLogger(Accounts.class.getName()).log(Level.SEVERE, null, ex);
//This is the added finally statement with the clearAccounts method
} finally {
acct.clearAccounts();
}
}
}
/**
* 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 {
String action = request.getParameter("action");
String custId = request.getParameter("custID");
if (action == null) {
request.getRequestDispatcher("/Welcome.jsp").forward(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 clear accounts method in the Accounts class was very very simple:
/**
* Clears the current array list of accounts
*/
public void clearAccounts(){
this.custAccounts.clear();
}

Categories