button click in html for jsp - html

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}"} />

Related

I cant understant why the delete button does not work for me in jsp

This is my code:
AdminDelete.jsp:
<%# page import ="java.sql.*" %>
<%
String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub",
"root", "root");
Statement st = con.createStatement();
int t= st.executeUpdate("DELETE * FROM post WHERE(uid like'"+uid+"' AND content like'"+content+"')");
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
this is in the Admin's index:
<form method="send" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<% String content = request.getParameter("content");%>
<input type="button" value="delete" id="content">
</form>
I am trying to make a button that when i'm clicking on it, it delete's all of the posts in my website but when i click it, it dosen't do anything
I can not write entire answer in comment. So writing answer. As I mentioned in comment. You need to add space after LIKE. Also using PreparedStatement.
<%# page import ="java.sql.*" %>
<% String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM post WHERE uid like ? AND content LIKE ?");
ps.setString(1, "%" + uid + "%");
ps.setString(2, "%" + content + "%");
int t= ps.executeUpdate();
try {
con.close();
} catch(Exception e) {
e.printStackTrace();
}
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
One thing to note here is that you need to verify the UID is set in session and content is set in request parameters.
Also you have used method="send". Instead use method="POST".
<form method="POST" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<input type="text" name="content" />
<input type="submit" value="Delete" />
</form>
Suppose one record in DB has UID containing letter a and corresponding to this record content has value containing b. Now submit data with b as input in form and make sure UID in session has value set to a. It should work. If you come up with any error message let me know.

ASP.NET MVC HtmlTagBuilder dosen't work

I tried to extend the HtmlHelper by a paragraph element this is the Code:
<Extension()>
Public Function Para(ByRef helper As HtmlHelper) As String
Dim builder = New TagBuilder("p")
builder.SetInnerText("Hello World")
Return builder.ToString()
End Function
View:
#ModelType BookViewModel
#Code
ViewData("Title") = "Index"
End Code
#Using (Ajax.Form("Index", "BooksController", "BookList", "ajax_form"))
#<input type = "search" name="search" id="search" />
#<input type = "submit" value="Filter" />
End Using
#Html.Para()
#Html.Partial("_Books", Model)
It produces the following Output on the page:
<p> Hello World </p>
instead of only Hello World.
Why isn't this working.

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.

Program will not read my if statement

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")

Retrieving Form collection data from action methods using mvc 2.0

I am developing a sample in asp.net MVC 2.0. In My view (ProductDetails.aspx) I have 3 link buttons which are calling different action methods present in the same controller (ProductController). When I am clicking on the search link the appropriate action method is called but when I am taking data from Form Collection using string pid=Request.Form["tbPid"] I am getting a null value into pid. Help me in rectifying the issue.
Note: I dont have code for AddProduct link but I think there will be no issues.
Code for View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MVCProductDetailsDemo.Models.ProductModel>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ProductDetails</title>
</head>
<body>
<div>
<% using(Html.BeginForm()){ %>
pid:<%=Html.TextBox("tbPid") %>
<%=Html.ActionLink("Search Product", "SearchProducts", "Product")%><br />
<%if (Model != null)
{ %>
pname:<%=Html.TextBox("tbPname", Model.PName)%><br />
Minqty:<%=Html.TextBox("tbMinQty",Model.MinOrdQty) %><br />
Maxqty:<%=Html.TextBox("tbMaxQty",Model.MaxOrdQty) %><br />
Up:<%=Html.TextBox("tbUP",Model.UnitPrice) %><br />
<%} %>
<%else { %>
Pname:<%=Html.TextBox("tbPname") %>
MinQty:<%= Html.TextBox("tbMinQty")%>
MaxQty:<%=Html.TextBox("tbMaxQty")%>
UP:<%=Html.TextBox("tbUP") %>
<%} %>
Manifacturer:<%=Html.DropDownList("manifacturers") %><br />
<%=Html.ActionLink("Add Product","AddProduct","Product") %>
<%=Html.ActionLink("Upd Product","UpdateProduct","Product") %>
<%=Html.ActionLink("Del Product","DeleteProduct","Product") %>
<%} %>
</div>
</body>
</html>
**Code for Controller:**
namespace MVCProductDetailsDemo.Controllers
{
public class ProductController : Controller
{
//Normal Methods and ActionMethods.
//ActionMethods are the methods which will usually call the views.
public ActionResult DisplayProduct()
{
List<string> lstManifacturers=GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails");
}
public List<string> GetManifacturers()
{
Manifacturers manifacturer = new Manifacturers();
return manifacturer.GetManifacturers();
}
public ActionResult SearchProducts()
{
string pid=Request.Form["tbPid"];
Products products = new Products();
ProductModel pModel=products.GetProductDetails(Convert.ToInt32(pid));
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails", pModel);
}
public ActionResult UpdateProduct()
{
string pid = Request.Form["tbPid"];
string pname = Request.Form["tbPname"];
string minqty = Request.Form["tbMinQty"];
string maxqty = Request.Form["tbMaxQty"];
string up = Request.Form["tbUP"];
Products products = new Products();
ProductModel pModel = new ProductModel();
pModel.Mid = 1;
pModel.PName = pname;
pModel.MinOrdQty = Convert.ToInt32(minqty);
pModel.MaxOrdQty = Convert.ToInt32(maxqty);
pModel.Pid = Convert.ToInt32(pid);
pModel.UnitPrice = Convert.ToInt32(up);
bool isRecordUpdated = products.UpdateProducts(pModel);
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails", pModel);
}
public ActionResult DeleteProduct()
{
string pid = Request.Form["tbPid"];
Products products = new Products();
bool isRecordDeleted = products.DeleteProduct(Convert.ToInt32(pid));
List<string> lstManifacturers = GetManifacturers();
ViewData["manifacturers"] = new SelectList(lstManifacturers);
return View("ProductDetails");
}
}
}
Html.ActionLink produces anchor (a) tag that, when clicked, simply points the browser to a different address. What you need is a submit button that causes form data to be posted to the server. The url where form data is submitted can be controlled by the parameters of Html.BeginForm - during view rendering, or by javascript on the client as the value of action attribute of the form tag. If you don't specify Html.BeginForm paremeters (as in your code), the form will be posted to controller action with the same name as the one that produced the page. You need to create an overloaded action method (with parameter FormCollection collection, for example) and mark it with [HttpPost] attribute.