How to know which button is clicked on jsp [duplicate] - java

This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
Closed 1 year ago.
Jsp with two buttons
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body style="background-color:black;">
<p>
<p><input type="button" name="good" value="Pen" onclick="location.href='hello';"> </p>
<p><input type="button" name="good" value="Paper" onclick="location.href='hello';">
</p>
</body>
</html>
This is the servlet
package pack.exp;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
#SuppressWarnings("serial")
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
String val=req.getParameter("good");
if("Pen".equals(val))
{
resp.setContentType("text/plain");
resp.getWriter().println("Pen was clicked" );
}
else if("Paper".equals(val))
{
resp.setContentType("text/plain");
resp.getWriter().println("Paper was clicked");
}
}
}
My code is not giving the correct output on clicking the buttons. I want when i click Pen then it should enter in if() and print the text and i want same for the paper button.

write this code in jsp, it will be helpful to you
<html>
<body style="background-color:black;">
<p><form method="post" action="hello">
<p><input type="submit" name="good" value="Pen" > </p>
<p><input type="submit" name="good" value="Paper" >
</p></form>
</body>
</html>

Add two hidden field.
<form id="my form" >
<input type="hidden" name="myPen" />
<input type="hidden" name="myPaper" />
<input type="button" name="good" value="pen" on click="{document.myform.mypen.value=this.value;location.href='hello';}"
<input type="button" name="good" value="paper" on click=" {document. myform. mypaper.value=this.value;location. href='hello';}" />
</form>
In Servlet
String val=req.getParameter('mypen');
String val1=req.getParameter("mypaper");
At time there is only one value other is null. You can do this with null check.

Use jQuery to do your task.
Change your html code to these lines of code.
<form method="post" action="#" name="Form" id="Form" >
<input type="button" value="one" id="One"/>
<input type="button" value="two" id="Two"/>
</form>
And add these lines in your script
$('input:button').click(function() {
alert($(this).val());
var value=$(this).val();
var url='hello?good=';
url+=value;
$("#Form").attr("action",url);
$("#Form").submit();
});
You can use jQuery 1.7.1 and above.

Encode the button's value into button's name.
In HTML:
<p><input type="button" name="good:Pen" onclick="location.href='hello';"> </p>
<p><input type="button" name="good:Paper" onclick="location.href='hello';">
In servlet: iterate over all parameters, look for parameter which startsWith("good") and if yes, subtrack the prefix good:. If there are no other submit buttons in your page, you can simply name your buttons just Pen and Paper and check the presence of these parameters as well. There is no javascript needed for this task.

Related

How can i call servlet from jsp (HTTP Status 404 – Not Found) [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 3 years ago.
I am making a login .JSP where on login button it called to login.java(servlet). But JSP is not able to call the servlet file and it gives an error.
Login.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Login.java(servlet file)
package com.login;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String uname=request.getParameter("uname");
System.out.print("uname is"+uname);
String upass=request.getParameter("upass");
if (uname.equals("meet") && upass.equals("1234")) {
response.sendRedirect("welcome.jsp");
}
else {
response.sendRedirect("login.jsp");
}
}
}
ERROR MESSAGE
HTTP Status 404 – Not Found
Type Status Report
Message /Login
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Simply you can use getConextPath in jsp request
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Wish i was helpfull; but regarding to BalusC using Scriptlets <% ... %> are officially discouraged since JSP 2.0 which was introduced in 2003(!!). Please do not encourage starters to use bad practices. The correct practice is to use EL ${ ... } instead. –
so you can write this way and always try to use it on this way
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="${requestScope.getContextPath}/Login" method="get">
Enter Username:<input type="text" name="uname"><br>
Enter Password:<input type="password" name="upass"><br>
<input type="submit" value="login">
</form>
</body>
</html>
Its better to know the bad coding and the write coding , wish i this help you too.

Save Form data after redirecting Servlet error message to JSP

