Program will not read my if statement - mysql

I am doing this project and I am almost done. It took me a while to actually get the code to actually run but I finally got it. My assignment was to make a HTML form, connect it to MySQL using JSP, and insert the values into the database or delete the values from the database. It is also password protected. Like I said I have gotten it to compile without error however the If statement I have implemented is not being picked up. I was wondering if you all could help me figure why this is happening. Im going to paste my HTML code then my JSP.
HTML CODE
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Assignment 3 </title>
</head>
<body>
<h3> Song Name Form </h3>
<form action = "hgooding.jsp" method = "post">
<table border = "1">
<tr>
<td>Song Title: </td>
<td> <input type = "text" name = "song"/> </td>
</tr>
<tr>
<td>Artist </td>
<td> <input type = "text" name = "artist"/> </td>
</tr>
<tr>
<td>Password: </td>
<td> <input type = "password" name = "pass1"
size = "20"/> </td>
</tr>
</table>
<br>
<input type = "radio" name = "option" value = "add"/> Add
<input type = "radio" name = "option" value = "delete"/> Delete
<br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
JSP CODE
<%# page import = "java.sql.*" %>
<html>
<head> <title> Database jsp </title></head>
<body>
<%
String connectionURL = "jdbc:mysql://sql.njit.edu:3306/hg33";
Connection connection = null;
Statement stm = null;
ResultSet rst=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "hg33", "grapes34");
String song = request.getParameter("song");
String artist = request.getParameter("artist");
String action = request.getParameter("option");
String pass2 = request.getParameter("pass1");
Statement stminsert = null;
stminsert = connection.createStatement();
if (pass2 == "apples4")
{
if (request.getParameter("action").equals("add"))
{
String sqlupdate1=("INSERT INTO Songs VALUES('"+song+"', '"+artist+"')");
stm.executeUpdate(sqlupdate1);
out.println("Hi!");
}
if (request.getParameter("action").equals("delete"))
{
String sqlupdate2=("DELETE FROM Music WHERE Song =('"+song+"')");
stm.executeUpdate(sqlupdate2);
}
rst = stm.executeQuery("SELECT * from Music");
}
else
{
out.println( "Password is not correct!!!" );
}
out.println("insert attempted");
%>
</body>
</html>

I guess ur condition in if statement should be like this
if (action.equals("add")){.........................}
or
if (action == "add"){.........................}
instead of
if (request.getParameter("action").equals("add")){....................}
coz u catch option in action variable like this
String action = request.getParameter("option")

Related

How to Loop form elements in JSP

I'm want to use some sort of loop to go over all input fields in my form . But I'm unable to find any proper documentation on how to do it. Is it possible to loop over all the elements in my form in some way as well as dealing with multiple checkboxes ?
I tried to follow some online sources . This one outputs null value.
<html>
<body>
<form action = "main.jsp" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>
</body>
</html>
<%# page import = "java.io.*,java.util.*" %>
<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width = "100%" border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>
Is there any documentation source from where I can read about request object's methods ?

button click in html for jsp

I have the following coding in JSP which work when a JSP page is loaded:
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
But I want it to work only when I click a HTML button like:
<button onclick="">JSP Command</button>
The button and the JSP coding must be in the same JSP page.
You can wrap your code that you need to load when click in a condition that check isButtonClick, then assign to onClick a function to update it
<c:set var="isButtonClicked" value="false" />
<c:if test="${isButtonClicked}">
<%
String sportugues = request.getParameter("port");
String senglish = request.getParameter("engl");
String sfuncgram = request.getParameter("funcgram");
//Integer snsyn = Integer.valueOf(request.getParameter("nsyninp"));
Usuario usu = new Usuario();
usu.setPortugues(sportugues);
usu.setEnglish(senglish);
usu.setFuncgram(sfuncgram);
//usu.setNsyn(snsyn);
UsuarioDao usudDao = new UsuarioDao();
usudDao.cadastroStudyAlfaDireita(usu);
%>
</c:if>
<button onClick="function(){<c:set var="isButtonClicked" value="${!isButtonClicked}"} />

how to get values from checkbox and pass it to the another jsp page?

