How to display an error message from servlet? - html

I want to display an error message when the login and the password are wrong, I tried this attempt but it didnt't work, thanks.
index.html
<body>
<form action="Serv">
<input type="text" name="log">
<input type="password" name="pwd">
<input type="submit" value="send">
</form>
</body>
Serv.java
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String u =request.getParameter("log");
String p =request.getParameter("pwd");
if(u != "admin" && p!= "admin"){
String someMessage = "Error !";
getServletContext().getRequestDispatcher("/index.html").forward(request, response);
out.println("<html><head>");
out.println("<script type=\"text/javascript");
out.println("alert("+ someMessage +");</script>");
out.println("</head><body></body></html>");
}

Use single quotes inside when it is possible, try this:
String someMessage = "Error !";
out.println("<script type='text/javascript'>");
out.println("alert(" + "'" + someMessage + "'" + ");</script>");
out.println("</head><body></body></html>");

It looks like you are not closing the quote or script tag, add the closing quote/angle bracket:
out.println("<script type=\"text/javascript\">");

Related

I cant understant why the delete button does not work for me in jsp

This is my code:
AdminDelete.jsp:
<%# page import ="java.sql.*" %>
<%
String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub",
"root", "root");
Statement st = con.createStatement();
int t= st.executeUpdate("DELETE * FROM post WHERE(uid like'"+uid+"' AND content like'"+content+"')");
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
this is in the Admin's index:
<form method="send" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<% String content = request.getParameter("content");%>
<input type="button" value="delete" id="content">
</form>
I am trying to make a button that when i'm clicking on it, it delete's all of the posts in my website but when i click it, it dosen't do anything
I can not write entire answer in comment. So writing answer. As I mentioned in comment. You need to add space after LIKE. Also using PreparedStatement.
<%# page import ="java.sql.*" %>
<% String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM post WHERE uid like ? AND content LIKE ?");
ps.setString(1, "%" + uid + "%");
ps.setString(2, "%" + content + "%");
int t= ps.executeUpdate();
try {
con.close();
} catch(Exception e) {
e.printStackTrace();
}
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
One thing to note here is that you need to verify the UID is set in session and content is set in request parameters.
Also you have used method="send". Instead use method="POST".
<form method="POST" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<input type="text" name="content" />
<input type="submit" value="Delete" />
</form>
Suppose one record in DB has UID containing letter a and corresponding to this record content has value containing b. Now submit data with b as input in form and make sure UID in session has value set to a. It should work. If you come up with any error message let me know.

ASP Classic - Request.Form data has no value

I'm new to ASP. I'm using MSWindows Server 2008 x86 6.0.6002 to make simple "PersonalInformation" page.
Even though this is pathetic, please do not downvote.
But I've got a problem that cannot get value from Request.Form data.
Implementation here on TestHtml.html & TestAsp.asp.
TestHtml.html
<html>
<title>MultiPart FormData Test</title>
<header></header>
<body>
<form action="http://10.21.56.101/Test/TestAsp.asp" method="POST" enctype="multipart/form-data" name="MPDFTest" id="MPDFTest">
Name : <input name="ST_Name" type="text" id="ST_Name"/>
Sex : <input name="ST_Sex" type="text" id="ST_Sex"/>
Age : <input name="ST_Age" type="text" id="ST_Age"/>
Height : <input name="ST_Height" type="text" id="ST_Height"/>
SData : <input name="ST_SData" type="file" id="ST_SData"/>
<input name="ST_SendInfo" type="submit" value="SaveData" id="ST_SendInfo"/>
</form>
</body>
</html>
TestAsp.asp
<%
Option Explicit
Dim miName, miSex, miAge, miHeight
miName = Request.Form("ST_Name")
miSex = Request.Form("ST_Sex")
miAge = Request.Form("ST_Age")
miHeight = Request.Form("ST_Height")
Response.Write "---- Data Check ----<br>"
Response.Write "Name : " & miName & "<br>"
Response.Write "Sex : " & miSex & "<br>"
Response.Write "Age : " & miAge & "<br>"
Response.Write "Height : " & miHeight & "<br>"
If miName = "" Or miSex = "" Or miAge = "" Or miHeight = "" Then
Response.Write "Please check Name, Sex, Age, Height again!<br>"
Else
Response.Write "Data Saved.<br>"
End If
%>
As you see, this is a simple code.
But on TestAsp.asp, it doesn't get value from Request.Form data.
I always get string "Please check Name, Sex, Age, Height again!".
Why? and What's wrong on my code?
Someone please help me. Thank you in advance.
Remove enctype="multipart/form-data"
And replace name="ST_Age to name="ST_Age", and name="ST_Height to name="ST_Height".
To upload file use aspupload or asppdf and don't forget to add enctype="multipart/form-data" at the beginning of the form

