I'm having trouble with doGet and doPost methods - java

PersonalInfoOutput.java servlet is using the doPost method. The user logs in at index.html. From index.html, the request is sent to Login.java servlet.
From there, the user is directed to the PersonalInfoOutput.java servlet.
Now, consider another page called ChangePassAdmin.html. In this html code, one of these goes to PersonalInfoOutput.java. But when I click on it from that page,
I get HTTP Status 405 - HTTP method GET is not supported by this URL.
Can someone please help me as to how I should solve this problem?
I tried changing PersonalInfoOutput.java to doGet instead of doPost but then Login.java servlet will return HTTP Status 405 - HTTP method POST is not supported by this URL. So it seems I need both doGet and doPost for this PersonalInfoOutput.java servlet.
PersonalInfoOutput.java (servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class PersonalInfoOutput extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
String employeeid = "";
if(session != null) {
employeeid = (String)session.getAttribute("employeeid");
}
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 employeeID, FirstName, LastName, Admin, DOB, Address, Email, HourlyRate, Gender, ALeaveBalance, SLeaveBalance, ActiveStatus, Role, BSB, BankName, AccNumber, SuperNumber, SuperCompany from payroll_system.employee_info where employeeID = ?");
ps.setString(1, employeeid);
ResultSet rs = ps.executeQuery();
st = rs.next();
if(st){
etc... (rest of the code isn't relevant to question)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<title>Login</title>
</head>
<body>
<form action="Login" method="post">
<h1>
Login
</h1>
<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");
HttpSession session = request.getSession();
session.setAttribute("employeeid", employee_id);
if(ValidateLogin.user(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("PersonalInfoOutput");
rs.forward(request, response);
}
else
{
out.print("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
ChangePassAdmin.html
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<link rel = "stylesheet" type = "text/css" href = "main.css">
<link rel = "stylesheet" type = "text/css" href = "sidebar.css">
<title>Change Password</title>
<style>
table { border-collapse: collapse; width: 50%; } th, td { text-align: left; padding: 8px; } tr:nth-child(even){background-color: #f2f2f2}
tr:hover {background-color: #e2f4ff;}
</style>
</head>
<body>
<ul>
<li><a href=PersonalInfoOutput>View Personal Information</a></li>
<li><a href=PersonalInfoOutput>View Expense Claims</a></li>
<li><a href=PersonalInfoOutput>View Payslips</a></li>
<li><a class=active >Change Password</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Tax Information</a></li>
<li><a href=PersonalInfoOutput>Maintain Payroll Items</a></li>
<li><a href=PersonalInfoOutput>Maintain Timesheet</a></li>
<li><a href=PersonalInfoOutput>Maintain Employee Expenses</a></li>
<li><a href=PersonalInfoOutput>Run Payroll</a></li>
<li><a href=PersonalInfoOutput>Generate Reports</a></li>
</ul>
<div style=margin-left:25%;padding:1px;>
</div>
<div id="container">
<h1>Change Password</h1>
<form action ="NewPassword" method = post>
<table border ="1">
<tr>
<td>Existing Password:</td>
<td><input type = "password" name = "oldpassword" size = "20"></td>
</tr>
<tr>
<td>New Password:</td>
<td><input type = "password" name = "newpassword" size = "20"></td>
</tr>
<tr>
<td>Confirm New Password</td>
<td><input type = "password" name = "confirmpassword" size = "20"></td>
</tr>
</table>
<br>
<br>
<input type = "submit" value = "Update Password">
</form>.
</div>
</body>
</html>

In ChangePassAdmin.html, double quotes around post are missing.
Both of your Servlet should have doPost method as your form is using "post" action.
<form action ="NewPassword" method = "post">
Additionally you will need two methods in this case. Add both doGet and doPost in your servlet. doPost will be used by form and doGet by links. By default all links are GET.
You can do it like:
Edit:
public class PersonalInfoOutput extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Your servlets code should be here
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
doPost() method to receive form based request. doGet() method to receive href based request. But in both cases processRequest() method will be called.

I believe the problem is that you're using the PersonalInfoOutput servlet in two ways:
Forwarding from Login servlet, which by forwarding keeps using POST method
And by href from the HTML, which by default uses method GET
Wouldn't a possible solution be for you to refactor your code, which would be good for you to do anyway, so that you implement both doGet() and doPost() in the PersonalInfoOutput servlet without repeating a lot of code?
Or you could refactor the employee database retrieval to an external class, that would be called from Login without the need to redirect from one servlet to another, and implement GET instead of POST in PersonalInfoOutput.

Related

Servelt Page doesn't Redirect to second Page using Servlet

I am a beginner of servlet jsp. I am creating a simple login form if the login successful page redirects to the second servlet along with the username. but it doesn't work it shows the error java.lang.IllegalArgumentException: Path second does not start with a "/" character
what I tried so far I attached below.
Form
<div class="row">
<form method="POST" action="login">
<div class="form-group">
<label>Username</label>
<input type="text" id="uname" name="uname" placeholder="uname" class="form-control">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="pword" name="pword" placeholder="pword" class="form-control">
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-success">
</div>
</form>
</div>
Login Servlet Page
#WebServlet("/login")
public class login extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String uname = request.getParameter("uname");
String pass = request.getParameter("pword");
if(uname.equals("John") && pass.equals("123"))
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
session.putValue("username", uname);
ServletContext context=getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("second");
rd.forward(request, response);
}
}
Second Servlet Page
#WebServlet("/second")
public class second extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String uname = (String)session.getValue("uname");
out.println("User Name is " + uname);
}
There are some big differences between redirect and forward . This article will help you to understand better your problem.
Some things to keep in mind from the article :
FORWARD
1) Request and response objects will remain the same object after forwarding. Request-scope objects will be still available (this is why if you try to add the "/" you get the 405 status - it will try to forward you to the "/second" servlet but the only request overridden is GET)
REDIRECT
1) The request is redirected to a different resource
2) A new request is created
So instead of using rd.forward I would suggest you to use the sendRedirect() method from HttpServletResponse class.
response.sendRedirect(request.getContextPath() + "/second");
AND the correct way to get the session username attribute is this:
String uname = (String) session.getValue("username");
Otherwise it will try to look after uname key which is not set. The uname was only a value mapped to the username key ( session.putValue("username",uname);
this exception indicates, path does not start with a "/".
try below instead.
RequestDispatcher rd=context.getRequestDispatcher(request.getContextPath() +"/second");

Sending a request through Ajax to a servlet (non spring) [duplicate]

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 4 years ago.
I have a CRUD table that lists a bunch of products, what I need is that when I click on a button, Ajax automatically sends a request to the servlet telling it that I want to change the state (instead of deleting the product) in the database, then after that is done it should reload the table.
I already have most of the code done, here is the AJAX that I had (Which I suppose is the part that is wrong), I was working on it trying to get it to work when I clicked on a row so ignore that part, there's a delete button per row).
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "statecontroller.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
});
</script>
And here is the servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
ProductDAO productBD = new ProductDAO();
Product products = productBD.selectById(id);
if(products.getState() == "Active"){
Product product = new Product(id,"Not Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}else if(products.getState() == "Not Active"){
Product product = new Product(id,"Active");
productBD.update(product);
ArrayList<Product> productList = new ArrayList<>();
productList = productBD.selectAll();
request.getSession().setAttribute("productList", productList);
request.getRequestDispatcher("/wproduct/listing.jsp").forward(request, response);
}
}
I tried looking it up but only found how to do this with Spring
(Here is the full servlet code, it has Spanish names on it which is why I translated it for the original post):
package controladores;
import daos.ClienteDAO;
import dtos.Cliente;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 lycan
*/
#WebServlet(name = "ControladorEstado", urlPatterns = {"/controladorestado.do"})
public class ControladorEstado 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 {
int id = Integer.parseInt(request.getParameter("id"));
ClienteDAO clientebd = new ClienteDAO();
Cliente clientes = clientebd.selectById(id);
if(clientes.getEstado() == "Activo"){
Cliente cliente = new Cliente(id,"No Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
}else if(clientes.getEstado() == "No Activo"){
Cliente cliente = new Cliente(id,"Activo");
clientebd.update(cliente);
ArrayList<Cliente> lista = new ArrayList<>();
lista = clientebd.selectAll();
request.getSession().setAttribute("lista", lista);
request.getRequestDispatcher("/wcliente/listar.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>
}
And here is the listing code:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : listar
Created on : 19-oct-2018, 11:00:29
Author : lycan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%#include file="../WEB-INF/jspf/estilos.jspf"%>
<title>Sistema Ventas</title>
</head>
<body>
<div class="container-fluid">
<%#include file="../WEB-INF/jspf/header.jspf"%>
<%#include file="../WEB-INF/jspf/nav.jspf"%>
<section>
<table id="test" class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${sessionScope.lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
Registrar
Buscar
</section>
<%#include file="../WEB-INF/jspf/footer.jspf"%>
</div>
<%#include file="../WEB-INF/jspf/js.jspf"%>
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
console.log(id);
$.ajax({
url: "controladorestado.do",
type: 'POST',
data: { id : id},
success: function() {
}
});
// Locate HTML DOM element with ID "somediv" and set its text content with the response text.
});
</script>
</body>
</html>
okay i see what you are doing now, thanks for including more information. The reason why nothing happens is because in your servlet you are trying to return the same page you are making the ajax call from. (and you're not even handling the response)
From the looks of it, you want to return a table through the ajax method, but in order to do that you need to create a separate jsp that you will return.. For example:
create a new jsp called user-table inside /wcliente/
user-table.jsp
<?xml version="1.0" encoding="UTF-8"?>
<%#page contentType="application/xml" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Descripcion</th>
<th>Categoria</th>
<th>Estado</th>
<th><i class="fas fa-binoculars"></i></th>
<th><i class="fas fa-pen-alt"></i></th>
<th><i class="fas fa-user-times"></i></th>
</tr>
</thead>
<tbody>
<c:forEach var="clientes" items="${lista}">
<tr>
<td>${clientes.id}</td>
<td>${clientes.nombre}</td>
<td>${clientes.descripcion}</td>
<td>${clientes.categoria}</td>
<td>${clientes.estado}</td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=detalle&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Detalle</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=actualizar&id=${clientes.id}" class="btn btn-primary btn-lg " role="button" >Actualizar</a></td>
<td><a href="<%=request.getContextPath()%>/controladorcliente.do?operacion=eliminar&id=${clientes.id}" class="btn btn-primary btn-lg eliminar" role="button" >Eliminar</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</data>
Now in your servlet, instead of this:
request.getRequestDispatcher("/wcliente/listar.jsp").forward(request, response);
do this:
request.getRequestDispatcher("/wcliente/user-table.jsp").forward(request, response);
For the ajax in your listar.jsp do this instead:
<script>
$("#test").on('click','tr',function() {
var id = $(this).find("td:first-child").text();
$.post("controladorestado.do", {id : id}, function(responseXml) { // Execute Ajax POST request on URL of "controladorestado.do" and execute the following function with Ajax response XML...
$("#test").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "test".
});
});
</script>
Reference:
How to use Servlets and Ajax?

tomcat says http method post is not supported by this url

i've been calling servlet by a HTML page and my servlet code goes like this:
import java.sql.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
public class validation extends HttpServlet
{
static PrintWriter pw = null;
public void doPost(HttpServletResponse response, HttpServletRequest request) throws ClassNotFoundException, SQLException, IOException, ServletException
{
pw = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
RequestDispatcher rd = request.getRequestDispatcher("new.html");
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/timetabledb", "root","`");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select password from users where username = '"+username+"';");
if(rs.next()==false)
{
pw.println("No such user found!");
}
else
{
if(password.equals(rs.getString("password")))
{
rd.forward(request, response);
}
else
{
pw.println("Invalid credentials!");
}
}
rs.close();
}
}
and my html page is this:
<!DOCTYPE html>
<html>
<head>
<title>Login Page - SGMS</title>
<link rel="stylesheet" href="main.css" />
</head>
<body>
<div id = "container">
<div class = "welcome-head">
Welcome
</div>
<div class = "sw-head">
Semi-Automatic Schedule Generator & Maintenance Software
</div>
<span class="logo">
<img src="logo.gif" alt="Logo"/>
</span>
<div class = "form">
<form method="POST" action="validation">
<label for="inp-usr" class="inp">
<input type="text" name="username" id="inp-usr" placeholder=" " required="required">
<span class="label">Username</span>
<span class="border"></span>
</label>
<br>
<label for="inp-pwd" class="inp">
<input type="password" name="password" id="inp-pwd" placeholder=" " required="required">
<span class="label">Password</span>
<span class="border"></span>
</label>
<br><br><br>
<button class="validate-btn" onclick="show();">
Validate
</button>
</form>
</div>
</div>
</body>
</html>
but the problem is that whenever i run all this, the application server says, that POST method isn't supported by this url.
I've experienced this error frequently, please explain why all this happens.
I've mapped the servlet in my web.xml
Thanks in advance.
You have made a mistake in your doPost method. You have declared it as this:
void doPost(HttpServletResponse response, HttpServletRequest request)
throws ClassNotFoundException, SQLException, IOException, ServletException
but the correct signature is this:
void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
Notice the different parameter order ....
Since your method doesn't have the correct signature, it is not overriding the inherited version. That means that your version never gets called. Instead, a POST requests calls the inherited method ... and the behavior of that is to say "POST not supported".
Solution:
Correct your doPost method's signature. (The exceptions will need fixing too!)
Add an #Override annotation to this ... and any other override methods in this class.
Get into the habit of always using #Override wherever you intend to override a method ... so that the Java compiler can point out your mistakes to you.

How to properly display Mysql tables using servlets and java?

I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}

Hang Man Game in MVC with JSP

I want to create Hang man game, but I need to save the session and the username, but I have problems for pass the username. I wrote the JSP, servlet and Javabean, but after the login my user, in the next view I only have Welcome + NULL. Help me please. thanks for the help.
I don't know how Can I pass the name to the next view.
enter code here
this is the JavaBean(Userdata.java):
public class Userdata {
String userName;
public Userdata() {
}
public Userdata(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
This is the servlet, in this code I need to use a session, but I want to that, in all the time that the user is logging, cans see his/her name
loginServlet.java
public class loginServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata = new Userdata(usuari);
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", username);
RequestDispatcher view = request.getRequestDispatcher("juego.jsp");
view.forward(request, resp);
}
}
Finally the Views in JSP, The first view is the login
Nom de jugador:
Contrasenya:
And this is the response of servlet -> juego.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Penjat</title>
</head>
<h2>Benvingut</h2>
<%=request.getAttribute("usuari")%>
<div align="center">
<h1>Joc del Penjat</h1>
</div>
<div align="center">
<!--DelaraciĆ³ d'imatges-->
<img src="Imatges/p_JEE_3.png">
</div>
<div align="center">
<!--DeclaraciĆ³ de les lletres-->
Lletra:
<input type="text" name="lletra" size="1" maxlength="1">
<br/>
<p>
<input type="hidden" name="id" value=""/>
<input type="hidden" name="vegades_jugades" value=""/>
<input type="hidden" name="pistes" value=""/>
<input type="submit" name="boto_jugar" value="Jugar">
</p>
</div>
First you have to put username in request, in your servlet use request.setAttribute in the following manner
request.setAttribute("username", value);
where value happens to be the object you want to read later.
Use it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("username")
or
<%= request.getAttribute("username")>
Thanks for your help, now I understand, I modificated and now I can get the username.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws
ServletException, IOException {
HttpSession session = request.getSession();
Userdata usuari = new Userdata();
if(request.getParameter("username")!=null &&
!request.getParameter("username").trim().equals("") ){
usuari = new Userdata(request.getParameter("username"));
}
if(request.getParameter("logout")!=null){
session.invalidate();
}
request.setAttribute("username", usuari);
RequestDispatcher view = request.getRequestDispatcher("juegoOriginal.jsp");
view.forward(request, resp);
}

Categories

Resources