This question already has answers here:
How to transfer data from JSP to servlet when submitting HTML form
(4 answers)
Closed 6 years ago.
I am trying to read the input by the user as soon as he clicks on a button. But unfortunately the request.getParamater() is always returning a null value. Can someone please help me I have been hours Trying to sort this out :(
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<head>
<script language="javascript">
function add()
{
<%
Integer quantity = 500;
Integer code = 1000;
//String codes = request.getParameter("code");
String codes = (String) request.getParameter("code");
String quanti = (String) request.getParameter("quantity");
if (codes != null && quanti != null) {
quantity = Integer.parseInt(quanti);
code = Integer.parseInt(codes);
}
out.println(code);
out.println(quantity);
String connectionURL = "jdbc:mysql://localhost:3306/products";
Connection connection = null;
PreparedStatement pstatement = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
int updateQuery = 0;
// check if the text box is empty
if (code != null && quantity != null) {
// check if the text box having only blank spaces
if (codes != "" && quanti != "") {
try {
/* Create a connection by using getConnection()
method that takes parameters of string type
connection url, user name and password to connect
to database. */
connection = DriverManager.getConnection(connectionURL, "root", "170293m");
// sql query to insert values in the secified table.
String queryString = "INSERT INTO sales (code, quantity, price, name) VALUES (?, ?, ?, ?)";
/* createStatement() is used for create statement
object that is used for
sending sql statements to the specified database. */
pstatement = connection.prepareStatement(queryString);
pstatement.setInt(1, code);
pstatement.setInt(2, quantity);
pstatement.setDouble(3, 50);
pstatement.setString(4, "aw ras");
updateQuery = pstatement.executeUpdate();
if (updateQuery != 0) {
out.println("Error in query");
}
} catch (Exception ex) {
out.println("Unable to connect to batabase.");
} finally {
// close all the connections.
pstatement.close();
connection.close();
}
}
}%>
print();
}
function remove()
{
}
</script>
<title>BestWholesaler LTd.</title>
</head>
<body>
<h1>Welcome to BestWholesaler Ltd. Online Ordering</h1>
<h2>Items Currently in Stock</h2>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/products"
user="root" password="170293m"/>
<sql:query dataSource="${snapshot}" var="result">
SELECT Name, Code, PricePU, Quantity from productinfo;
</sql:query>
<table border="1" width="100%">
<tr>
<th>Name</th>
<th>Code</th>
<th>Price/Unit</th>
<th>Quantity Available</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.Name}"/></td>
<td><c:out value="${row.Code}"/></td>
<td><c:out value="${row.PricePU}"/></td>
<td><c:out value="${row.Quantity}"/></td>
</tr>
</c:forEach>
</table>
<br>
<br>
Enter Code: <input type="text" name="code" id="code" value="" />
<br>
Enter Quantity: <input type="text" name="quantity" id="quantity" value="" />
<input type="button" value="ADD" name="add" onclick="add()" />
<input type="button" value="REMOVE" name="remove" onclick="remove()" />
</body>
</html>
You are not using any <form> HTML tag. All input tag must go inside it, and the button click should do a submit of the form.
By the way, you are mixing Javascrit client code and Java server code in a way that cannot work, you have different rendering timings.
On this example, assuming you are wanting to have a unique component both for client-side and for server-side, as you are doing, you can add the following to your JSP. For commodity I'm going to separate client-side and server-side logics.
Client side
<script>
function flagLoaded(){
document.forms[0]["loaded"].value = "true";
}
</script>
<form name="input" action="myself.jsp" method="get" onsubmit="flagLoaded()">
<!-- put here all your client-side's inputs -->
<!-- ... TODO ... -->
<input type="hidden" name="loaded" value="false">
<input type="submit" value="Submit">
</form>
Server side
<%
if("true".equals(request.getParameter("loaded"))){
//TODO
/*
Do here server-side logic...
*/
}
%>
The main reason behind this is you are using the javascript i.e <script language="javascript"> and you are trying to run the server side code inside it .
you must close the javascript by using </script> and then try to run the server side code..
You don't need javascript here, go with basic html form tag to submit the details. Also don't use scriplets as you are already aware of jstl. Note below code is only implemented for add, you need to write your code for remove.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/products" user="root" password="170293m" />
<title>BestWholesaler LTd.</title>
<style>
.error {
color: red;
}
</style>
<body>
<h1>Welcome to BestWholesaler Ltd. Online Ordering</h1>
<h2>Items Currently in Stock</h2>
<!-- add button was clicked -->
<c:if test="${null != param.add}">
<c:catch var="error">
<sql:update dataSource="${snapshot}" scope="page" var="result">
INSERT INTO sales (code, quantity, price, name) VALUES (?, ?, ?, ?)
<sql:param value="${param.code}" />
<sql:param value="${param.quantity}" />
<sql:param value="50" />
<sql:param value="aw ras" />
</sql:update>
</c:catch>
</c:if>
<!-- error occured -->
<c:if test="${null != error}">
<div class='error'>
Failed to save stock details
</div>
</c:if>
<c:catch var="error">
<sql:query dataSource="${snapshot}" var="result">
SELECT Name, Code, PricePU, Quantity from productinfo;
</sql:query>
</c:catch>
<c:if test="${null != error}">
<div class='error'>
Failed to get stock details
</div>
</c:if>
<c:if test="${null == error}">
<table border="1" width="100%">
<tr>
<th>Name</th>
<th>Code</th>
<th>Price/Unit</th>
<th>Quantity Available</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td>
<c:out value="${row.Name}" />
</td>
<td>
<c:out value="${row.Code}" />
</td>
<td>
<c:out value="${row.PricePU}" />
</td>
<td>
<c:out value="${row.Quantity}" />
</td>
</tr>
</c:forEach>
</table>
</c:if>
<br/>
<br/>
<form method='post'> <!-- no action required, still you can give the same jsp file name -->
Enter Code:
<input type="text" name="code" />
<br/>Enter Quantity:
<input type="text" name="quantity" />
<input type="submit" value="ADD" name="add" />
</form>
</body>
Related
I have made a login page and a forward tag is not working it creates error which i can not able to find out.
I uses access database and after clicking sign in button it will check, if user is already registerd then page should forward next page but it does not so.
Here is my code:
<form action="login.jsp" method="get">
<table>
<tr></tr>
<td><br>
<label>EmailID:</label>
</td>
<td>
<input type="text" name="emailid" maxlength="50" size="30">
</td>
<tr></tr>
<td><br>
<label>Password:</label>
</td>
<td>
<input type="password" name="passwordid" maxlength="50" size="30">
<p>
</p>
</td>
<tr></tr>
<td></td>
<td><input type="submit" value="sign in"></center></td>
<%
try
{
String existemail="registration",existpass="12345";
ResultSet rs, rs1;
String emailid1=request.getParameter("emailid");
String passwordid1=request.getParameter("passwordid");
if(emailid1.length()!=0 && passwordid1.length()!=0)
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:collegep");
Statement st = conn.createStatement();
rs=st.executeQuery("select password from collge where
email='"+emailid1+"'");
while(rs.next())
{
existpass= rs.getString(1);
}
if(existpass.equals(passwordid1))
{
<jsp:forward page=
"afterlogin.html" />
}else
{ %> invalid combination of email and password<%
}
}
else
{` %>
<div id="error">all field must be filled.</div>
<%
}
}
catch(Exception e){}
%>
Please try changing from:
<jsp:forward page:
to:
<jsp:forward page=
It seems like you used inappropriate Scriplet Tags(<% %>)..close scriptlet end tag(%>) above ur <jsp:forward page="afterlogin.html"/>
All java code should be in Scriplet Tag only..and html code outside of it..make this changes
This is my coding for order.jsp, a form for customer to insert order and I use session.menus to display option menu in a HTML input element from database. I already connect to database using jdbcutility.java, where I put sql statement to connect my servlet with database and its working for login but not for this session.
<form class="form-horizontal" method="post" action="InsertOrderServlet">
<center>
<table border="10" cellpadding="20" cellspacing="20">
<thead>
<tr>
<th colspan="2"><h2 style="line-height: 3;" >Order Food</h2></th>
</tr>
</thead>
<tbody>
<tr>
<td><br><br>Food</br></br></td>
<td>
<br><br>
<div class="col-lg-9">
<select class="form-control" name="menuName">
<c:forEach items="${sessionScope.menus}" var="currentmenu" varStatus="loop">
<option><c:out value="${currentmenu.foodName}" /></option>
</c:forEach>
</select>
</div>
</td>
</tr>
<tr>
<td>Quantity</td>
<td><input type="text" name="quantity" required/></td>
</tr>
<tr style="line-height: 10;" >
<td> <button class="btn btn-primary" type="reset" >Cancel</button></td>
<td > <button type="submit" class="btn bt primary">Submit</button></td>
</td>
</tr>
</tbody>
</table>
</center>
</form>
getMenuServlet.java
//select all from menu
try {
ResultSet rs = jdbcUtility.getPSSelectMenu().executeQuery();
while (rs.next()) {
menu = new Menu();
menu.setId(rs.getInt("menuid"));
menu.setfoodName(rs.getString("foodName"));
menu.setImage(rs.getString("image"));
menu.setPrice(rs.getDouble("price"));
//put into arraylist
menus.add(menu);
}
}
catch (SQLException ex)
{
}
//put into sessions
session.setAttribute("menus", menus);
jdbcutility.java
String sqlValidateLogin = "Select username,password from customer where username=? and password=?";
psInsertLogin = con.prepareStatement(sqlValidateLogin);
String sqlInsertOrder = "INSERT INTO orderfood(menuName, quantity) " + "VALUES(?, ?)";
psInsertOrder = con.prepareStatement(sqlInsertOrder);
String sqlSelectAllMenu ="SELECT * FROM menu";
psSelectAllMenu = con.prepareStatement(sqlSelectAllMenu);
String sqlSelectAllOrder ="SELECT * FROM orderfood";
psSelectAllOrder = con.prepareStatement(sqlSelectAllOrder);
This keep occurring, how do I fix this?
image blank
Make sure the JSP is allow access session.
<%# page session="true" %>
To use core JSTL, make sure the following code is included.
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
I am a beginner in jsp.I want to get data from database and show checked on a checkbox depending on db value i.e. 0 or 1.This is working for me.But I also want o that when I check or uncheck the checkbox it will reset value and pass it to controller as a href parameter.
here is my jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Investor Account</title>
</head>
<body>
<script type="text/JavaScript">
function updateCheck(){
if(document.getElementById('chk').checked){
document.getElementById('chk').value = 1;
location.href=""
alert(document.getElementById('chk').value);
}
else{
document.getElementById('chk').value = 0;
alert(document.getElementById('chk').value);
}
}
</script>
<div align="center">
<h1>Investor Account List</h1>
<table border="1">
<th>ID</th>
<th>Investor Code</th>
<th>Investor Name</th>
<th>SMS Subscriber</th>
<th>Action</th>
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td> <input type="checkbox" id="chk" name="chkSms" value= <c:if test="${investorAcc.sms_sub==1}">1</c:if> onclick="updateCheck();"
<c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<td>
1</c:if>"> Update
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
To update checkbox value, the easiest way is to use form in loop. Try
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<form action="updateInvestorAcc">
<input type="hidden" name="id" value="${investorAcc.id}"/>
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td>
<c:choose>
<c:when test="${investorAcc.sms_sub==1}">
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" checked="checked"/>
</c:when>
<c:otherwise>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}"/>
</c:otherwise>
</c:choose><td> <!-- end of checkbox -->
<td><input type="submit" value="Update"></td>
</tr>
</form>
</c:forEach>
Edit:
You need a Servlet to get updated value
#WebServlet("/updateInvestorAcc")
public class UpdateInvestorAcc extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String idStr=request.getParameter("id");
int id= Integer.parseInt(idStr);// If you need to parse to int
String[] chkSms=request.getParameterValues("chkSms");
boolean isChkSms =false;
if(chkSms !=null && chkSms.length > 0){//If checkbox is checked than assign it with true or 1
isChkSms=true;
}
// Now update the DB with id and checkbox value.
}
you can simplify the middle bit in the other posters suggestion with a basic IF test. Because it's only going to be 1 or 0 (choose is overkill IMO). Technically because it's 1/0 you don't even need to ==1 comparitor, just reference it raw in the test="" block as test="${investorAcc.sms_sub}". The JSTL is smart enough to handle all angles (including NULL). 1=true, 0=false, NULL=false.
<c:forEach var="investorAcc" items="${listInvestorAcc}" varStatus="st">
<form action="updateInvestorAcc">
<input type="hidden" name="id" value="${investorAcc.id}"/>
<tr>
<td>${st.index + 1}</td>
<td>${investorAcc.investor_code}</td>
<td>${investorAcc.investor_name}</td>
<td>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" <c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<td> <!-- end of checkbox -->
<td><input type="submit" value="Update"></td>
</tr>
</form>
</c:forEach>
For your second bit about the 'unchecked' box passing invalid values. That's a super annoying thing with HTML. Unchecked boxes get 'dropped to null' when a form is submitted. A lot of people are supplementing with a 2nd hidden input to get this done without NULL errors (note, it MUST be second). Different "ID", but same "NAME" so the Servlet will see it and capture the 'unchecked' value from it instead of the NULLed original checkbox:
ex:
<td>
<input type="checkbox" id="chk" name="chkSms"
value="${investorAcc.sms_sub}" <c:if test="${investorAcc.sms_sub==1}">checked="checked"</c:if>/>
<input type="hidden" id="chk_0" name="chkSms"
value="0"/>
<td> <!-- end of checkbox -->
I have a success.jsp page which displays multiple rows and columns with an Edit button and a checkbox for each row. If the user clicks on Edit button, the checkbox is selected.
Below is success.jsp :
<%#page import="mymvc.model.TableColumns"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%--
Document : success
Created on : Jul 8, 2014, 1:43:17 PM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Success</title>
<script type="text/javascript">
function validate(n) {
v = document.getElementById("check"+n)
v.checked = !v.checked;
x = document.getElementById("typeId"+n).removeAttribute('readonly');
y = document.getElementById("paramSeq"+n).removeAttribute('readonly');
z = document.getElementById("paramName"+n).removeAttribute('readonly');
}
</script>
</head>
<body>
<form action="DBController" method="post">
Welcome ${requestScope['user'].username}.
<table>
<tr style="background-color:#f0a64e;">
<th class="border">ID</th>
<th class="border">Param Sequence</th>
<th class="border">Param Name</th>
</tr>
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input id="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input id="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input id="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
<input type="submit" value="Update" name="update" />
</form>
</body>
</html>
I don't know how to send the whole row data to my servlet if more than one row is selected. I am able to get all the indexes of the checkboxes which are selected. But I am unable to extract other related values like typeId, paramSeq and paramName. My servlet is as follows :
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String[] edited = request.getParameterValues("selectedItems");
//String pName = request.getParameter("paramName"+edited[1]);
Enumeration<String> paramName = request.getParameterNames();
String[] param = new String[10];
int i=0;
while(paramName.hasMoreElements()){
param[i]=paramName.nextElement();
}
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("/update.jsp");
request.setAttribute("param", param);
request.setAttribute("edited", edited);
rd.forward(request, response);
}
In the above code, currently, I am trying to get all the parameters passed and the rows which are selected. I want to modify this servlet and access the selected row along with other data like typeId, etc. to create UPDATE statements for every row. I referred this and this but not much help.
I think what you are missing is that you are giving each input type a unique id but you are not specifying the name of the input types, and in the servlet you are trying to get values by name.
So please add names along with the id's in order to get them in the servlet
<c:forEach var="element" items="${requestScope['listData']}" varStatus="status">
<tr>
<td><input name="typeId${status.index}" value="${element.typeId}" readonly="true"</td>
<td><input name="paramSeq${status.index}" value="${element.paramSeq}" readonly="true"</td>
<td><input name="paramName${status.index}" value="${element.paramName}" readonly="true"</td>
<td>
<input id="edit${status.index}" type="button" value="Edit" name="edit" onclick="validate(${status.index})"</input>
</td>
<td><input type="checkbox" id="check${status.index}" name="selectedItems" value="<c:out value="${status.index}"/>"</td>
</tr>
</c:forEach>
</table>
I'm forwarding to a jsp that shows a table and a form for comments populated by jstl sql tags.
The problem is that the form works fine if I use response.sendRedirect("comments.jsp");
But since I need to retain session info between pages I want to use request.getRequestDispatcher("comments.jsp").forward(request, response);
which triggers the post form and redirects subsequent posts to the servlet url.
LoginServlet
public class LoginServlet extends HttpServlet {
Connection connection = null;
PreparedStatement ptmt = null;
ResultSet resultSet = null;
User user = null;
boolean fail = true;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (null != email && null != password) {
try {
connection = ConnectionFactory.getInstance().getConnection();
user = new User();
String queryString = "SELECT * FROM USERINFO WHERE EMAIL=?";
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, email);
resultSet = ptmt.executeQuery();
resultSet.next();
user.setEmail(resultSet.getString("EMAIL"));
...
user.setSecret3(resultSet.getString("SECRET3"));
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
}
}
if (null != user.getPassword() && user.getPassword().equals(password)) {
request.setAttribute("user",user);
request.getRequestDispatcher("comments.jsp").forward(request, response);
// response.sendRedirect("comments.jsp");
}
comments.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Comments</title>
</head>
<body>
<sql:setDataSource var="dataSource" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<sql:setDataSource var="dataSource2" driver="org.apache.derby.jdbc.ClientDriver"
url="jdbc:derby://localhost:1527/mp1"
user="app" password="app"/>
<H2>Comments</H2>
<sql:query dataSource="${dataSource}" sql="SELECT * FROM COMMENTS" var="comments" />
<table border=1>
<c:forEach var="row" items="${comments.rows}">
<tr>
<c:forEach var="col" items="${row}">
<td><c:out value="${col.value}" /></td>
</c:forEach>
</tr>
</c:forEach>
</table>
<form method="post">
<table>
<tr>
<td>Enter Email</td>
<td><input type="text" name="EMAIL"></td>
</tr>
<tr>
<td>Enter Comment</td>
<td><input type="text" name="COMMENT"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
<c:if test="${pageContext.request.method=='POST'}">
<c:catch var="exception">
<sql:update dataSource="${dataSource2}" var="updatedTable">
INSERT INTO
COMMENTS (EMAIL,COMMENT)
VALUES (?, ?)
<sql:param value="${param.EMAIL}" />
<sql:param value="${param.COMMENT}" />
</sql:update>
<c:if test="${updatedTable>=1}">
<c:redirect url="/comments.jsp"/>
</c:if>
</c:catch>
<c:if test="${exception!=null}">
<c:out value="Unable to add comment." />
</c:if>
</c:if>
</body>
</html>
BTW, this is a homework assignment were the teacher wants us learn how it was done the old way. So security and better technologies to use are not real concerns.
PS. I've solved this by separating the comments and add comment into separate pages. Perhaps a better solution would be to use the session instead of the request for object transfer.
Both redirect and forward should retain session since session is supported by cookies (in most cases).
Your form doesn't have action parameter thus its behavior depends on the browser current URL (form gets posted to current URL instead of defined in action), and current URL is different in case of redirect and forward.