Form will not send Information

So I have been sitting here racking my brain for a few hours and just cannot seem to find what I have wrong here. I am trying to get my form to send the information that the user inputs to my email. When I click send nothing happens... Anything would help! Thanks!
Here is the code I have atm:
Email me!
<div class="formCenter">
<form action="MAILTO:myemail#yahoo.com" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName"><br>
Last Name:<br>
<input type="text" name="lastName"><br>
Email:<br>
<input type="text" name="email"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
</div>
Okay so you have to send the Action to a page like Email.PHP (or ASP.net ect) which will process your POST variables.
Example:
<?php
$firstame = $_POST['firstName'];
?>
You then have to use Mail(), which will work on most servers but sometimes it won't so you can use a tool like PHPMailer which is an object orientated tool.
As you are providing the link as MAILTO, it opens up your local mail client to send an email with the POST variables listed, which is very unprofessional at best. You are better off having a link that goes to MAILTO for the time being, perhaps with a hidden value like or something like that, so when they open the client it automatically generates an email that they can just click. With that being said, you would keep your form layout as it is, but just swap out variables so they don't appear.
The reason you didn't see anything when you clicked Send is because even though your TYPE is a submit, you sometimes need the Value and/or Name to be Submit. Some browsers and servers will treat it differently, even frameworks like Bootsrap. If you change your name and value to Submit then change one back to Send to see what works for you, you can keep it in the Send format, given that it works.
I hope this helps.
you can try this one:
<?php
if($_POST["message"]) {
mail("your#email.address", "Form to email message", $_POST["message"], "From: an#email.address");
}
?>
see this page http://htmldog.com/techniques/formtoemail/
The form itself is not able to send the email. What the code does is prompts you to select email client software such as Outlook.
Did you check whether your email client software work properly? A reboot of machine is also a mean of troubleshooting.
JavaScript
function submitEmail() {
var fname = $.trim($("#txtfname").val());
var lname = $.trim($("#txtlname").val());
var email = $.trim($("#txtemail").val());
var comments = $.trim($("#txtComments").val());
if (isValidEmail(email) && (fname.length > 1) && (lname.length > 1)) {
$.ajax({
type: "POST",
url: "index.aspx/SubmitEmail",
data: "{'Email':'" + $.trim($("#txtemail").val()) + "'," + "'FName':'" + $.trim($("#txtfname").val()) + "'," + "'LName':'" + $.trim($("#txtlname").val()) + "'," + "'Comments':'" + $.trim($("#txtComments").val()) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != "null") {
var JsonObj = $.parseJSON(response.d);
if (JsonObj._Status == "OK") {
alert('Success Email :)')
}
else {
alert(JsonObj._Message);
}
}
},
failure: function (msg) {
alert(msg);
}
});
}
else {
return false;
}
}
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
<WebMethod()> _
Public Shared Function SubmitEmail(ByVal Email As String, ByVal FName As String, ByVal LName As String, ByVal Comments As String) As String
Dim _serializer = New JavaScriptSerializer()
Dim jSonRes As String = String.Empty
Dim MyString As New StringBuilder()
MyString.Append("First Name: " & FName).Append(Environment.NewLine)
MyString.Append("Last Name: " & LName).Append(Environment.NewLine)
MyString.Append("Email Address: " & Email).Append(Environment.NewLine)
MyString.Append("Comments: " & Comments).Append(Environment.NewLine)
Try
Dim Message As New Net.Mail.MailMessage("Do-Not-Reply#test.com", "myemail#yahoo.com")
Message.CC.Add("test#test.com,test#test.com")
Message.Subject = "New Request from " & FName & " " & LName
Message.IsBodyHtml = False
Message.Body = MyString.ToString()
Dim SmtpMail As New System.Net.Mail.SmtpClient
SmtpMail.Host = "localhost"
SmtpMail.Send(Message)
jSonRes = _serializer.Serialize(New With {._Status = "OK", ._Message = ""})
Catch ex As Exception
jSonRes = _serializer.Serialize(New With {._Status = "Error", ._Message = ex.Message})
End Try
Return jSonRes
End Function
<form action="index.aspx/submitEmail" method="post" enctype="text/plain">
First Name:<br>
<input type="text" name="firstName" id="fname"><br>
Last Name:<br>
<input type="text" name="lastName" id="lname"><br>
Email:<br>
<input type="text" name="email" id="txtemail"><br>
Comments:<br>
<textarea name="commentBox" rows="6" cols="40" id="txtComments"></textarea><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
This is the correct way to send a email. You can also use a php or C# code for sending a email. I have used vb.net code(webmethod) for sending email.

