Servlet works only for one jsp form - java

I started experimenting a little bit with JSPs and Servlets.I have a project that lets you create an account and saves user data in Oracle db.I have created a form that allows the user to make a quick log-in,from the webapps header using email and password fields:
<jsp:include page="/includes/header.jsp" />
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='sources/css/logIn.css'/>" type="text/css" rel="stylesheet" />
<form action="logIn" method="post">
<table>
<td>
<div id="header_logo">
<a href="<c:url value='/welcome.jsp'/>">
<img src="<c:url value='/sources/images/logo.jpg'/>">
</a>
</div>
</td>
<td>
Dont have an account?
</td>
<td>
JOIN! </td>
<td class="header_label" align="left">
<div id ="header_email">
email Address<br>
<input type="text" name="logEmailAddress" size="15" value="" class="header_input">
</div>
</td>
<td class="header_label" align="left">
<div id="header_password">
password<br>
<input type="password" name="logPassword" size="15" value="" class="header_input">
</div>
</td>
<td>
<div id="header_submit">
<br><input id="sub" type="submit" value="Log In">
</div>
</td>
</table>
</form>
I use post method to call the LogInServlet which looks like this:
package appUsers;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserDB;
public class LogInServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String logEmailAddress = request.getParameter("logEmailAddress");
String logPassword = request.getParameter("logPassword");
String url = "";
String message ="";
boolean isLogged=false;
//debug message
System.out.println("user input is emailaddress: " + logEmailAddress + " and password: " + logPassword);
if (logEmailAddress.length()==0 || logPassword.length()==0)
{
message = "Please provide your email address and password";
url = "/welcome.jsp";
}
User user = UserDB.selectUser(logEmailAddress);
if (user!=null)
{
isLogged = logPassword.equals(user.getPassword());
System.out.println(isLogged);
if(isLogged)
{
message = "You have succesfully loged in";
url = "/welcome.jsp";
}
else
{
message = "Invalid password";
url = "/welcome.jsp";
}
}
else
{
message = "No such account";
url = "/welcome.jsp";
}
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("isLogged", isLogged);
request.setAttribute("message",message);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The function that selects the user from the db:
User user = UserDB.selectUser(logEmailAddress);
is implemented like this:
public static User selectUser(String emailAddress)
{
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM USERS " + "WHERE EmailAddress = ?";
try
{
ps = connection.prepareStatement(query);
ps.setString(1, emailAddress);
rs = ps.executeQuery();
User user = null;
if (rs.next())
{
user = new User();
user.setFirstName(rs.getString("FirstName"));
user.setLastName(rs.getString("LastName"));
user.setEmailAddress(rs.getString("EmailAddress"));
user.setUserName(rs.getString("UserName"));
user.setPassword(rs.getString("Password"));
user.setUserType(rs.getString("Type"));
}
return user;
}
catch (SQLException e){
e.printStackTrace();
return null;
}
finally
{
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
All of the above work fine together, user is selected from DB and confirms users account when logging in from header fields.
Yesterday i tried to create a similar form which is displayed in the main view calling the same Servlet using post method:
<jsp:include page="/includes/header.jsp" />
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<link href="<c:url value='sources/css/logIn.css'/>" type="text/css" rel="stylesheet" />
<div id="log">
<h1>Log in to Triptip</h1>
<form action="logIn" method="post">
<table>
<tr class="spaceBetweenRows">
<td class="user_label" align="left">
email Address<br>
</td>
<td>
<input class="user_input" type="text" name="logEmailAddress" value=" ">
</td>
</tr>
<tr>
<td class="user_label" align="left">
password<br>
</td>
<td>
<input class="user_input" type="password" name="logPassword" value="">
</td>
</tr>
<tr>
<td>
</td>
<td align="right">
<br>
<input id="sub" type="submit" value="Log In">
</td>
</tr>
</table>
</form>
</div>
</body>
Although i have confirmed that attributes Email and Password are being passed correctly to the Servlet the User user = UserDB.selectUser(logEmailAddress); returns null although the user exists!
Anybody have an idea of what might be going on? I tried implementing a new servlet but with the same outcome!Any help would be appreciated since i spent a lot of latenight hours trying to figure this thing out!
I'm using Windows 7 64, Netbeans, 7.4 Java 1.7.0-51, Tomcat 7 and Oracle 11.2XE

In your code, you set a default value that includes a space -
<input class="user_input" type="text" name="logEmailAddress" value=" ">
Based on your comment, you didn't notice that and simply added more characters. You don't need a default value so it could be,
<input class="user_input" type="text" name="logEmailAddress" value="">
or just
<input class="user_input" type="text" name="logEmailAddress">

As you have specified
<input class="user_input" type="text" name="logEmailAddress" value=" ">
so whenever you enter some value in the text-field like abc and when you do
String email = request.getParameter("logEmailAddress");
email shall give you initialspace+abc
so change
<input class="user_input" type="text" name="logEmailAddress" value=" ">
to
<input class="user_input" type="text" name="logEmailAddress" value="">

Related

Why is it that my form does not redirect me to the route im passing?

Im doing a CRUD app with Java using Servlets and i have a jsp file as a list of many users where i have a button to edit my row. As i click on my button it should redirect me to ServletPacientes?Param=editar&dni=<%a.getDni()%>.
So this is my ListarPacientes.jsp: Where i have some scriplets and my html forms.
<body>
<% if (request.getSession().getAttribute("usuario") == null) {
request.getRequestDispatcher("Login.jsp").forward(request, response);
throw new UsuarioNoLoggeadoException();
}
Usuario user = (Usuario)request.getSession().getAttribute("usuario");
if (user.getTipo_usuario().getID() != 1) {
request.getRequestDispatcher("Home.jsp").forward(request, response);
throw new UsuarioSinPermisoException();
}
%>
<%
if (request.getParameter("buscarLista") == null) {
request.getRequestDispatcher("ServletPacientes?Param=list").forward(request, response);
}
List<Paciente> listaM = new ArrayList<Paciente>();
if (request.getAttribute("listaPac") != null) {
listaM = (List<Paciente>)request.getAttribute("listaPac");
}
%>
<jsp:include page="Menu.jsp"></jsp:include>
<div class="table-title">
<h3>Tabla Pacientes</h3>
</div>
<form method="post" action="ServletPacientes">
<div class="form-group">
<label>Buscar: </label>
<input type="text" class="form-control" name="txtBuscar">
</div>
<div class="col-12">
<input type="submit" class="btn btn-success" value="Buscar" name="btnBuscar">
</div>
<table class="table-fill">
<thead>
<tr>
<th class="text-left">Nombre</th>
<th class="text-left">Apellido</th>
<th class="text-left">DNI</th>
<th class="text-left">Sexo</th>
<th class="text-left">Direccion</th>
<th class="text-left">Fecha de Nacimiento</th>
<th class="text-left">Email</th>
<th class="text-left">Telefono</th>
<th class="text-left">Nacionalidad</th>
</tr>
</thead>
<tbody class="table-hover">
<tr>
<%
for (Paciente a : listaM) {
%>
<tr>
<form action="ServletPacientes" method="post">
<td><%=a.getNombre()%></td>
<td><%=a.getApellido()%></td>
<td><%=a.getDni()%> <input type="hidden" name="dniPaciente" value="<%=a.getDni()%>" ></td>
<td><%=a.getSexo()%></td>
<td><%=a.getDireccion()%></td>
<td><%=a.getFechaNac()%></td>
<td><%=a.getCorreo()%></td>
<td><%=a.getTelefono()%></td>
<td><%=a.getNacionalidad()%></td>
<td> <input type="submit" name="btnEliminar" value="Eliminar" class="btn btn-danger"></td>
</form>
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
</tr>
<%
}
%>
</tbody>
</table>
<br>
<div align="center">
</div>
</form>
</body>
As you can see i have de following tags
<td> <input type="submit" name="btnEditar" value="Editar" class="btn btn-warning"></td>
So in each row i have this button where i call my Controller (Servlet) with the parameter "editar" and i pass the method getDni() of my class Paciente.
And here is my code of my ServletPacientes:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("Param")!=null)
{
String opcion = request.getParameter("Param").toString();
switch (opcion) {
case "previoInsert":
{
break;
}
case "list":
{
request.setAttribute("listaPac", negPac.listarPacientes());
RequestDispatcher dispatcher = request.getRequestDispatcher("/ListarPacientes.jsp?buscarLista=1");
dispatcher.forward(request, response);
break;
}
case "editar":
{
Paciente p = new Paciente();
p = negPac.obtenerUno(request.getParameter("dniPaciente"));
System.out.println(p);
request.setAttribute("dniPac", p);
RequestDispatcher dispatcher = request.getRequestDispatcher("/EditarPaciente.jsp");
dispatcher.forward(request, response);
break;
}
default:
break;
}
}
}
The method above shows a switch where each case is a different parameter that im passing to my route. So when i click on my edit button instead of taking me to for example ServletPacientes?Param=editar&dni=20216447 it just redirects me to ServletsPacientes which is a blank page.
It looks like im never receiving the parameter editar neither the dni property. Becaus if i manually put on my url ServletPacientes?Param=editar&dni=20216447 it does takes me to the Edit view.
You essentially have the following structure:
<form method="post" action="ServletPacientes">
<a href="ServletPacientes?Param=editar&dni=<%=a.getDni()%>">
<input type="submit" value="Editar">
</a>
</form>
This means that when you click on this "Editar" button, a form submission will happen as a POST request. This request is supposed to be processed by a doPost method on the servlet side, and the URL would be /ServletPacientes. This is why you navigate to /ServletPacientes. The link in the wrapping <a> element will have no effect.
If you expect to navigate to something like ServletPacientes?Param=editar&dni=20216447, you'll have to make the nested input element a regular button, not a submit: <input type="button" value="Editar">.

