This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 3 years ago.
I have a JSP which will let a user register for an account at my website. If the user submits wrong or illegal info into the JSP, then I want to return the same JSP with an appropriate error message next to/above each wrongly filled (form) fields.
If possible, highlight the wrongly filled form field - this feature is not necessary though.
I have given a sample below to show what I need. I understand that the sample must be using something like javascript, but I don't know all that client side scripting. I only want to use JSP to do it. As I said, I want to sort of return the JSP form to the user after marking all the mistakes and how to correct them.
How do I do this ? I only need some initial direction. I will make the code myself and post it here later.
Thanks.
EDIT - I don't want the drop down box. I don't want red borders around wrongly entered fields. I only want to display the error messages (in red color) next to the relevant fields.
Here is some sample code -
<%# page language="java" contentType="blah..." pageEncoding="blah..."%>
<!DOCTYPE html PUBLIC "blah...">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user"><br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
RegServlet -
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
static String okUser = "loser";
public RegServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(user.equalsIgnoreCase(okUser) == false){
//Do something MAGICAL to set an error next to username field of Form.jsp, then forward.
RequestDispatcher view = request.getRequestDispatcher("/jsp/Form.jsp");
view.forward(request, response);
}
}
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Validation</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<!-- or download to a directory -->
<!-- <script src="js/jquery-1.9.1.js"></script> -->
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#user').change(function() {
var userName = jQuery(this).val();
jQuery.ajax({
type : 'GET',
url : 'AjaxUserCheck',
data : {user:userName},
dataType : 'html',
success : function(data) {
if(jQuery.trim(data)=='1')
{
jQuery("#userLabel").html("Sorry! username is taken");
//write other stuff: border color ...
}
else if(jQuery.trim(data)=='0')
jQuery("#userLabel").html("user name available");
else
alert(data); //possible error
},
error : function(xhr,status,error){
console.log(xhr);
alert(status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action = "/RegServlet">
user name: <input type="text" name="user" id="user">
<label id="userLabel"></label>
<br>
password : <input type="password" name="pwd">
</form>
</body>
</html>
---------Servlet------
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
//if(dao.isUserExist(user)){
if(user.equals("java")){ // check for db if userid exists in DB print '1' else '0'
out.print("1");
}
else
out.print("0");
have the page post to itself, like this login.jsp fragment:
<div class="error">
<%
String usrName = "" + request.getParameter("username");
String usrPass = "" + request.getParameter("password");
if (isValid(usrName,usrPass){
openUserSession(usrName); //here you open a session and set the user, if the session doesn't have an user redirect to login.jsp
response.sendRedirect("index.jsp"); //user ok redirect to index (or previous page)
} else {
out.print("Invaid user or password");
}
%>
</div>
<form action="login.jsp" method="POST"> <!-- login.jsp post to itself -->
<input type="text" name="username" id="username"/>
<input type="password" name="password" />
<input type="submit" value="login" name="login" />
<input type="submit" value="register" name="register" />
</form>
Related
I keep getting the error This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 405
I created a signup form. but when I submit, it doesn't show the action page.
**In html:
**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student Signup Form</title>
<link rel="stylesheet" href="\assets\css\main.css">
</head>
<body>
<nav class="flex-container">
<div class="one"><img src="\assets\images\vanierlogo.jpg" alt="logo"></div>
<div class="two"><a href=\signup.html>Signup</a></div>
<div class="three">Login</div>
</nav>
<div id="txtHint"></div>
<form>
<h3>Create New Student Account</h3><br><br>
<label for="username">Student ID: </label>
<input type="text" id="username" name="username" required><br><br>
<label for="firstName">First Name: </label>
<input type="text" id="firstName" name="firstName"><br><br>
<label for="lastName">Last Name: </label>
<input type="text" id="lastName" name="lastName"><br><br>
<label>Enter Password<sup>*</sup>: </label>
<input type="password" autocomplete="passwd" name="passwd" required><br><br>
<label>Confirm Password: </label>
<input type="password" autocomplete="passwd1" name="passwd1" required><br><br>
<label>Are you Full-Time or Part-Time?</label><br><br>
<label for="Full-Time">Full-Time</label>
<input type="radio" id="Full-Time" name="status" value="Full-Time">
<label for="Part-Time">Part-Time</label>
<input type="radio" id="Part-Time" name="status" value="Part-Time"><br><br>
<input type="submit" onclick="createAccount(this)" value="Sign Up!"><br><br>
<footer>* Password must be at least 3 characters in length</footer>
</form>
<script src="\assets\js\main.js"></script>
</body>
</html>
In main.js:
function createAccount(element) {
const currForm = element.closest('form');
const params = "username="+currForm.elements[0].value +
"&firstName="+currForm.elements[1].value +
"&lastName="+currForm.elements[2].value +
"&passwd="+currForm.elements[3].value +
"&passwd1="+currForm.elements[4].value +
"&status="+currForm.elements[5].value;
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:80/SignupHandlingServlet",true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhttp.readyState == 4) {
alert("DONE");
alert(xhttp.status);
if (xhttp.status==409 || xhttp.status==417 || xhttp.status==200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
else {
alert(xhttp.method);
let response = JSON.parse(xhttp.responseText);
document.querySelector("#ipText").innerHTML = response.ip;
}
}
else if (xhttp.readyState==0) {
alert("request unsent");
} else if (xhttp.readyState==1){
alert("request OPENED");
} else if(xhttp.readyState==2) {
alert("request HEADERS_RECEIVED");
} else {
alert("The HTTP request response is being downloaded");
}
}
}
**In web.xml:
**
<web-app>
<servlet>
<servlet-name>SignupHandlingServlet</servlet-name>
<servlet-class>SignupHandlingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SignupHandlingServlet</servlet-name>
<url-pattern>/SignupHandlingServlet</url-pattern>
</servlet-mapping>
</web-app>
**In java:
**
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
#WebServlet("/SignupHandlingServlet")
public class SignupHandlingServlet extends HttpServlet {
/* Process the HTTP Post request */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Obtain parameters from the client
String username = request.getParameter("username");
String passwd = request.getParameter("passwd");
if (Interpreter.usernameExists(username)) {
out.println("<br><br>That username already exists.<br>");
response.setStatus(417);
}
else if (!passwd.equals(request.getParameter("passwd1"))) {
out.println("<br><br>Please confirm password<br>");
response.setStatus(409);
}
else {
String lastName = request.getParameter("lastName");
String firstName = request.getParameter("firstName");
String status = request.getParameter("status");
Student CreateStudent = new Student(username, passwd, firstName, lastName, status);
Interpreter.saveStudentCredentials(CreateStudent);
out.println("<br><br>Account created successfully<br>");
response.setStatus(200);
}
out.close(); // Close stream
}
}
Any help please? it's my 1st front end school project. It's been long debugging this error with no success.
I was expecting a createAccount page with result of the doPost() printed out.
click here to view my folder structure
When submitting a form, only input fields with the name attribute are submitted.
For inputs 'username', 'new-password' and 'new-password1', there is no name attribute and hence no data sent to server. So, accessing 'passwd' variable (which is null) with equals method will throw 'NullPointerException'.
Hello, im working on a project in the university, and im stuck on an error.
Im working on a mypage feature, where you can update your old password, when you are looged in. The problem is that ChangepasswordServlet is not doing what it is supposed to do.
Here you can see my servlet, the problem is probably somewhere in the IF sentence. (Manager=Entitymanager)
#WebServlet(name = "ChangePasswordServlet", urlPatterns = {"/ChangePassword"})
public class ChangePasswordServlet extends HttpServlet {
#EJB
UserManagerLocal manager;
private void changePassword(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loggedInUsersUsername = request.getRemoteUser();
/* PrintWriter writer = response.getWriter(); */
User userFromTheDB = manager.getUser(loggedInUsersUsername);
String oldPasswordFromDB = userFromTheDB.getPassword();
String oldPasswordFromForm = (String) request.getAttribute("theOldPW");
;
String newPasswordFromForm = (String) request.getAttribute("theNewPW");
String newPasswordToCheckFromForm = (String) request.getAttribute("theNewPWCheck");
try {
if (oldPasswordFromDB.toLowerCase().equals(oldPasswordFromForm.toLowerCase()) && newPasswordFromForm.toLowerCase().equals(newPasswordToCheckFromForm.toLowerCase())) {
userFromTheDB.setPassword(newPasswordFromForm);
manager.updateUser(userFromTheDB);
response.sendRedirect("/Slit/MyPage/PasswordSucsess.jsp");
} else {
response.sendRedirect("Slit/Error/error.jsp");
}
}
catch (NullPointerException en) {
PrintWriter print = response.getWriter();
print.println("nullpointeryes");
print.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
#Override
protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
changePassword(request, response);
}
so
Here is my JSP with the form
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<head>
<title>Her kan du endre ditt nåværende passord</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css"
href="/Slit/Templates/CSS/MainPageTemplate.css">
</head>
<body>
<title>Slit</title>
<div>
<div class="form">
<form method="post" action="/Slit/ChangePassword">
<input type="Password" name="theOldPW" placeholder="Gammelt
Password"/>
<input type="Password" name ="theNewPW" placeholder="Nytt
Password"/>
<input type="Password" name ="theNewPWCheck" placeholder=" Nytt
Password på nytt"/>
<input type="submit" name="ByttePassord" value="Trykk her for å bytte
passord!"/>
</form>
</div>
</div>
</body>
</html>
</head>
<body>
</body>
So im getting nullpointer after i have filled in the form with the old and the new password.
If im running the code now, im getting the "nullpointeryes" error.
Edit:
This is the console error after filling in the form:
12:39:37,194 INFO [stdout] (default task-12) Hibernate: select
user0_.username as username2_3_0_, user0_.fName as fName3_3_0_, user0_.lName
as lName4_3_0_, user0_.password as password5_3_0_, user0_.DTYPE as
DTYPE1_3_0_ from User user0_ where user0_.username=?
Thanks for any answers
After hours i figured that i used get.attribute instead of parameter :/
String newPasswordFromForm = (String) request.getParameter("theNewPW");
String newPasswordToCheckFromForm = (String)
request.Paramter("theNewPWCheck");
I am new to Ajax, Jquery, JSON stuff. I have created one login page in jsp servlet technology. On login page, when user presses submit button, data gets collected in JSON and transferred to controller through AJAX. Now, in controller if on some condition, login name found to be correct, then it should use RequestDispatcher to dispatch it to success page. However if condition not satisfied, then it should write the message in JSON object and return it as content type json. Now the problem is that I am able receive JSON data on controller, but not able to redirect on success and also not able to show alert box to user if he entered wrong data. Below are the files:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script>
function validateAndSet()
{
var jsonRequest = {};
var login_name = $.trim($('#loginName').val());
var password = $.trim($('#password').val());
if(login_name=='' || login_name.length==0 ){
alert("Please enter login name.");
$('#loginName').focus();
return false;
}
if(password=='' || password.length==0 ){
alert("Please enter password.");
$('#password').focus();
return false;
}
jsonRequest["login_name"] = login_name;
jsonRequest["password"] = password;
return jsonRequest;
}
</script>
</head>
<body>
<jsp:include page="commonResources/Header.jsp">
<jsp:param value="none" name="headerMenu"/>
</jsp:include>
<script>
$(document).ready(function(){
$("#but").click(function(){
var formData=validateAndSet();
var strUrl="rwcntrlr.do?action=loginForm";
$.post(strUrl, {jsonData: JSON.stringify(formData)},function(response){
response = jQuery.parseJSON( response);
if(response.status=='NOT OK')
{
alert("not ok");
}
else{
alert('OK');
}
});
});
});
</script>
<br><br>
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<div class="container-fluid">
<div class="panel panel-default" id="p1">
<div class="panel-heading"><h3>Login</h3></div>
<div class="panel-body">
<center>
<table>
<tr>
<td height="50">LoginName:</td><td height="50"><input type="text" id="loginName" name="loginName"/></td>
</tr>
<tr>
<td height="20">Password:</td><td height="20"><input type="password" id="password" name="password"/></td>
</tr>
<tr><td height="50" colspan="2" align="right"><input type="submit" id="but" name="subBut" value="Go>" /></td></tr>
</table>
</center>
</div>
</div>
</div>
</div>
<div class="col-sm-4"></div>
</div>
</body>
</html>
controller servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String formName=request.getParameter("action");
if(formName.equalsIgnoreCase("loginForm")){
String strJSONData = request.getParameter("jsonData");
System.out.println(strJSONData);// data received correctly...
JSONObject jsonResponse = new JSONObject();
try{
JSONObject requestedJSONObject = new JSONObject(strJSONData);
String login_name = requestedJSONObject.getString("login_name");
String password = requestedJSONObject.getString("password");
if(login_name.equalsIgnoreCase("u2")){
RequestDispatcher rd=request.getRequestDispatcher("employeeSection/employeeDailySheet.jsp");
response.setContentType("text/html");
rd.forward(request, response);
}
else{
jsonResponse.put("status", "NOT OK");
response.setContentType("application/json");
response.getWriter().write(jsonResponse.toString());
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
When I presses submit button on login.jsp, nothing happens. No console error is shown. What should I do to resolve this problem.
Everything is working fine else why RequestDispatcher showing source code of page?
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String uName=req.getParameter("uEmail");
String uPass=req.getParameter("uPass");
try{
DBConnection con=new DBConnection();
if(con.login(uName, uPass)){
HttpSession on = req.getSession();
on.setAttribute("u_id", uName);
res.sendRedirect("dashboard.jsp");
}
else{
RequestDispatcher dis= getServletContext().getRequestDispatcher("/login.jsp");
PrintWriter write = res.getWriter();
write.println("Wrong Username or Passowrd");
dis.include(req, res);
}
}catch(ClassNotFoundException | SQLException e){}
}
}
Page redirecting fine to given url /login.jsp and also showing the error message, but why as source code?
Wrong Username or Passowrd
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="LoginServlet" method="POST" />
<input type="text" name="uEmail" />
<br /><br />
<input type="text" name="uPass" />
<br /><br />
<input type="Submit" name="Register" value="Register" />
<br /><br />
</form>
</body>
</html>
direct link to login.jsp works fine.
from http://docs.oracle.com/javaee/6/api/javax/servlet/RequestDispatcher.html#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
The include method of Request Dispatcher gets the content of the resource that why you are getting the source code in browser.
I think what you want to do is forward the request to login.jsp so use forward method of request dispatcher.
As #JBNizet mentioned in his comment due to your message from Servlet, HTML is going to be invalid.
before dis.include(req,res);
add this line res.setContentType("text/html); it
I was facing the same issue when I used RequestDispacther method and try to return and String massage along with html page then i have found you have to put some kind of tag to the String massage like then use include method
so if my code was
out.println("Terms & Condition not accepted");
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
i changed it to "
out.println("<h1>Terms & Conditions not accepted </h1>")
RequestDispatcher rd = request.getRequestDispatcher("index.html");
rd.include(request, response);
"
You need to set the content type of the response.
Add the below line in your doPost method.
response.setContentType("text/html;charset=UTF-8");
Hope it works for you!!
I have server and I should make request on button pressed also I have to call this method and when it is works I should parse json but my doesn't see controller method only main method is available
How to call
<input type="submit" onclick="#routes.Login.resp()" value="LOGIN" >
because it is not worrking Cannot resolve symbol
GET /login controllers.Login.main()
My controller:
package controllers;
import play.libs.F;
import play.libs.WS;
import play.mvc.Controller;
import play.mvc.Result;
public class Login extends Controller {
public static Result main() {
return ok(views.html.login.render());
}
public static F.Promise<Result> resp() {
String feedUrl="http://validate.jsontest.com/?json=%7B%22key%22:%22value%22%7D";
final F.Promise<Result> resultPromise = WS.url(feedUrl).get().flatMap(
new F.Function<WS.Response, F.Promise<Result>>() {
public F.Promise<Result> apply(WS.Response response) {
return WS.url(response.asJson().findPath("empty").asText()).get().map(
new F.Function<WS.Response, Result>() {
public Result apply(WS.Response response) {
return ok("size" + response.asJson().findPath("count").asInt());
}
}
);
}
}
);
return resultPromise;
}
}
view:
<!--
Author: W3layouts
Author URL: http://w3layouts.com
License: Creative Commons Attribution 3.0 Unported
License URL: http://creativecommons.org/licenses/by/3.0/
-->
<!DOCTYPE html>
<html>
<head>
<title>LOGIN</title>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/stylelogin.css")">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:600italic,400,300,600,700' rel='stylesheet' type='text/css'>
<!--//webfonts-->
</head>
<body>
<!-----start-main---->
<div class="main">
<div class="login-form">
<h1>Member Login</h1>
<div class="head">
<img src="#routes.Assets.at("images/user.png")" alt=""/>
</div>
<form>
<input type="text" class="text" value="USERNAME" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'USERNAME';}" >
<input type="password" value="Password" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Password';}">
<div class="submit">
<input type="submit" onclick="#routes.Login.main()" value="LOGIN" >
</div>
</form>
</div>
<!--//End-login-form-->
<!-----start-copyright---->
<!-----//end-copyright---->
</div>
<!-----//end-main---->
</body>
</html>
I am not sure if I also parse json properly,how to make proper GET,POST requests and parse it
As far as I know with the onclick attribute you always call a function in your JavaScript. If you want to specify an URL you need to put it into your form tag with an action attribute like <form action="#routes.Login.main()">.
The default for the HTML form tag is to send a GET. If you want to send a POST you have to specify it via an additional method="post" like <form action="#routes.Login.main()" method="post">. But then you have to change your routing too: POST /login controllers.Login.main(). If you want to post login data I'd strongly recommend to use POST because with GET your data including the password turns up in the query string of your URL.
Additionally your #routes.Login.main() method just returns the login view return ok(views.html.login.render());. Instead it should evaluate the form data you are sending.