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

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.

Related

Encryption method for cuba platform

Cuba has its own backend system to add users.
Now I need to write a user registration in the front-end.
The Cuba version I am using is 6.9
I know that this version of encryption is SHA1 : https://doc.cuba-platform.com/manual-6.9/login.html
Now my question is : I don't know how to set the encrypted password to the database.
I create an entity through the Metadata
User user = metadata.create(User.class);
user.setPassword(passWord);
I'm not sure that's the best option but I used the following code:
#Inject
protected PasswordEncryption passwordEncryption;
...
user.setPassword(passwordEncryption.getPasswordHash(user.getId(), password));
I think you just need to create html file with this code:
<div class="span6">
<h3>Login</h3>
<div th:if="${(param.error != null)}">
<p>Invalid username / password</p>
</div>
<form id="f" name="f" method="POST" action="login">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div>
<div>
<label style="width: 80px" for="login">Login</label>
<input type="text" id="login" name="login" value=""/>
</div>
<div>
<label style="width: 80px" for="password">Password</label>
<input type="password" id="password" name="password" value=""/>
</div>
</div>
<button type="submit">Login</button>
</form>
</div>
and then Request it from Controller:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Model model) {
if (PortalSessionProvider.getUserSession().isAuthenticated()) {
LoadContext l = new LoadContext(User.class);
l.setQueryString("select u from sec$User u");
model.addAttribute("users", dataService.loadList(l));
}
return "index";
}

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") %>

Form onSubmit() not being called after upgrade to Wicket 7

