Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I could get my session values in my jsp, now I want to compare the session value whether it matches the textbox, if it matches, it will redirect the user to another page else it will remain the same page, I am not sure how to proceed, please help . Much thanks!
JSP
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
<%= session.getAttribute( "money" ) %>,
</form>
</body>
</html>
Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String text = request.getParameter("money");
int money = (Integer)session.getAttribute("money");
String testing = String.valueOf(money);
if(text == testing)
{
RequestDispatcher rd = request.getRequestDispatcher("MainPage");
rd.forward(request, response);
}
else
{
response.redirect("Errorpage.jsp");
}
Assuming that you have already got a Session attribute called "money", you would not need to access it from JSP
<body>
<form action="fact" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
</form>
</body>
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String text = request.getParameter("num");
int money = (Integer)session.getAttribute("money");
String testing = String.valueOf(money);
if(testing.equalsIgnoreCase(text))
{
RequestDispatcher rd = request.getRequestDispatcher("MainPage");
rd.forward(request, response);
}
else
{
response.sendRedirect("Errorpage.jsp");
}
}
If you have not created a Session attribute called "money" yet and want to create it in jsp, you have to use Scriptlet.
<body>
<form action="abc.do" method="POST">
Enter a number: <input type="text" name="num">
<input type="submit"/>
<% session.setAttribute("money",1000); %>,
</form>
</body>
Related
<html>
<head>
<title>Report Preview</title>
</head>
<body>
<div class="container">
<h2>Patient Data</h2>
<form action = "reportUpdate" method = "post" >
<input type="text" name="fvalue" value="testingData1"/>
<input type="text" name="svalue" value="testingData2"/>
<input type="submit" value="Submit"/>
</form>
</div>
<script type = "text/javascript" src = "main.js"></script>
</body>
</html>
I have a SpringBootProject and I'm using the above Freemarker code template file(*.ftl). I tried to display some input field with the values(binded), after editing I want to extract the data from HTML input tags(fvalue,svalue) to controller without using any model. How to get the values?
My controller code:
#PostMapping({ "/reportUpdate"})
public String reportToUpdate( ) {
String firstName = ""; // I should get fvalue here
String secondName = ""; // I should get svalue here
//Some other logics which will use above value.
return "Data saved!";
}
By using HttpServletRequest request, HttpServletResponse response we can get the data from HTML form.
Using the below code.
public void getDataFromForm(HttpServletRequest request, HttpServletResponse response) throws ServletException{
// Get the values from the request using 'getParameter'
String name = request.getParameter("name");
}
For more info, you can see this.
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I created a login form which as I wanted to practice ajax from JQUERY. Unfortunately this program is given me unexpected error.
ISSUE
Browser is given me 500 error : NullPointerException
So I printed username and password. Then I saw that for one button click username and password print for two times and for first time it is same values as I entered and second time username is Null password is similar to entered value.And other thing is although I commented out the Ajax part that second scenario is happening (null username and entered password printing)
JSP:
<form action="" style="border:1px solid #ccc" method="post">
<div class="container">
<h2>LogIn Form</h2>
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" id="uName" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" id="psw" required>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn" id="login">LogIn</button>
</div>
</div>
</form>
JQUERY
<script type="text/javascript">
$(document).ready(function() {
alert("qwqw");
$('#login').click(function(){
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
});
</script>
Servlet
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
//PrintWriter out = response.getWriter();
String userName = request.getParameter("uName");
System.out.println(userName+"uName");
String psw = request.getParameter("psw");
System.out.println(psw+"psw");
RequestDispatcher rd;
if(!userName.isEmpty()| userName != null){
rd = request.getRequestDispatcher("/Header.html");
rd.forward(request, response);
}else{
rd = request.getRequestDispatcher("/SignUp.jsp");
rd.forward(request, response);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException{
request.getRequestDispatcher("UserRegistration.jsp").forward(request,response);
}
Please help me to solve this issue..Thank you..!
I'd rather put an event handler on the "submit" event of the form, then call preventDefault() and stopPropagation() on the event:
$("#myform").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.post('userRegistrationServlet',{
uName : $('#uName').val(),
psw : $('#psw').val()},
function(responseText) {
alert(uName);
alert("Login Successfully..!");
});
});
this button type is 'submit' so when you click it your form will be submit coherently but no url path
LogIn
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
It's my first day trying servlets. It's just a simple login function, but I get an error that doesn't explain what I'm doing wrong. It just says
404: The requested resource is not available.
Here's my servlet:
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String key = "ole";
String username = request.getParameter("username");
String password = request.getParameter("password");
response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
And here's my login page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login page</title>
</head>
<body>
Enter username and password below.
<form method=get action="hej">
<input type="text" user="username" /> <input type="password"
user="password" /> <input type="submit" value="Login" />
</form>
</body>
</html>
There is a file called secret.jsp as well, but there's nothing interesting in there. I don't understand why it's returning 404. When I have remove the if statement it works... only then, there's not much function.
As you say it works without IF-ELSE then I guess your web.xml entry is correct.
First change this to
<input type="password" user="password" />
this
<input type="password" name="password" />
input tag does not have any user attribute , it's name.
Next mistake is , you are using session.getAttribute to access parameters that you have not set, yet.
Your code should be
if (username.equals(key)
&& password.equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
session.getAttribute can only be used when you have in your code session.setAttribute
example session.setAttribute("username","ole");session.setAttribute("password","ole");.
Then only you could get a value with session.getAttribute("username") OR session.getAttribute("password"). But right now it only returns NULL. So code won`t work.
You could add this code in your existing code and it will work.
session.setAttribute(username,username);
session.setAttribute(password,password);
Your complete code should be
String username = request.getParameter("username");
String password = request.getParameter("password");
session.setAttribute(username,username);
session.setAttribute(password,password);
//response.sendRedirect("NewFile.jsp");
if (session.getAttribute(username).equals(key)
&& session.getAttribute(password).equals(key)) {
response.sendRedirect("secret.jsp");
} else {
response.sendRedirect("NewFile.jsp");
}
Replace user="... by name="... in your HTML and it will work.
Replace user="... by name="... in your HTML and it will work. NullPointerException is thrown because because of the wrong HTML the request parameters are NULL and these are used for the session lookup.
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>
I wrote the following form and servlet , hoping that the servlet would return the value of the text field from the form , but it returns null instead. What should be corrected ?
<html>
<head>
<title>Simple form</title>
</head>
<body>
<form method="post" action="theServlet">
<input type="text" id="userName"/>
<input type="submit" value="Post"/>
</form>
</body>
</html>
public class theServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("userName");
response.setContentType("text/html");
PrintWriter writer=response.getWriter();
writer.println("<html>");
writer.println("userName = "+ username);
writer.println("</html>");
}
}
You should use name attribute instead of id to send parameters to the server.
<input type="text" id="userName" name="username" />