I have created many checkboxes using a for loop. Now I want to get the values from checkboxes if they are ticked or not.
When a checkbox is ticked, then its label must be passed to another JSP page. But I am unable to achieve it properly.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1><center>REGISTER FORM</center></h1>
<%
String[] stArray=new String[40];
ArrayList ar = new ArrayList();
int idcounter = 0;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/registerdb", "root", "");
PreparedStatement ps = con.prepareStatement("select leave_types from leaves");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
String array_value = rs.getString("leave_types");
ar.add(array_value);
}
// out.println(ar);
request.setAttribute("LEV_ARRAY", ar);
}
catch(Exception e)
{
out.println(e);
}
%>
<form action = "insertdata.jsp" name="myform" method="post">
<%
for(int i = 0; i<ar.size(); i++)
{
out.println(ar.get(i));
%>
<input id ="<%=idcounter%>" type="checkbox" name = "" value="" />
<%
idcounter++;
}
// String[] selectedCheckboxes = request.getParameterValues("selected");
%>
<center><button type= "submit" name="action">SIGN UP</button></center>
</form>
</body>
</html>
You can do like below :
Pass ar.get(i) as values in checkboxes :
<form action = "insertdata.jsp" name="myform" method="post">
<%
for(int i = 0; i<ar.size(); i++)
{
out.println(ar.get(i));
%>
<!--name=abc will be used in jsp to get value selected in checkboxes-->
<input id ="<%=idcounter%>" type="checkbox" name = "abc" value="<%=ar.get(i)%>" />
<%
idcounter++;
}
%>
<center><input type= "submit" name="action" value="SIGN UP"/></center>
</form>
Then ,to get above values in jsp page do like below:
<!--getting values selected using "abc"-->
<%String check[]= request.getParameterValues("abc");
<!--checking for null values-->
if(check!= null){%>
<!--there might be more one checkbox selected so, using loop-->
<%for(int i=0; i<check.length; i++){%>
<!--printing values selected-->
<%=check[i]%>
<%}
}%>

Unable to fetch the data of a column with radio buttons in jsp using servlet with request.getParameterValues() function

I have a table with 3 columns.Last column has 4 radio buttons in each row.I am not able to fetch all the values of radio buttons checked after submitting the form.I always get only one value which is the value of radio button checked in the first row.
Here is the code of jsp page:
<form action = "SaveData" method = "POST" target = "_blank">
<h1>LIST</h1>
<%
try {
/* Create string of connection url within specified format with machine
name, port number and database name. Here machine name id localhost and
database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/sample";
// declare a connection by using Connection interface
Connection connection = null;
/* declare object of Statement interface that is used for executing sql
statements. */
Statement statement = null;
// declare a resultset that uses as a table for output data from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* 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", "password");
/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from data";
rs = statement.executeQuery(QueryString);
%>
<table class="comparison-table">
<tr>
<th>LIST</th>
<th>Y/N</th>
<th>OPTIONS</th>
</tr>
<div>
<tr>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<form>
<input type="radio" name="option" value="a" checked> A
<input type="radio" name="option" value="b" >B
<input type="radio" name="option" value="c" > C
<input type="radio" name="option" value="d"> D
</form>
</td>
</tr>
</div>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
}
catch (Exception ex) {
%>
<%
out.println("Unable to connect to database."+ex);
}
%>
</table>
<button value="Submit" id="button">Submit</button>
</form>
Here is the Servlet code:
import javax.servlet.annotation.WebServlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
//Extend HttpServlet class
#WebServlet("/SaveData")
public class SaveData extends HttpServlet {
// Method to handle GET method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Form Parameters";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<table width = \"100%\" border = \"1\" align = \"center\">\n" +
"<tr bgcolor = \"#949494\">\n" +
"<th>Param Name</th>"+
"<th>Param Value(s)</th>\n"+
"</tr>\n"
);
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues = request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
}
Output after submitting the form would be values of two parameters "choose" and "option". I get proper output for "choose" parameter ie. all the selected Yes/No options in a cloumn,whereas for "option" parameter i would get only the value of first row selected radio button ie if i select 'c' in the first row radio buttons only 'c' will be displayed with rest of the rows ignored.
Please help me out in fetching data of all the columns of the radio buttons selected in a String array.
I also want to fetch the value of "slist" which is from database using servlet. This is under td tag with name="list".
First you sould not nest form tag, remove the form tag before radio button.
From MDN web docs :
elements of type radio are generally used in radio
groups—collections of radio buttons describing a set of related
options. Only one radio button in a given group can be selected at the
same time.
You should add a variable to differentiate lines like this for example :
<tr>
<%! int lineNumber = 0 %>
<%
while (rs.next()) {
String slist=rs.getString(1);
%>
<td name="list"><%= slist%></td>
<td>
<select id="choose" name="choose">
<option>Yes</option>
<option>No</option>
</select>
</td>
<td>
<input type="radio" name="option<%= lineNumber %>" value="a" checked> A
<input type="radio" name="option<%= lineNumber %>" value="b" >B
<input type="radio" name="option<%= lineNumber %>" value="c" > C
<input type="radio" name="option<%= lineNumber %>" value="d"> D
</td>
</tr>
<% lineNumber++ %>

direct jsp page by button onclick event without form tag

can we use input tag button without form tag and how to direct to another jsp page through onclick event?
I am trying to do this task by below code Here am trying to direct one editsurvey,jsp page through button onclick event without form tag.Can anyone explain the way I am using correct or incorrect?
<%--
Created by IntelliJ IDEA.
User: rajee
Date: 2/16/15
Time: 10:17 AM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="delete"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="print"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<td><input type="button" value="send mail"></td>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
</tr>
</table>
</table>
<%
}
%>
</body>
</html>
HI i think you can use the following code
<button type="submit" formaction="demo_admin.asp">Submit as admin</button>
In the formaction attribute you can use your form name where you want to redirect.