I'm in the process of upgrading our web app to use Wicket 7 (was using 6.19).
The first page is a login screen, but for some reason, the form's onSubmit() method isn't being called, so on clicking the submit button, I just get the login page re-displayed.
I've consulted the Wicket 7 migration guide, which doesn't mention any specific changes in this area.
It's a pretty straightforward case, as you can see, it's a simple form containing username and password fields
<form wicket:id="loginform" id="loginform" >
<table style="display: table; border: 0px; margin: auto;">
<tr style="display: table-row;">
<td class="login" colspan="2"><span wicket:id="feedback">Feedback</span></td>
</tr>
<tr style="display: table-row;">
<td class="login">
<label for="username"><wicket:message key="username">Username</wicket:message>: </label>
</td>
<td class="login">
<input wicket:id="username" id="username" type="text" name="user" value="" size="30" maxlength="50"/>
</td>
</tr>
<tr style="display: table-row;">
<td class="login">
<label for="password"><wicket:message key="password">Password</wicket:message>: </label>
</td>
<td class="login">
<input wicket:id="password" id="password" type="password" name="pswd" value="" size="30" maxlength="16"/>
</td>
</tr>
<tr style="display: table-row;">
<td class="login"> </td>
<td class="login"><input class="btn" type="submit" name="Login" value="Login" wicket:message="title:loginButtonTitle"/></td>
</tr>
</table>
</form>
Here's the Java code setting up the page components -
public class Login extends UnSecurePageTemplate {
private static final long serialVersionUID = -7202246935258483555L;
#SpringBean private IBrandingService brandingService;
#SpringBean private IRemonService remonService;
#SpringBean private IUserAdminService userAdminService ;
private static final Logger logger = LoggerFactory.getLogger( Login.class);
public Login() {
this(new PageParameters());
}
public Login(PageParameters pageParameters) {
super(pageParameters);
BrandingThemeProperties properties = brandingService.getBrandingThemeProperties();
String welcomeLabel = properties.getProperty("welcome-label");
add(new Label("welcome", welcomeLabel));
add(new Label("loginHeader", getStringFromPropertiesFile("loginInstruction", this)));
LoginForm form = new LoginForm("loginform", new SimpleUser(), pageParameters);
form.add(new FeedbackPanel("feedback"));
add(form);
}
And here's the Login form (the login() method authenticates the user and returns another page) -
public final class LoginForm extends Form<SimpleUser>
{
PageParameters pageParameters;
public LoginForm(String id, SimpleUser simpleUser, PageParameters pageParameters)
{
super(id, new CompoundPropertyModel<SimpleUser>(simpleUser));
this.pageParameters = pageParameters;
add(new TextField<String>("username").setRequired(true).add(StringValidator.maximumLength(50)));
add(new PasswordTextField("password").setResetPassword(true).add(StringValidator.maximumLength(50)));
}
/**
* Called upon form submit. Attempts to authenticate the user.
*/
protected void onSubmit()
{
SimpleUser user = getModel().getObject();
String username = user.getUsername();
String password = user.getPassword();
login(username, password, pageParameters);
}
}
I also tried using a submit Button, but its onSubmit() wasn't called either.

415 unsupported media type

I have got a form with file upload and sometimes I'm catching 415 unsupported media type with no messages in log. This is my form:
<form:form method="post" enctype="multipart/form-data"
class="form-horizontal" modelAttribute="massSMSForm"
style="width: 650px;">
<c:if test="${!empty errorFlag}">
<div class="alert alert-danger">
× <b>Ошибка.
</b>
<form:errors path="*" />
</div>
</c:if>
<div class="well" style="width: 650px;">
<table style="width: 100%">
<tr>
<td align="left"><b>Наименование рассылки*</b></td>
<td align="right"><form:input path="title" type="text"
class="form-control" id="title" style="width:340px;"
maxlength="15" /><br /></td>
<tr>
<td align="left"><b>Отправитель*</b></td>
<td align="right"><form:input path="from" type="text"
maxlength="15" class="form-control" id="from" style="width:340px;" /><br /></td>
</tr>
<tr>
<td align="left"><b>Дата начала рассылки</b></td>
<td align="right"><form:input id="deliveryDate"
path="deliveryDate" type="text" autocomplete="off"
class="form-control" placeholder="сейчас" style="width:310px;" /><br /></td>
</tr>
<tr>
<td align="left"><b>Срок жизни</b></td>
<td align="right"><form:input id="expiration" path="expiration"
type="number" min="1" max="72" autocomplete="off"
class="form-control" placeholder="в часах" style="width:310px;" /><br /></td>
</tr>
<tr>
<td align="left"><b>Файл рассылки*</b></td>
<td align="right"><input type="file" name="file"
accept="text/xml, text/plain" id="mass" /><br /></td>
</tr>
</table>
<br /> <b>Текст сообщения рассылки</b><br /> <br />
<c:choose>
<c:when test="${massSMSForm.ignore==false}">
<form:textarea path="message" class="form-control" rows="5"
id="message" placeholder="..." maxlength="500" />
</c:when>
<c:otherwise>
<form:textarea path="message" class="form-control" rows="5"
id="message" placeholder="..." disabled="true" maxlength="500" />
</c:otherwise>
</c:choose>
<br />
<form:checkbox path="ignore" id="ignoreBox" />
<small>Игнорировать сообщение</small>
</div>
<div style="text-align: right">
<a href="/${initParam['appName']}/userRole/"
class="btn btn-link btn-sm">Назад</a><input
class="btn btn-success btn-sm" type="submit" name="send"
onclick="myAlert()" value="Отправить" />
</div>
</form:form>
<script type="text/javascript">
function confirmSend() {
if (confirm("Отправляем сообщения?")) {
return true;
} else {
return false;
}
}
</script>
<script type="text/javascript">
jQuery('#deliveryDate')
.datetimepicker(
{
lang : 'ru',
i18n : {
ru : {
months : [ 'Январь', 'Февраль', 'Март',
'Апрель', 'Май', 'Июнь', 'Июль',
'Август', 'Сентябрь', 'Октябрь',
'Ноябрь', 'Декабрь', ],
dayOfWeek : [ "Вс", "Пн", "Вт", "Ср", "Чт",
"Пт", "Сб", ]
}
},
dayOfWeekStart : 1,
timepicker : true,
format : 'Y-m-d H:i'
});
</script>
<script type="text/javascript">
document.getElementById('ignoreBox').onchange = function() {
document.getElementById('message').disabled = this.checked;
};
</script>
And method:
#RequestMapping(value = "/sms/mass", method = RequestMethod.POST, headers = "content-type=multipart/form-data")
public String massSMSProcess(Map<String, Object> map,
#ModelAttribute("massSMSForm") MassSMSForm massSMSForm,
BindingResult result, HttpSession session) throws IOException {
session.removeAttribute(SESSION_KEY);
massSMSFormValidator.validate(massSMSForm, result);
if (result.hasErrors()) {
map.put("errorFlag", true);
return massSMSPage(map, massSMSForm, session);
} else {
try {
SMS sms = SmsBuilder.build(massSMSForm);
session.setAttribute(SESSION_KEY, sms);
map.put("title", "Подтверждение операции");
map.put("count", sms.getSmsEntityList().size());
} catch (IOException e) {
// mailer.send("/sms/mass :" + e.getMessage() + "form:"
// + massSMSForm);
map.put("error", "Ошибка ввода/вывода");
return distributionListPage(map);
}
return "confirmMassSMSPage";
}
}
What is wrong? Is it js problem or what? Should I add new headers? What's your thoughts?
No need to set headers in #RequestMapping. Post request from Form with enctype="multipart/form-data" is by default consider as a multipart request in Controller.
So here your request is multipart already, you just need to to add some maven repository for file upload to support your multipart-data.
Refer this Spring file upload documentation and Go through this example
Try to change :
headers = "content-type=multipart/form-data"
to :
consumes="multipart/form-data"
So your #RequestMapping will become like this :
#RequestMapping(value = "/sms/mass",
method = RequestMethod.POST,
consumes="multipart/form-data")
If you have not done this already, try adding multipartResolver bean in application context. Add this in application / servlet context xml file.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="100000"/>
</bean>
And supporting jar file commons-fileupload jar. Maven dependency for this jar is :
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
Try adding exception handler to the controller. It will help you to identify the real cause of the issue:
#ExceptionHandler({Exception.class})
public void resolveException(Exception e) {
e.printStackTrace();
}

Servlet works only for one jsp form

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="">

Categories

Resources