I have a user login form which takes an error message when the password does not match the one in the database. I redirect the error message to the form as shown below, but when it shows the error message on the form it deletes the data on the email/password input fields. What can I do to still keep the data in the input fields after showing the error message? Thank you in advance.
//SERVLET REDIRECT TO JSP
request.setAttribute("errorMessage", "Wrong credentials!");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
//JSP FORM PAGE
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>User Log in</title>
</head>
<body>
<form action = "LoginServlet" method="POST">
<h3>Sign In</h3><br>
Email: <input type="text" name="email" required><br>
Password: <input type="password" name="pass" required><br>
<div style="color: #FF0000;">${errorMessage}</div><br>
<input type="submit" name="submit" value="Sign in">
</form>
</body>
</html>
I solved this by adding these few lines:
//SERVLET
request.setAttribute("email",request.getParameter("email"));
request.setAttribute("pass", request.getParameter("pass"));
request.setAttribute("errorMessage", "Wrong credentials!");
request.getRequestDispatcher("/Login.jsp").forward(request, response);
//JSP PAGE
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>User Log in</title>
<%# include file="PageHeader.html" %>
</head>
<body>
<form action = "LoginServlet" method="POST">
<h3>Sign In</h3><br>
Email: <input type="text" name="email" required value="${email}"><br>
Password: <input type="password" name="pass" required value="${pass}"><br>
<div style="color: #FF0000;">${errorMessage}</div><br>
<input type="submit" name="submit" value="Sign in" id="sButton">
</form>
</body>
</html>
Here's an example on how to achieve this with AJAX.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<title>User Log in</title>
<%# include file="PageHeader.html" %>
<!-- you need to include jquery for this example -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form action = "LoginServlet" method="POST" id="someform">
<h3>Sign In</h3><br>
Email: <input type="text" name="email" required><br>
Password: <input type="password" name="pass" required><br>
<div style="color: #FF0000;display:none" id="someMsg"></div><br>
<input type="submit" name="submit" value="Sign in" id="sButton">
</form>
<script>
//the following will ajaxify your form, all you have to do is add 'id="someform" to it
//reference here: https://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax
$(document).on("submit", "#someform", function(event) {
var $form = $(this);
$.post($form.attr("action"), $form.serialize(), function(response) {
//response is not empty (because it contains the error string message)
if(response){
//here we are using the response from the servlet to set the text of the div. .show() makes the element visible, .delay(1000) is a 1000ms delay for .fadeOut() which makes the element invisible after some time
$('#someMsg').text(response).show().delay(1000).fadeOut("slow");
}else{
//response here is empty (String error = "";), so we just redirect the user (because details match)
window.location = "Welcome.jsp";
}
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
</body>
</html>
include jquery to the head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
add id="someform" to your form
and id="someMsg" to your div (also make the display:none)
Then for your LoginServlet, try something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pass1 = request.getParameter("pass");
String email = request.getParameter("email");
String error = "";
//do whatever you need to do here, just don't do any forwarding
//here we check if the details are incorrect (!), javascript on the front end will decide whether to stay on the same page or redirect based on the value we send in error string.
if(!validate(email,pass1)){
//if details are wrong, lets send the following string:
error = "Your password or email is wrong and you should feel bad.";
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(error); // Write response body.
}
Let me know if it works for you

JSP requestDispacthing

I have two JSP pages. In first page I have given fields to fill personal details and I have written request.getRequestDispatcher("second.jsp") and forwarded the the request. But When I run the "first.jsp" on server in eclipse, it is directly going to "second.jsp" but in URL it is shopwing "first.jsp". What might be the problem?
First.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
<h2>Enter Your Personal Details</h2>
<form action="personal.jsp" method="get">
<table>
<tr><td>Name: </td><td> <input type="text" name="name" /><br /><br /></td></tr>
<tr><td>Email-ID: </td><td><input type="text" name="email" /><br /><br /></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dob" /><br /><br /></td></tr>
<tr><td>Password: </td><td><input type="text" name="pass" /><br /><br /></td></tr>
<tr><td>Age: </td><td><input type="text" name="age" /><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%!
String uname=null,pass=null,email=null;
String age=null,dob = null;
%>
<%
uname= request.getParameter("name");
session.setAttribute("username",uname);
pass= request.getParameter("pass");
session.setAttribute("password",pass);
age = request.getParameter("age");
session.setAttribute("age",age);
email = request.getParameter("email");
session.setAttribute("email",email);
dob = request.getParameter("dob");
session.setAttribute("dob",dob);
response.sendRedirect("academic.jsp");
%>
</body>
</html>
Second.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
<h2>Enter Your Academic Details</h2>
<form action="academic.jsp" method="get">
<table><tr><td>
MID: </td><td> <input type="text" name="mid" /><br /><br /></td></tr>
<tr><td>Marks: </td><td> <input type="text" name="marks" /><br /><br /></td></tr>
<tr><td>Salary: </td><td><input type="text" name="salary" /><br /><br /></td></tr>
<tr><td>Stream:</td><td><select name="stream"><option>Java</option><option>dotNET</option><option>Testing</option></select><br /><br /></td></tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
<%
out.println(session.getAttribute("name"));
%>
</body>
</html>
You need to do response.sendRedirect() to make the effect in url.
request#forward
Silently passes the control to your another resource,And happens on server side,browser doesn't know about it.
Forward():
For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.
sendRedirect()
Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.
Highlighting Luggis comment,that move your business logic to Controller and try to avoid scriplets too if possible.
Though,it is not recommended,If you want to change the URL and still want to access the data in second page,one possibility is that put data in session and access in second jsp.
The problem is generated because you have a direct call of forward method in a scriptlet, this might look like this
request.getRequestDispatcher("second.jsp").forward(request, response);
By your question edit, this is generating the problem:
response.sendRedirect("academic.jsp");
Note that using scriptlets is highly discouraged.
Make sure all your data processing and navigation is handled in a Servlet or another controller classes provided by a MVC framework like JSF managed beans or Spring MVC #Controller decorated classes.
More info:
How to avoid Java code in JSP files?
StackOverflow's Servlet wiki, here you can find a real world basic example about how to handle data processing and manipulation from a view to a servlet and then navigating to another view.
The actual problem lies in first.jsp line response.sendRedirect("academic.jsp"); which is inside a JSP Declaration and not JSP Scriptlet, as per the doc variables and methods in JSP declarations become declarations in the JSP page’s servlet class which explains why when you hit the first.jsp its getting redirected to another page without any action and as other suggested its not advisable to use JSP scriptlets, or declarations in your JSP.

Passing Data from JSP to Servlet

As described in the title I need to pass data from my JSP page to my servlet.
I load data out of a database into a form of my JSP page.
Now the user should be able to change that data.
So I have to send the changed data back to my servlet to update my database.
Therefore I want to use the doPost() method in my servlet
This is my JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="content-script-type" content="text/javascript" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="content-language" content="de" />
<link href="../resources/css/basic.css" type="text/css" rel="stylesheet" />
<title>Edit Movie</title>
</head>
<body>
<div id="wrapper">
<h2 id="title">Edit Person</h2>
<br></br>
<br></br>
<form id="1" class="appnitro" method="post" action="">
<ul>
<li id="li_1" >
<label class="description" for="element_1">Name</label>
<div>
<input id="element_1" name="element_1" class="element text large" type="text" maxlength="255" value="${requestScope.person.name}"/>
</div>
</li>
<li id="li_2" >
<label class="description" for="element_2">Deparment</label>
<div>
<input id="element_2" name="element_2" class="element text large" type="text" maxlength="255" value="${requestScope.person.department}"/>
</div>
</li>
<li id="li_3" >
<label class="description" for="element_3">Job</label>
<div>
<input id="element_3" name="element_3" class="element text large" type="text" maxlength="255" value="${requestScope.person.job}"/>
</div>
</li>
<li id="li_4" >
<label class="description" for="element_4">Biographie</label>
<div>
<textarea id="element_4" name="element_4" class="element textarea medium">${requestScope.person.biography}</textarea>
</div>
</li>
<li class="buttons">
<input type="hidden" name="form_id" value="652973" />
<input id="saveForm" class="button_text" type="submit" name="submit" value="Submit" />
</li>
</ul>
</form>
</div>
</body>
</html>
And this is my Servlet without the doPost() method:
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;
import de.hof.university.spj.model.People;
import de.hof.university.spj.model.PeopleDAO;
public class SinglePersonEditServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PeopleDAO peopleDao = new PeopleDAO();
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String name = "id";
String value = request.getParameter(name);
int id = Integer.parseInt(value);
People people = peopleDao.getPerson(id);
request.setAttribute("person", people);
RequestDispatcher reqDispatcher = request.getRequestDispatcher("../jsp/singlePersonEdit.jsp");
reqDispatcher.forward(request, response);
}
}
After the submit button was pressed I want to send the changed
data to my servlet so I can store it in my database.
Why String name = "id";
String value = request.getParameter(name); ? I can't seem to find any input in your JSP that's name = "id" ...
In the servlet, you should have this (for example), this :
String element_1_value = request.getParameter("element_1") ;
Either you forgot the input with id name or I am missing something. In any case, this is what you need to fix within your code.
Not to mention that you forgot inserting the name of the servlet in the action attribute of the form tag, so you had this :
<form id="1" class="appnitro" method="post" action="">
Which should become this :
<form id="1" class="appnitro" method="post" action="SinglePersonEditServlet">
Finally, your action method is "post" (as shown in the above two code lines), in the piece of servlet of your question you work with doGet, you ought to put your code in doPost unless that's done, otherwise it's sufficient to call doGet inside doPost.
I am a beginner myself, so I recognize one when I see it, we all started somewhere and I would recommand you this totu or any good search about "handling form data with servlet".
Note : duplicate of this, check it out for further learning :).
Regards.

Can't get parameter from the page via servlet

It should be simple, but i have a problem,
This is my *.jsp file
<html>
<head>
<title>Edit DataBase data</title>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<meta name="ProgId" content="FrontPage.Editor.Document">
<title>New Page 1</title>
</head>
<body>
<hr size="2"/>
<h2>id in DB = ?</h2>
<p>id:<input type="text" name="id" size="20" value="sdfs"></p>
<p>
<form action="/web/save" method="POST">
<input class="button" type="submit" value="submit" />
</form>
</p>
</form>
</body>
</html>
servlet looks like this
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id")
System.out.println("ID=" + id);
}
but in output ID=null
servlet was loaded by the button click on the server
You need to put the input tag in between the form tags.
For the code you put here
<form action="" method="POST">
is correct.
Check, you might have put
<form action="" method="GET">

Categories