PHP getting data from HTML fields

I'm having some problems with getting data from HTML fields. This is how it looks in HTML
<form action="getInfo.php">
<span>Series</span>
<input class="searchFieldAlign" type="text" name="seriesName" /><Br>
<span>Volume</span>
<input class="searchFieldAlign" type="text" name="volumeName" /><Br>
<span>Nr</span>
<input class="searchFieldALign" type="text" name="issueNR" /><Br>
<p input class="searchFieldALign" type=submit></p>
</form>
This is my php script:
<?php
$seriesName = mysqli_real_escape_string($conn, $_POST['seriesName']);
$volumeName = mysqli_real_escape_string($conn, $_POST['volumeName']);
$issueNR = mysqli_real_escape_string($conn, $_POST['issueNR']);
$con=mysqli_connect("localhost","user","psswd","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where (seriesName='$seriesName') and (issueVolume='$volumeName') and (issueNR=$issueNR)");
$rowIssueInfo = mysqli_fetch_array($qryIssueInfo);
The problem is I don't get output from my query. There are no problems if i change it to this:
$qryIssueInfo = mysqli_query($con,"select issueNR, issueVolume, issueName, issueImageURL from issue, series where seriesName='Buffy, the Vampire Slayer' and issueVolume= 'Season 8' and issueNR=1");
If you not set form method = "post" it will be "get" and you should $_GET.
To correct:
<form method="post" action"getInfo.php">
Take it easy
The first version does not contain the apostrophes around the variables.
You should also consider security issues, like SQL injection.

Apostrophe (Smart Quote) in search throws Apache 400 Bad Request

I have a search form in my web application that throws an Apache 400 Bad Request error when you search using an apostrophe (smart quote, i.e. ’ not '). This happens when someone copy and pastes from Microsoft Word (which automatically converts tick marks to smart quotes).
The form causes a GET request which puts the search string in the URL. Even when I encode the string, it causes this error. What should I do to get this to work?
<script type="text/javascript">
function zend_submit_main() {
var query = $('#search_field').val();
if(query != '') {
var search_field = '/query/' + escape(query);
var url = '/search/results' + search_field + '/active-tab/contacts';
window.location = url;
}
return false;
}
</script>
<form id="search_form" method="GET" onsubmit="zend_submit_main(); return false;">
<input type="text" value="search by contact name" onFocus="if (this.value=='search by contact name') { this.value=''; }" onBlur="if (this.value=='') { this.value='search by contact name'; }" name="search_field" id="search_field" style="width:160px;" />
<input type="submit" value="Go" />
</form>
Use encodeURIComponent instead of escape:
var search_field = '/query/' + encodeURIComponent(query);
escape is not a standard function and does not encode the value according to the Percent-encoding as specified by RFC 3986. ’ for example is encoded as "%u2019.