How to preserve values of fields on jsp page when jsp is calling servlet and redirecting back to same jsp

I have a one welcome.jsp page where I am collecting few information and with the help of HTML FORM sending this request and response object to servlet to insert data into DB, so after this operation I want to go back to the same Welcome.jsp, but when I tried to use the
RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);
I lost all the populated values on the same Welcome.jsp,
So please suggest is there a way where I can send the existing request and response object with new request and response to the servlet and will send back old request and response object from servlet to JSP.
So below is code from "Welcome.jsp"
<!DOCTYPE html>
<%#page import="***********"%>
<%#page import="java.io.Console"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.util.ArrayList"%>
<html>
<head>
<title>Treatment Dashboard</title>
<meta charset="utf-8" />
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- <script type="text/javascript">
function noBack()
{
window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function(evt) { if (evt.persisted) noBack() }
window.onunload = function() { void (0) }
</script> -->
</head>
<body>
<%
HttpSession sessions = request.getSession();
String lanId = (String)sessions.getAttribute("lanid");
System.out.println("session Lanid:- " + lanId);
%>
<!-- Codrops top bar -->
<div class="codrops-top">
<a>
<strong> VALUES </strong>
</a>
<span class="right">
<strong> VALUE </strong>
</span>
<div class="menu-area">
<div id="dl-menu" class="dl-menuwrapper">
<button class="dl-trigger">Open Menu</button>
<ul class="dl-menu">
<li>Profile</li>
<li>Weekends Shift</li>
<li>Comp Off</li>
<li>Log Off</li>
</ul>
</div>
</div>
<!-- intro area -->
<div id="intro">
<div class="intro-text">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<div class="brand">
<%
String fname = (String) request.getAttribute("fname");
String lname = (String) request.getAttribute("lname");
String emailid = (String) request.getAttribute("emailid");
String ext = (String) request.getAttribute("ext");
String rmlanid = (String) request.getAttribute("rmlanid");
String role = (String) request.getAttribute("role");
String ipadd = (String) request.getAttribute("ipadd");
String wcounts = (String) request.getAttribute("weekendsCount");
String acocounts = (String) request.getAttribute("appliedCompOff");
String rcocounts = (String) request.getAttribute("remainingCompOff");
String pacocounts = (String) request.getAttribute("appliedCompOffPendingApprovalcount");
%>
<table style="width:100%" >
<tr>
<td>
<label for="userName" class="uname" data-icon="u"> Name :- </label>
</td>
<td>
<label for="userName" class="uname" data-icon="u"><%=fname%> <%=lname%></label>
</td>
</tr>
<tr>
<td>
<label for="userEmail" class="email" data-icon="u"> Email :- </label>
</td>
<td>
<label for="userEmail" class="email" data-icon="u"><%=emailid%> </label>
</td>
</tr>
<tr>
<td>
<label for="userExt" class="ext" data-icon="u"> EXT :- </label>
</td>
<td>
<label for="userExt" class="ext" data-icon="u"><%=ext%> </label>
</td>
</tr>
<tr>
<td>
<label for="userRmlanid" class="rmlanid" data-icon="u"> RM Lan-Id :- </label>
</td>
<td>
<label for="userRmlanid" class="rmlanid" data-icon="u"><%=rmlanid%> </label>
</td>
</tr>
<tr>
<td>
<label for="userIpadd" class="ipadd" data-icon="u"> TechM Machine IP :- </label>
</td>
<td>
<label for="userIpadd" class="ipadd" data-icon="u"><%=ipadd%> </label>
</td>
</tr>
<tr>
<td>
<label for="userWeekendsNumber" class="weekends" data-icon="WND"> Worked ON Weekends :- </label>
</td>
<td>
<label for="userWeekendsNumber" class="weekends" data-icon="WND"> <%=wcounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffApplied" class="compoff" data-icon="u"> Applied Comp Off :- </label>
</td>
<td>
<label for="userCompOffApplied" class="compoff" data-icon="u"> <%=acocounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffAvailed" class="compoff" data-icon="u"> Remaining Comp Off :- </label>
</td>
<td>
<label for="userCompOffAvailed" class="compoff" data-icon="u"> <%=rcocounts%> </label>
</td>
</tr>
<tr>
<td>
<label for="userCompOffPendingApproval" class="compoff" data-icon="u"> CompOff Pending For Approval :- </label>
</td>
<td>
<label for="userCompOffPendingApproval" class="compoff" data-icon="u"> <%=pacocounts%> </label>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Update"/>
<!-- <input type="submit" value="Cancel"/> -->
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Weekend Shift -->
<section id="WeekendsShift" class="home-section bg-white">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<form method = "post" action="AddWeekendsShiftDetails" autocomplete="on" >
<div class="brand">
<table style="width:100%" >
<tr>
<td>
<p> <br><br><br>
<label for="weekendDetails" class=""> Worked On Weekend :- </label>
</p>
</td>
<td>
<p><br><br><br>
<input type="text" id= "datepicker1" placeholder="Weekend Date" name="pickedDate"/>
<script>
var datepicker = $("#datepicker1").datepicker({
dateFormat: 'yy-mm-dd',
changeMonth: true,
changeYear: true
}).val();
</script>
</p>
</td>
</tr>
<tr>
<td>
<p> <br>
<label for="processname" class="uname" data-icon="PN" > Process Name :- </label>
</p>
</td>
<td>
<p> <br>
<input id="processname" name="processname" required="required" type="text" placeholder="ex:-BAC"/>
</p>
</td>
</tr>
<tr>
<td> </td>
<td>
<p> <br>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</p>
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!-- Comp Off -->
<section id="compoff" class="home-section bg-white">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="intro-data">
<form method = "post" action="AddCompOffDetails" autocomplete="on" >
<div class="brand">
<%
final String USER_WEEKENDS_COMPOFF_DETAILS_QRY = "SELECT WEEKEND_DATE FROM tbl_weekend_rota WHERE (LANID= ? and IS_COMPOFF_CONSUMED = 'N' and IS_APPROVED != 'P')";
Connection con = null;
con = DBConnection.createConnection();
PreparedStatement ps = null;
ps =con.prepareStatement(USER_WEEKENDS_COMPOFF_DETAILS_QRY);
ps.setString(1, lanId);
ResultSet rs = ps.executeQuery();
%>
<table style="width:100%" >
<tr>
<td>
<p> <br><br><br>
<label for="userName" class=""> Apply CompOff :- </label>
</p>
</td>
<td>
<p><br><br><br>
<select name="compOffDate">
<option>-- Available CompOffs --</option>
<% while(rs.next()) { %>
<option><%=rs.getString(1)%></option>
<% } %>
<% con.close();%>
</select>
<p>
</td>
</tr>
<tr>
<td> </td>
<td>
<p><br>
<input type="submit" value="Apply"/>
<input type="reset" value="Reset"/>
<br><br>
</p>
</td>
</tr>
</table>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</body>
</html>
But when I clicked on Submit button it calls the AddWeekendsShiftDetails servlet,
So in this case this form will send its own request and response object right ?
So from the AddWeekendsShiftDetails servlet I'm inserting values to the Mysql DB
Below is the code from AddWeekendsShiftDetails servlet:-
package com.taskManagment.login;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Date;
//import javax.servlet.RequestDispatcher;
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("/AddWeekendsShiftDetails")
public class AddWeekendsShiftDetails extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddWeekendsShiftDetails() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sDate = request.getParameter("pickedDate");
String processName = request.getParameter("processname");
try {
Date sqlDate=Date.valueOf(sDate);
Connection con = null;
con = DBConnection.createConnection();
String lanId = SessionDetails.getDetailsFromSession(request, "lanid");
System.out.println("session Lanid from Weekend Servlet:- " + lanId);
insertWeekendShiftDetails(con, lanId, processName, sqlDate);
con.close();
/*RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);*/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void insertWeekendShiftDetails(Connection con, String lanId, String processname, Date date ) {
PreparedStatement ps = null;
try {
String insertWeekendRotaDetails = "MY INSERT QUERY";
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
ps = con.prepareStatement(insertWeekendRotaDetails);
ps.setString(1, null); ps.setString(2, lanId);
ps.setDate(3, (java.sql.Date) date); ps.setString(4, processname);
ps.setString(5, "Y"); ps.setString(6, "N");
ps.setString(7, null); ps.setDate(8, null);
ps.setString(9, "N"); ps.setDate(10, sqlDate);
ps.setDate(11, null);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Now from the doPost when I want to go back to the "Welcome.jsp" with the code like
RequestDispatcher rs = request.getRequestDispatcher("Welcome.jsp");
rs.forward(request, response);
so it will send back the request and response object of the form which was called from the section
and because of which the other values on the fields are getting null,
So I want a way with which I can hold the old values on Welcome.jsp page.
before sending it back you need to set the attributes you want to the request. You can do that using request.setAttribute("attribute_name","attribute_value"); and the you can retrieve it by using request.getAttribute in the next page. For example
request.setAttribute("errorMsg", "Invalid data . Please correct the input data");
requestDispatcher = request.getRequestDispatcher("error.jsp");
requestDispatcher.forward(request, response);
And then in error.jsp you can use:
<%=request.getAttribute("errorMsg") %>

Java – How can I Log into a Website with HtmlUnit?

I am writing a Java program to log into the website my school uses to post grades.
This is the url of the login form: https://ma-andover.myfollett.com/aspen/logon.do
This is the HTML of the login form:
<form name="logonForm" method="post" action="/aspen/logon.do" autocomplete="off"><div><input type="hidden" name="org.apache.struts.taglib.html.TOKEN" value="30883f4c7e25a014d0446b5251aebd9a"></div>
<input type="hidden" id="userEvent" name="userEvent" value="930">
<input type="hidden" id="userParam" name="userParam" value="">
<input type="hidden" id="operationId" name="operationId" value="">
<input type="hidden" id="deploymentId" name="deploymentId" value="ma-andover">
<input type="hidden" id="scrollX" name="scrollX" value="0">
<input type="hidden" id="scrollY" name="scrollY" value="0">
<input type="hidden" id="formFocusField" name="formFocusField" value="username">
<input type="hidden" name="mobile" value="false">
<input type="hidden" name="SSOLoginDone" value="">
<center>
<img src="images/spacer.gif" height="15" width="1">
<script language="JavaScript">
document.forms[0].elements['deploymentId'].value = 'ma-andover';
</script>
<script language="JavaScript">
$(function()
{
$('form').attr('autocomplete', 'off');
var name = $('#username');
var password = $('#password');
name.attr('autocomplete', 'off');
password.attr('autocomplete', 'off');
if (name.val() == '')
{
password.attr('disabled','disabled');
}
});
</script>
<img src="images/spacer.gif" height="30" width="1">
<table border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td>
<div id="logonDetailContainer" class="logonDetailContainer">
<table border="0" cellpadding="0" cellspacing="0">
<tbody><tr>
<td>
<label style="text-align: center; margin-bottom: 0px">Andover Public Schools</label>
<img src="images/spacer.gif" height="10" width="1">
<hr class="logonHorizontalRule">
</td>
</tr>
<tr>
<td>
<img src="images/spacer.gif" height="10" width="1">
<input type="text" name="fakeuser" style="display: none">
<input type="password" name="fakepassword" style="display: none">
</td>
</tr>
<tr>
<td class="labelCell">
<label>Login ID</label>
<input type="text" name="username" tabindex="1" value="" onkeypress="$('#password').prop('disabled', false)" id="username" class="logonInput" autocomplete="off">
</td>
</tr>
<tr>
<td class="labelCell">
<label>Password</label>
<input id="password" type="password" name="password" tabindex="2" value="" class="logonInput" autocomplete="off" disabled="disabled">
<a href="javascript:EmbeddedPopup.popupManager.open('passwordRecovery.do?isSecondary=false&deploymentId=ma-andover', 400, 400, 100)" tabindex="5" style="float: right">
I forgot my password
</a>
</td>
</tr>
<tr>
<td width="1" class="logonTopPadding" style="float: left">
<input type="submit" tabindex="3" value="Log On" class="log-button">
</td>
</tr>
</tbody></table>
</div>
</td>
</tr>
</tbody></table>
</center>
<script>
setTimeout(function(){window.location.reload(true);}, 1800000);
</script>
</form>
I am trying to use the following code to log in:
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class LoginAttempt {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = (HtmlPage) webClient.getPage("https://ma-andover.myfollett.com/aspen/logon.do");
HtmlForm form = page.getFormByName("logonForm");
form.getInputByName("username").setValueAttribute("myUsername"); //works fine
form.getInputByName("password").setValueAttribute("myPassword"); //does not work
page = form.getInputByValue("Log On").click(); //works fine
System.out.println(page.asText());
}
}
The program fills the username box and clicks the "Log On" button, but it does not fill the password box. What can I change to make this program work? I suspect the "type = 'password'" attribute of the password box has something to do with the problem, but please correct me if I am wrong. Any help is appreciated. Thank you very much.
The target page: https://ma-andover.myfollett.com/aspen/home.do
And this is my output, in case it might be helpful:
Aspen: Log On
Aspen
About Aspen
Andover Public Schools
Login ID myUsername
Password I forgot my password
Log On
Copyright © 2003-2014 Follett School Solutions. All rights reserved.
Follett Corporation Follett Software Company Aspen Terms of Use
You must enter a password.
OK
The password field is disabled until you type something in the username field.
By setting the value in username doesn't trigger the event that manages the enabling of password field.
The below works
public static void main(String[] args) {
WebClient webClient = new WebClient();
try {
HtmlPage page = (HtmlPage) webClient
.getPage("https://ma-andover.myfollett.com/aspen/logon.do");
HtmlForm form = page.getFormByName("logonForm");
form.getInputByName("username").setValueAttribute("myUsername");
HtmlInput passWordInput = form.getInputByName("password");
passWordInput.removeAttribute("disabled");
passWordInput.setValueAttribute("myPassword");
page = form.getInputByValue("Log On").click(); // works fine
System.out.println(page.asText());
} catch (Exception e) {
e.printStackTrace();
} finally {
webClient.close();
}
}
The output is
Aspen: Log On
Aspen
About Aspen
Andover Public Schools
Login ID myUsername
Password I forgot my password
Log On
Copyright © 2003-2014 Follett School Solutions. All rights reserved.
Follett Corporation Follett Software Company Aspen Terms of Use
Invalid login.
OK
To automatically handle the JavaScript, you should use type() instead.
try (WebClient webClient = new WebClient()) {
HtmlPage page = (HtmlPage) webClient.getPage("https://ma-andover.myfollett.com/aspen/logon.do");
HtmlForm form = page.getFormByName("logonForm");
form.getInputByName("username").type("myUsername");
form.getInputByName("password").type("myPassword");
page = form.getInputByValue("Log On").click();
System.out.println(page.asText());
}
I used:
final WebClient webClient = new WebClient())
HtmlPage page = webClient.getPage("url");
((HtmlTextInput) page.getHtmlElementById("usernameID")).setText("Username");
page.getHtmlElementById("passwordID").setAttribute("value","Password");
page.getElementsByTagName("button").get(0).click();
System.out.println(page.asText());
I clicked the button that way because my button doesn't have an id, name, or value, but luckily its the only button on the page. So I just get all the button tags (all one of them) and select the first element in the List to click.

How can I display data on input tag using ajax?

Hi:) I want to display data on "input" when select "select option".
I included jsp page, which have "input" tag, so using ajax send data to included jsp page.
Here's my code. Name is "new_order.jsp"
<script>
$('select#product').change(function() {
var param = "code=" + $('#product').val();
$.ajax({
url : 'add_products/add_products.jsp',
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
data : param,
type : 'POST',
dataType : 'html',
success : function(data, textStatus, jqXHR){
}
});
});
...
</script>
<body>
<table class="add_products_tb table" data-toggle="table">
<tr>
..
</tr>
<tr>
..
</tr>
<tr>
<td>
..
</td>
<td>
<table>
<tr>
<td>
<select name="product" id="product" class="selectpicker" data-width="150px">
<option data-hidden="true">-Select-
<%
try {
query = "select * from new_product";
rs = stmt.executeQuery(query);
while (rs.next()) {
product_code = rs.getString("product_code");
%>
<option value="<%= product_code %>"> <%= product_code %>
<%
}
} catch (SQLException e) {
out.println(e);
} finally {
}
%>
</select>
</td>
</tr>
</table>
</td>
<jsp:include page="add_products/add_products.jsp" />
</tr>
</table>
</body>
The Next Code. This is included jsp, "add_product.jsp"
<script>
$(document).ready(function() {
$('select#product').change(function() {
<%
product_code = request.getParameter("code");
int size = 0;
try {
query = "select * from new_product where product_code='"+product_code+"'";
rs = stmt.executeQuery(query);
while (rs.next()) {
size = rs.getInt("sizes");
%>
$('#size').val("<%= size %>");
<%
}
} catch (SQLException e) {
out.println(e);
} finally {
}
%>
});
});
</script>
...
<body>
<td>
<input type="text" id="size" class="form-control" name="size" />
</td>
<td>
<input type="text" id="color" class="form-control" name="color" />
</td>
<td>
<input type="text" id="price" class="form-control" name="price" value="0" readonly />
</td>
<td>
<input type="text" id="quantity" class="form-control" name="quantity" value="1" />
</td>
<td>
<input type="text" id="total_price" class="form-control" name="total" value="0" readonly />
</td>
</body>
The Problem is, I want to receive the data, "code", from "new_order.jsp" and display the data on "add_product.jsp", but it doesn't display on the page. I also have debugging the page, the data is sent to "add_product.jsp", but didn't display on input.
I changed a variable "product_code", placed on "add_product.jsp" script, to value, not jsp variable but special value in DB. So, there is data on "input"! Just One....
I want to display using jsp variable. Please help me...T.T Thanks.

showing error message(invalid name or password) in same jsp page is not working

i have two jsp file index.jsp and login.jsp and profile.jsp.
here index.jsp has two text field name and password.
When I give right name and password login shows successful and go to success.jsp but when i give wrong password or name i want that an error message will show in same index page that is "invalid name or pass". my code is not working login.jsp is used for username and password authentication..please help me to solve this .
I have searched about RequestDispatcher but it is used in servlet class.but i want to do it in my jsp file.my code
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>JSP Example</title>
</head>
<body>
<form method="post" action="login.jsp">
<center>
<table border="1" width="30%" cellpadding="3">
<thead>
<tr>
<th colspan="2" align ="left">Login Here</th><h5><%=request.getAttribute("errorMessage") %></h5>
</tr>
</thead>
<tbody>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Yet Not Registered!! Register Here</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
login.jsp
<%# page import ="java.sql.*" %>
<%
String userid = request.getParameter("uname");
String pwd = request.getParameter("pass");
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
Statement st = con.createStatement();
ResultSet rs;
rs = st.executeQuery("select * from member where uname='" + userid + "' and pass='" + pwd + "'");
if (rs.next()) {
session.setAttribute("userid", userid);
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("success.jsp");
} else {
//out.println("Invalid password <a href='index.jsp'>try again</a>");
request.setAttribute("errorMessage", "Invalid user or password");
response.sendRedirect("index.jsp");
}
%>
In your else statement, don't use response.sendRedirect() because all the saved attributes will be lost as it's a new request, use requestDispatcher.forward() instead:
req.setAttribute("errorMessage", "Invalid user or password");
req.getRequestDispatcher("/index.jsp").forward(req, res);
The answer is in your code itself. For success you have used session.setAttribute so its working, and for login failed" you have used request.setAttribute that's why its not working. Go for session rather than request or user requestDispatcher to forward your request. And You have mansion that you used RequestDispatcher but its not working, it will not work unless you write complete statement like calling forward method of requestDispatcher.
you can do in index page in form
<div style="color:red">${errorMessage}</div>

Categories

Resources