I'm having a JSP page as follows :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Admin Tools</title>
<jsp:include page="/basic/nav.jsp"/>
<link rel="stylesheet" type="text/css" href="tools.css"/>
</head>
<body>
<div class="container">
<h2>Admin Tools</h2>
<br/><br/><br/><br/>
<%#page import="java.sql.ResultSet"%>
<%
boolean def_admin = false, def_admin_changed = false;
conn.connect.main(null);
conn.dbc.main(null);
ResultSet rstools = conn.connect.st.executeQuery("select * from admins where uname='admin'");
if (rstools.next()) {
if (rstools.getString("uname").equals("admin") && rstools.getString("password").equals("123")) {
def_admin = true;
}
if (rstools.getString("uname").equals("admin") && !rstools.getString("password").equals("123")) {
def_admin_changed = true;
}
}
%>
<%if (def_admin == false) {%>
Add Default Admin Account :<br/>
<input type="button" value="Add" onclick="<% add_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
Delete Default Admin Account :<br/>
<input type="button" value="Delete" onclick="<% delete_admin(); %>"/>
<% } else if (def_admin == true && def_admin_changed == false) { %>
The Default Admin Password Exists but the password has been changed<br/>
Do you still want to delete the Default Admin Account?<br/>
<input type="button" value="Even so, Delete it" onclick="<% delete_admin(); %>"/>
<% }%>
<div id="tools_error"></div>
<%!
boolean insert_success = false;
void add_admin() {
try {
int Urows;
Urows = conn.connect.st.executeUpdate("insert into admins(uname,password) values('admin','123');");
if (Urows == 1) {
insert_success = true;
} else {
insert_success = false;
}
%>
<script>
(function () {
boolean i_s = "<%=insert_success%>";
if (i_s == false) {
document.getElementById("tools_error").value = "There has been an error in Adding Default Admin";
}
});
</script>
<%!
} catch (Exception e) {
}
}
void delete_admin() {
}
%>
</div>
</body>
<jsp:include page="/basic/footer.jsp"/>
</html>
As you can see when the button is clicked I have made it to run the declared JSP functions. But when the JSP file is loaded the functions run automatically and the insert MYSQL query runs which automatically inserts the values given in the query.
I don't want it the functions add_admin() and delete_admin() to run automatically on load. Any suggestions?
The events in the webpage (onclick event for example) is executed client side when someone opens your webpage and clicks the button. The JSP scriplets are executed when the webpage is opened and their result is the actual page that the client receives. So your method executes ONLY when the page is loaded (and the JSP is compiled). The java code is not even visible in the webpage you generate. If you open it in browser and check the source you will see what I mean.
TL;DR: You can't
Your Java code is executed once, when the page is loaded. The page is not on the server anymore, so you can't use its back-end capabilities. Otherwise, that would mean someone reewriting your HTML could make your page execute any code on your back-end.
Once your page is loaded, all there is on it is HTML and Javascript (CSS if you want to bicker).
Related
Does Eclipse Orion WebIDE support JSP? I am trying to create a simple application and jsp files are not working.
index.html
<html>
<head>
<script type="text/javascript" src="jquery-1.12.4.js"></script>
<script>
function getInput()
{
$.ajax({
type:"GET",
url: "./test.jsp",
success: function(success) {
console.log(success);
}
});
}
</script>
</head>
<body onload="getInput()">
test.jsp
<%#import="./javaMethod*"%>
<%javaMethod a = new javaMethod();
var value = a.initiate();
%>
<input type="hidden" id="test" value="<%=value%>">
javaMethod.java
public class javaMethod
{
public int initiate()
{
return 1;
}
}
This should add a hidden input field which will hold the value from the java method. However, it is not working and the jsp is just displaying as plain text.
This should add a hidden input field - no, this should log anything comes from test.jsp to the browser console. To add the output of the JSP to the body element, use $(document.body).append(success);.
This question already has answers here:
Passing an object from JSP page back to Servlet
(3 answers)
Closed 6 years ago.
I have one Java Web Application.
My User_Objects class is given below
public class User_Objects {
public String firstName;
public String middleName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
}
I forward request with my Java User_Objects to JSP with using following code
User_Objects fillObj = fillData(request);
request.setAttribute("reqObj", fillObj);
RequestDispatcher view = request.getRequestDispatcher("/organization.jsp");
view.forward(request, response);
public User_Objects fillData(HttpServletRequest request) {
User_Objects fillObj = new User_Objects();
try {
fillObj.setFirstName(request.getParameter("txtFirstname"));
} catch (Exception e) {
}
try {
fillObj.setMiddleName(request.getParameter("txtMiddlename"));
} catch (Exception e) {
}
return fillObj;
}
I successfully receive this Object into my JSP form. But I want to send this Object again to the Servlet and When I click on Submit button on my JSP form and try to get this Object into my Servlet using below code
User_Objects obj = (User_Objects) request.getAttribute("reqObj");
request.getAttribute("reqObj") gives me null
My JSP form code is given below
<%# page import="otn.aitc.io.User_Objects" %>
<%# 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>Organization</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
$(function() {
var reqObj = '${reqObj}';
var reqStatus = '${orgStatus}';
var orgJson = '${reqOrgJson}';
orgJson = orgJson.replace("/", "'");
if(reqStatus != "" || orgJson != "") {
if(reqStatus == "false") {
document.getElementById("lblError").style.display = '';
}
else {
document.getElementById("lblError").style.display = 'none';
}
var availableTutorials = [];
if(orgJson != "") {
var parsed = JSON.parse(orgJson);
for(var x in orgJson) {
if(parsed[x] != undefined) {
availableTutorials.push(parsed[x]);
}
}
}
$("#txtOrgName").autocomplete({source: availableTutorials});
}
else {
window.location.href = "index.jsp";
}
});
function validateOrg() {
var orgName = document.getElementById("txtOrgName");
if (orgName.value.trim().length == 0) {
alert("Enter Org Name");
return false;
}
}
</script>
</head>
<body>
<form name="orgname" action="org_name" method="post">
<table align="center">
<tr align="center">
<td colspan="4"><img src="images/logo.jpg" /></td>
</tr>
<tr>
<td>Organization :</td>
<td><input type="text" id="txtOrgName" name="txtOrgName" /><label style="color: red;">*</label></td>
</tr>
<tr>
<td align="center" colspan=2><br/><input type="submit" name="btnOrgName" id="btnOrgName"
value="Validate" onclick="return validateOrg();" /></td>
</tr>
</table>
<p align="center"><label id="lblError" style="color: red;">Error Message.</label></p>
</form>
</body>
</html>
I am using Java with Eclipse.
Don't mix and match the different execution scopes.
The serlvet and the JSP page are executed on server side (actually the JSP page is compiled to a servlet, too). Once the HTTP request is finished all request based objects are discarded, including the request attributes.
In the end it is a templating engine producing HTML text.
This HTML text (with embedded JavaScript) is executed by the client's browser. This execution scope is totally different to your server request scope, which has created this HTML page. So in your JavaScript code all the Java objects used to create that page on server side are unknown and unaccessable.
So you have two alternatives.
While creating the HTML include enough information to recreate your server side object. E.g. if you have a Person object with name and age attributes, you can include name and age as hidden form fields. After submitting the form you can recreate the Person object with the hidden field values coming in as request parameters.
Pro: Simple to implement.
Con: Only feasable for small data. Data is exposed to the client and can be manipulated.
Store the object on server side inside the session.
Pro: Data is not exposed to the client.
Con: Implementation more complex because of possible concurrent access to the session variables (browser can do multiple requests for the same session at the same time).
I was wondering how I can print an error message to the user in the case he/she entered the wrong passowrd in JSP. Given that I have the form set up and validation works, I am trying to add this one check but the output is printed to the standard out ie console, however, I would like for it to be printed to the screen that the user is viewing. Here's my code for authentication:
public boolean verify (String username, String password) {
if (!password.equals("1234")) {
System.out.println("Wrong password!\n");
return false;
}
return true;
}
EDIT: LoginProcessing.java calls the method above and checks the boolean value (logedin), if it is not set I execute the code below, but it still doesn't print to the screen where user can see it.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// skipping initializations for brevity
if (logedin) {
// do stuff
}else {
System.out.println("Wrong password!\n");
response.sendRedirect("login.jsp");
return;
}
}
EDIT 2: Here's what my code looks like in login.html to which I redirect in the code above from the doPost() method, except I removed the println() method.
<%# 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>Login Using JSP</title>
</head>
<body>
<form action="login" method="post">
Please enter your username: <input type="text" name="username"><br>
Please enter your password:<input type="password" name="password"><br>
<input type="submit">
</form>
<c:if test="${!loggedin}">
Sorry. Wrong user name or password
</c:if>
</body>
</html>
In your servlet method:
// check the credentials
boolean loggedIn = verify(username, password);
// store the result in a request attribute, so that the JSP can retrieve it
request.setAttribute("loggedIn", loggedIn);
// let a JSP display the result
request.getRequestDispatcher("/loginResult.jsp").forward(request, response);
In the JSP (using the JSTL), test the value of the loggedIn request parameter:
<c:if test="${loggedIn}">
Congratulations: you're now logged in.
</c:if>
<c:if test="${!loggedIn}">
Sorry. Wrong user name or password
</c:if>
I have a Person model attribute that contains a list of emails.
I've created some JavaScript code that deletes elements from an HTML list of emails. This is pure JavaScript client side code, no AJAX call.
After submitting, I don't understand why I get all the emails in the corresponding #Controller method, even the ones that were deleted in the HTML.
Can anyone please explain?
JSP
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" href="<c:url value="/styles/resume.css"/>" type="text/css"></link>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"></link>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="/resume/js/jquery.editable-1.0.1.js"></script>
<title>Resumes manager</title>
<script>
$(document).ready(function() {
$('.trash').click(function() {
$(this.parentNode).remove();
});
});
</script>
</head>
<body>
<h1>Personal data</h1>
<form:form modelAttribute="person" action="/resume/person/edit/save" id="personForm" method="post" >
<table>
<tr>
<td>Email addresses:</td>
<td colspan="4">
<ol id="emails">
<c:forEach items="${person.emails}" varStatus="status">
<li><form:hidden path="emails[${status.index}].order" class="emailsDisplayOrder"></form:hidden><form:input path="emails[${status.index}].label"></form:input><form:input type="email" path="emails[${status.index}].value"></form:input><input type="image" src="/resume/images/trash.png" class="trash" value="${status.index}"></input></li>
</c:forEach>
</ol>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Controller
#Controller
#SessionAttributes(types={Person.class}, value={"person"})
public class PersonController {
private final static String PERSON_VIEW_NAME = "person-form";
private ResumeManager resumeManager;
#Autowired()
public PersonController(ResumeManager resume) {
this.resumeManager = resume;
}
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
#RequestMapping(value="/person/edit/save")
public String save(#ModelAttribute(value="person") Person p, BindingResult result, SessionStatus status) {
new PersonValidator().validate(p, result);
Collections.sort(p.getEmails()); //this collection still contains client-side dropped objects
this.resumeManager.savePerson(p);
return PERSON_VIEW_NAME;
}
}
Explanation
When you load a page with <form:form modelAttribute="person" ...>, there are two cases :
case 1 : if person doesn't exist, it creates an empty Person
case 2 : if person already exists, it uses it
In all cases, when a page is loaded, there is an existing person.
When you submit a form, Spring MVC updates this existing person only with the submitted information.
So in case 1, if you submit email 1, 2, 3 and 4, Spring MVC will add 4 emails to the empty person. No problem for you in this case.
But in case 2 (for example when you edit an existing person in session), if you submit email 1 and 2, but person has already 4 emails, then Spring MVC will just replace email 1 and 2. Email 3 and 4 still exist.
A possible solution
Probably not the best one, but it should work.
Add a remove boolean to the Email class :
...
public class Email {
...
private boolean remove; // Set this flag to true to indicate that
// you want to remove the person.
...
}
In the save method of your controller, remove the emails that have remove set to true.
Finally, in your JSP, add this hidden field :
<form:hidden path="emails[${status.index}].remove" />
And tell your Javascript to set the input value to true when the user clicks to delete the email.
Alternate solution to Jerome Dalbert one
Jerome's solution should work (thanks again for clear answer and solution), but I didn't want to modify business model.
So here is the way I found out: mark HTML elements to remove using java-script and actually remove it using ajax calls at form submit (I initially avoided ajax to keep model unchanged until user submits, but this solutions preserves that requirement).
JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" href="<c:url value="/styles/resume.css"/>" type="text/css"></link>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"></link>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="/resume/js/jquery.editable-1.0.1.js"></script>
<title>Resumes manager</title>
<script>
$('.sortable').sortable({
update: function(event,ui) {
var liElements = this.getElementsByTagName('li');
$(liElements).each(function(i, liElement) {
var orderElements = liElement.getElementsByClassName('order');
$(orderElements).each(function (j, orderElement) {
orderElement.value = i;
});
});
}
});
$('.trashable').click(function() {
$(this.parentNode.childNodes).each(function(index, element) {
if(element.src.match(/trash.png/) != null) {
element.src = '/resume/images/back.png';
this.parentNode.className = 'trashed';
} else if(element.src.match(/back.png/) != null) {
element.src = '/resume/images/trash.png';
this.parentNode.className = '';
} else {
element.disabled = !element.disabled;
}
});
});
function trash(element) {
var sfx = element.alt;
var lnk = ('/resume/person/edit/').concat(sfx);
$.ajax({
url: lnk
});
}
$('#personForm').submit(function() {
var trashed = $(this).find('.trashed');
$(trashed).each(function(index, element) {
var img = $(element).find('.trashable');
var tmp = $(img)[0];
trash(tmp);
});
});
});
</script>
</head>
<body>
<h1>Personal data</h1>
<form:form modelAttribute="person" action="/resume/person/edit/save" id="personForm" method="post" >
<table>
<tr>
<td>Email addresses:</td>
<td colspan="4">
<ol class="sortable">
<c:forEach items="${person.emails}" varStatus="status">
<li><form:hidden path="emails[${status.index}].order" class="order"></form:hidden><form:input path="emails[${status.index}].label"></form:input><form:input type="email" path="emails[${status.index}].value"></form:input><img src="/resume/images/trash.png" class="trashable" alt="dropEmail/${person.emails[status.index].id}"></img></li>
</c:forEach>
</ol>
</td>
</tr>
<tr><td colspan="5"><form:button name="save" value="${person.id}">${person.id == 0 ? 'save' : 'update'}</form:button></td></tr>
</table>
</form:form>
</body>
</html>
Controller:
#Controller
#SessionAttributes(types={Person.class}, value={"person"})
public class PersonController {
private final static String PERSON_VIEW_NAME = "person-form";
private ResumeManager resumeManager;
#Autowired()
public PersonController(ResumeManager resume) {
this.resumeManager = resume;
}
#InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
#RequestMapping(value="/person/edit/{id}")
public String edit(#PathVariable("id") long personId, Model model) {
Person p = this.resumeManager.getPersonById(personId);
if(p != null) {
model.addAttribute("person", p);
return PERSON_VIEW_NAME;
} else {
return "redirect:/";
}
}
#RequestMapping(value="/person/edit/save")
public String save(#ModelAttribute(value="person") Person p, BindingResult result, SessionStatus status) {
new PersonValidator().validate(p, result);
Collections.sort(p.getEmails());
this.resumeManager.savePerson(p);
return PERSON_VIEW_NAME;
}
#RequestMapping(value="/person/edit/dropEmail/{id}")
#ResponseBody
public void dropEmail(#ModelAttribute(value="person") Person p, #PathVariable("id") long id) {
int i = 0;
for(Email e : p.getEmails()) {
if(e.getId() == id) {
p.getEmails().remove(i);
break;
}
i++;
}
}
}
I want to disable the jQuery event if a Text box is in focus. I am using following code. If a user is entering any text in text field then if by change the cursor moves to the image then it will reset the text in text field to the value shoot by event. I don't want to the event to execute if text field is in focus.
<!DOCTYPE html>
<html>
<head>
<style>span {display:none;}</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="team" />
<script>
$("input").focusin(function() {
document.getElementById("team").value = "I am in Focus Dont shoot events PLZ";
}
);
$(document).ready(function() {
$("img").mouseover(function(event) {
if(event.target.name != '')
{
document.getElementById("team").value = event.target.name;
}
//alert(event.target.name);
});
});
</script>
<img src="http://1.bp.blogspot.com/-bVD6mGlH_ik/TnHV75bw9KI/AAAAAAAAB84/1hJU7WJuU8k/s400/fewr.jpg" name="I" />
</body>
</html>
I have already tried following function
$("input").focusin(function() {
document.getElementById("team").value = "I am in Focus Dont shoot events PLZ";
});
Now I am using below code but still not working. Please help me.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<img src="http://1.bp.blogspot.com/-bVD6mGlH_ik/TnHV75bw9KI/AAAAAAAAB84/1hJU7WJuU8k/s400/fewr.jpg" name="Ihhhhhhhhhhhhhhh" id="myimage" />
<input id="theone">
<input type="image" src="http://www.clker.com/cliparts/e/2/a/d/1206574733930851359Ryan_Taylor_Green_Tick.svg.thumb.png" id="bind">
<input type="image" src="http://www.clker.com/cliparts/4/3/1/f/1195436930767206781not_ok_mark_h_kon_l_vdal_01.svg.thumb.png" id="unbind">
<script>
$("#unbind").click(function(event) {
$("img").off();
alert("off");
});
$("#bind").click(function(event) {
$("img").on();
alert("on");
});
$("img").mouseover(function(event) {
if(event.target.name != '')
{
document.getElementById("theone").value = "done";
}
//alert(event.target.name);
});
</script>
</body>
</html>
Just put one condition in mousehover event...
Enter Text in text box if textbox is not focus using this code !$("#team").is(":focus")
here is the demo : http://jsfiddle.net/s8zxY/1/