I'm doing a login page with Spring MVC in server and JS & Ajax in client. I don't know what's wrong, the code of the server executes but don't return nothing.
login.html
<script type="text/javascript">
$(function() {
$(".loguser").click(function() {
var user = $("#login").val();
var pass = $("#pass").val();
$.ajax({
method: "POST",
url : "${prefix}loginUser",
data : "username=" + user + "&password=" + pass,
dataType : "json",
success: function(data){
if (data.res == "YES") alert("ok");
else alert("NOPE");
}
});
})
})
</script>
<table id="userData" class="center">
<tr id="usernametr">
<th><label for="user">Nombre de usuario: </label></th>
<th><input id="login" type="text" name="login" value=""
placeholder="Name" required /></th>
</tr>
<tr>
<th><br /></th>
</tr>
<tr>
<th><label for="pass">Clave de usuario: </label></th>
<th><input id="pass" type="password" name="pass" value=""
placeholder="Password" required /></th>
</tr>
<tr>
<th><button class="loguser">Acceder</button></th>
<th><input type="button" name="lost"
value="He perdido mi clave" /></th>
</tr>
</table>
HomeController.java:
#RequestMapping(value = "/loginUser")
#ResponseBody
#Transactional
public String loginUser(#RequestParam("username") String username,
#RequestParam("password") String pass, HttpServletRequest request, Model model) {
logger.info("Trying to log in {} {}", username, pass);
if (username.length() > 3) {
logger.info("ok");
return new String("[\"res\": \"YES\"]");
} else {
logger.warn("nope");
return new String("[\"res\": \"NOPE\"]");
}
}
I tryiend returning EntityResponse too but nothing change. Springs console prints the logger info or warn but Firefox's javascript console doesnt.
You must specify Requestmethod in controller like
#RequestMapping(value = "/loginUser", method = RequestMethod.POST)
You must Return Json Values In { }
Braces
Related
I am trying to delete the data by checking multiple checkboxes, but when I choose the checkboxes from the screen and hit the delete button then the only top row gets deleted. Means no matter which row I select it deletes the only first entry of the table. Please help me.
Delete.servlet
delPage = request.getParameter("delPage");
patientId = request.getParameter("pid");
if(delPage.equals("true")) {
int p = Integer.parseInt(patientId);
patientDao = new PatientDAO();
boolean b = patientDao.isPatientDeleted(p);
if (b) {
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}else
System.out.println("Patient deleting failed ... ! ");
}
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
Masterpage.jsp
<script type="text/javascript">
function addNewPatient(){
debugger;
var addNewPat = "true";
document.form.method = "POST";
document.form.action = "addPatient?newPage="+addNewPat;
document.form.submit();
}
function deletePatient(){
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}">
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
<i class="trash ulternate icon"></i>
Delete
</div>
DeletePatientServlet.java
public class DeletePatientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private PatientBean patient = null;
private PatientDAO patientDao = null;
String delPage = null ;
String patientId = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
System.out.println("Patient Deleted Successfully .... !");
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
}
}
Okay so there are a bunch of mistakes in your code. I'll start with the jsp...
You are trying to pass parameters via the servlet url with a POST request
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
You cannot pass data in the url with post requests. You need to change your servlet to a GET if you want to do this.
Also, in this line:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)">
you are passing a value to your deletePatient method. But your deletePatient method does not have an option to pass a value:
function deletePatient(){ // no value being passed here?
debugger;
var pid = document.getElementById("del").value;
var delpatient = "true";
document.form.method = "POST";
document.form.action = "deletePatient?delPage="+ delpatient+"&pid="+pid;
document.form.submit();
}
You can also just do:
${user.patientId}
instead of:
<c:out value="${user.patientId}"></c:out>
Another problem with your code is this, you cannot have multiple elements in your HTML with the same id. This is illegal HTML, and it's the reason why you are getting the same id each time:
<c:forEach var="user" items="${patients}">
<tr>
<td>
<input type="checkbox" id="del" value="<c:out value="${user.patientId}"> //no this is bad.
</c:out>" >
</td>
<td>
<input type="hidden" id="delpatient"><c:out value="${user.patientId}">
</c:out>
<td><c:out value="${user.patientName}" /></td>
<td><c:out value="${user.patientAddress}" /></td>
<td><c:out value="${user.patientPhone}" /></td>
</tr>
</c:forEach>
Your delete button is not even inside your loop, so it will not work:
<div class="ui small button" onClick="deletePatient(<c:out value="${user.patientId}"></c:out>)"> //this will pass the same id each time
<i class="trash ulternate icon"></i>
Delete
</div>
Try something like this instead (for delete only):
<script type="text/javascript">
function deletePatient(e){
var patientid = e.getAttribute("data-patientid");
deletePatientForm(patientid);
}
function deletePatientForm(pid) {
var form = document.createElement("form");
var input = document.createElement("input");
form.method = "POST";
form.action = "deletePatient";
input.value=pid;
input.name="pid";
form.appendChild(input);
document.body.appendChild(form);
form.submit();
}
</script>
<c:forEach var="user" items="${patients}">
<tr>
<th>id</th>
<th>name</th>
<th>address</th>
<th>phone</th>
<th></th>
<tr>
<tr>
<td>${user.patientId}</td>
<td>${user.patientName}</td>
<td>${user.patientAddress}</td>
<td>${user.patientPhone}</td>
<td>
<div class="ui small button" onClick="deletePatient(this)" data-patientid="${user.patientId}"><i class="trash ulternate icon"></i> Delete</div>
</td>
<tr>
</c:forEach>
Then in the post of your servlet:
int patientId = Integer.parseInt(request.getParameter("pid"));
PatientDAO patientDao = new PatientDAO();
patientDao.isPatientDeleted(patientId);
RequestDispatcher rd = request.getRequestDispatcher("/Pages/MasterPage.jsp");
rd.forward(request, response);
If you have any problems or questions let me know.
I am new to Spring.
I am trying to show error messages on jsp for the wrong user and password by using BindingResult. But the error messages are not showing.
Please suggest me what I is wrong in the below code.
JSP
<script type="text/javascript">
function loginUser() {
$('#loginForm').submit();
}
</script>
</head>
<body>
<form:form action="login.test" id="loginForm" commandName="loginForm" method="POST">
<div class="brand_area"></div>
<div class="content_area">
<table style="top: 360px; position: relative; margin-left: 333px;">
<tr id="uNameID">
<td class="label">User Name:</td>
<td><form:input id="userNameID" path="userName" class="textInput" /></td>
<td><form:errors path="userName" class="error"/></td>
</tr>
<tr id="pID">
<td class="label">Password:</td>
<td><form:password id="passwordID" path="password" class="textInput" /></td>
<td><form:errors path="password" class="error"/></td>
</tr>
<tr>
<td></td>
<td><span id="saveButton" class="loginButton"
onclick="loginUser()"> <span>Login</span>
</span></td>
</tr>
</table>
</div>
</form:form>
Controller
#RequestMapping(value = "login.test", method = RequestMethod.POST)
public String processForm( LoginForm loginForm, BindingResult result, ModelMap model, HttpSession session) throws SQLException {
String resultedPage;
model.addAttribute("l_nodes", reportService.getAllLiveNodes());
model.addAttribute("s_nodes", reportService.getAllStaticReportNodes());
User user = userService.getUserByName( loginForm.getUserName() );
if( user != null ){
session.setAttribute("userID", user.getUserID());
if( loginForm.getPassword().equals( user.getPassword() ) ){
resultedPage = "home/userHome";
}else{
result.rejectValue( "password", "login.passwordNotValid");
resultedPage = "redirect:login.test";
}
}else{
result.rejectValue( "userName", "login.userNotValid");
resultedPage = "redirect:login.test";
}
return resultedPage;
}
Thanks
In case anyone else research the same...
Add the hasBindErrors tag to your JSP:
<spring:hasBindErrors name="loginForm">
<c:forEach var="error" items="${errors.allErrors}">
<b><spring:message message="${error}" /></b>
<br/>
</c:forEach>
</spring:hasBindErrors>
Well, i generally send back the values using the Model object.
May be this answer might help you.
I've got a jsp file with two text fields (signUp and post). Now, I want the post text and the signUp text to be called to a servlet. Normally its going with request.getParameter(), but now I want the post text going to the servlet with an AJAX function and the signup text with the normal way (that means the name of the input within the jsp file and then request.getParameter).
Is it possible to mix both parts within one servlet because i have this:
<form name="form1" method="POST" action="PostWallServlet" id="form1">
form1 is the ajax code. I don't know how this should work. Normally there stands
`<form action="PostWallServlet" method="POST" >
and everything is callable through the Servlet. But, for now I don't know how I can mix up both components.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PostWall pw=new PostWall();
SimpleDateFormat df = new SimpleDateFormat("YYYY/MM/DD hh:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println("Current Date Time : " + df.format(cal.getTime()));
String message = "";
String sender = request.getParameter("sender");
String post = request.getParameter("message");
String a= df.format(cal.getTime()).toString();
pw.setSender(sender);
pw.setPost(post);
pw.setDate(a);
if (pwi.addPost(pw)) {
message = "Student Successfuly Added";
} else {
message = "Student Adding Failed";
}
//RequestDispatcher rd = request.getRequestDispatcher("post.jsp");
//rd.forward(request, response);
}
$(document).ready(function(){
$('#Add').click(function(){
sendData();
});
});
function sendData(){
var mge = $('#newText').val();
alert(mge);
$.ajax({
type: "POST",
url: "PostWallServlet",
data: { message : mge }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
<form name="form1" method="GET" action="PostWallServlet" id="form1"></form>
<table border="0" width="100%">
<tr>
<td colspan="3"> ${message}</td>
</tr>
<tr>
<td>Sender</td>
<td>:</td>
<td><input type="text" name="sender" value="" size=20/></td>
</tr>
<tr>
<td>Post</td>
<td>:</td>
<td><input type="text" name="post" value="" size=500 id="newText"/ ></td>
</tr>
<tr>
<td></td>
<td></td>
<td><input type="submit" value="Add" name="Add" /></td>
</tr>
</table>
Any solutions?
Put your ending tag for form AFTER all your inputs:
<form name="form1" method="GET" action="PostWallServlet" id="form1">
...
<td><input type="text" name="sender" value="" size=20 /></td>
...
<td><input type="text" name="post" value="" size=500 id="newText" /></td>
...
<td><input type="submit" value="Add" name="Add" /></td>
...
</form>
Your inputs must be INSIDE the form, not after the form.
Also make sure to end your input tags with /> not / >. You have a space between / and > on one of them.
For the Ajax part you need to give your inputs ids as well as names:
<td><input type="text" name="sender" id="sender" value="" size=20 /></td>
And then in your Ajax function for data:
data: { sender: $('#sender').val(), post: $('#post').val() }
Hi I have a JSP page as below,jsp page contains one table in which i am displaying data by iterating through the list from the action class.
each row of a table has refresh button at row level.jsp is as shown below.
<script type="text/javascript">
function refreshRecord(id)
{
$(document).ready(function(){
var fileId=id;
alert(fileId);
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data: {fileId:fileId},
success:function(data){
alert("returned from action");
}
});
});
}
</script>
</head>
<body>
<%#include file="index1.html" %>
<div class="box2">
<div class="box3">
<s:property value="userId"/>
</div>
<center><h2>FILE STATUS</h2></center>
<center>
<form action="Upload" method="post" enctype="multipart/form-data">
<label for="myFile" class="text">Upload your file:</label>
<input type="hidden" name="upload" value="upload"/>
<input type="file" name="myFile" size="40" class="file"/>
<input type="submit" value="Upload" class="button"/>
<input type="submit" value="Refresh" class="button"/>
</form>
</center>
<center>
<table border="1" class="displaytab" id="rtable">
<s:if test="%{user.roles == 'admin'}">
<tr> <td colspan="10" style="background:#7395B8;color:white;font-size:18px;font-weight:bold;"><center>Admin</center></td></tr>
</s:if>
<tr>
<th>FileId</th><th>File Name</th><th>Upload Date</th><th>#Records</th><th>Status</th><th>Estimated Time</th><th>Processed Records</th><th>Generate Report</th><th></th><s:if test="%{user.roles == 'admin'}"><th>Controls</th></s:if>
</tr>
<s:iterator value="uploadList" var="m">
<tr>
<td><s:property value="%{#m.fileId}" /></td>
<td><s:property value="%{#m.fileName}" /></td>
<td><s:property value="%{#m.uploadDate}" /></td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><s:property value="%{#m.status}" /></td>
<td>tbd</td>
<td><s:property value="%{#m.numRecords}" /></td>
<td><img src="images/generate.png" title="Generate Report"> </td>
<td><img src="images/refresh.png" title="Refresh" onclick="refreshRecord(<s:property value="%{#m.fileId}" />);"></td>
</tr>
</s:iterator>
</table>
</center>
at the refresh button onclick i am calling onclick="refreshRecord();"> this javascript method it will go to action class get the latest values of status and # records.
through ajax i am passing this fileId to action class checkStatusAndNumRecsAction.java to get the updated status and #records column values from database
my action class is as below
import com.mxui.db.api.PersistenceService;
import com.mxui.db.service.*;
import com.opensymphony.xwork2.ActionSupport;
public class checkStatusAndNumRecsAction extends ActionSupport
{
/**
*
*/
private static final long serialVersionUID = 6450400234448854648L;
private String status;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
private long numRecords;
public long getNumRecords()
{
return numRecords;
}
public void setNumRecords(long numRecords)
{
this.numRecords= numRecords;
}
private String fileId;
public String getFileId()
{
return fileId;
}
public void setFileId(String fileId)
{
this.fileId = fileId;
}
public String execute()
{
PersistenceService svc = PersistenceServiceImpl.getInstance();
status = svc.getStatusByFileId(fileId);
System.out.println("status is "+status);
numRecords = svc.getNumRecordsByFileId(fileId);
System.out.println("num records are "+numRecords);
return "SUCCESS";
}
}
this action get the values of status and #records from database
what i want to do is i should get the values of status and numRecords from action class to jsp using ajax and replace the tables of status and #records column with the new retrieved data from action class.on click of that row refresh button.
In the function defined in success: you will need to write javascript that replaces the contents of the <TD> for the record that has been refreshed. You can identify the <TD> by using the fileId. For example: <td id="%{#m.fileId}"><s:property value="%{#m.status}" /></td> and using jQuery search for this fileId and by using replaceWith substitute the new value of status. For example: $("td#fileId").replaceWith(newStatusData);
Depending of the format of the data returned to the AJAX call you might need to do some parsing in order to extract the data that you want.
EDIT: Just seen your comment. Can you control to format of the data returned to the AJAX call? If so you might like to format in JSON. Although a simple CSV format would be sufficient. Also can you post an example of the data sent back to the AJAX.
You appear to be missing a servlet that recuperates the values from the DB and sends then to the client. In your servlets doPost() method you need to call the methods that return the status of the record and number of records and return them to the client. I imagine servlet code something like this:
#WebServlet(checkStatusAndNumRecs)
class MyServlet extends HttpServlet
protected doPost(HttpServletRequest request, HttpServletResponse)
throws IOException, ServletException{
String fileId = request.getParameter("fileId");
String status = XXXXX.getStatus(fileId);
String numRec = XXXXX.getNumRecords();
String responseTxt = status + "," + numRec;
response.out.println(responseTxt);
response.getWriter().println(responseTxt);
}
XXXXX is the object that encapsulates the calls to the DB to retrieve the values of status and record number.
And also you need to change to jQuery AJAX to something like this:
$.ajax({
type: "post",
url: "checkStatusAndNumRecs",
data: "fileId=" + fileId,
success: function(data){
var rData = data.split(",");
$("td#fileId").replaceWith(rData[0]);
// Do the same for the record number data: rData[1]
}
I have a project using Spring and i need to create admin page using jQuery. I have a table with all users and i have a button "delete". When i click it user should be deleted from the database. Without script everything works fine but with script i can't figure out how do i make user deleted from database and how to send user login to controller. I could only remove row from table, but when i refresh the page user is still there.
Could anyone please help me how to delete user from db within script?
Table
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
<a class="confirm" href="delete/${user.login}">Delete</a></td>
</tr>
</c:forEach>
</table>
Controller without script(it's commented now, but it works fine)
#RequestMapping("/delete/{userLogin}")
public String deleteUser(#PathVariable("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return "redirect:/welcome";
}
Controller for script
#Controller
public class SpringController {
#Autowired
private UserService userService;
#RequestMapping(value = "/delete/{userLogin}", method = RequestMethod.POST)
#ResponseBody
public boolean updateUser(#RequestParam("userLogin") String userLogin) {
userService.remove(userService.findByLogin(userLogin));
return true;
}
}
Script
<script>
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
if(conBox){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
});
} else {
$(this).dialog("close");
}
});
});
</script>
Here's what worked for me:
Table (check "Delete" link)
<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
<tr>
<th>Login</th>
<th>First Name</th>
<th>Last Name</th>
<th>Birthday</th>
<th>Role</th>
<th>Actions</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.login}</td>
<td>${user.firstname}</td>
<td>${user.lastname}</td>
<td>${user.birthday}</td>
<td><c:if test="${user.roleid==1}">Admin</c:if>
<c:if test="${user.roleid==2}">User</c:if></td>
<td>Edit
Delete
</tr>
</c:forEach>
</table>
Controller
#RequestMapping(value="/delete/{userLogin}", method=RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public void deleteUser(#PathVariable String userLogin) {
userService.remove(userService.findByLogin(userLogin));
}
Script
<script>
$(document).ready(function() {
var deleteLink = $("a:contains('Delete')");
$(deleteLink).click(function(event) {
var conBox = confirm("Are you sure ?");
if(conBox){
$.ajax({
url: $(event.target).attr("href"),
type: "DELETE",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function() {
var tr = $(event.target).closest("tr");
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();})
}
});
} else {
event.preventDefault();
}
event.preventDefault();
});
});
</script>
On your code, you are not calling the needed url to call the handler method that will delete the user. I assume you want to do this using ajax? it would also help if you can add your markup.
What you can do is(for now since your question and your code seems pretty vague)
$(document).ready(function() {
$("#userBase .confirm").on("click",function() {
var conBox = confirm("Are you sure ?");
var userLogin = "sampleOnly" //maybe somewhere in your html you have this
var url = "mycontroller/delete/"+userLogin //A rough guess for now
if(conBox){
$.post(url+userLogin,function(e){
var tr = $(this).closest('tr');
tr.css("background-color","#000000");
tr.fadeIn(1000).fadeOut(200, function(){
tr.remove();
})
});
} else {
$(this).dialog("close");
}
});
});
If you want to send data using jQuery, I'd suggest using AJAX with REST. Here's how I'd do it:
#RequestMapping(value="delete.json", method=RequestMethod.DELETE, produces="application/json")
#ResponseBody
public Boolean deleteAjaxMultiple(#RequestBody String[] gotten)
{
for (String login : gotten)
userService.remove(userService.findByLogin(login));
return true;
}
This controller handles JSON requests, in this case an array of logins. Then you'll just have to call it from JavaScript like this:
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: '/delete.json', //or whatever url works for you
type: 'DELETE',
data: JSON.stringify(arr), //arr is an array of logins you want to delete
success: function(data) {
location.reload(true); //or do whatever you want on success
}
});
You need to set up Jackson for this. For more info see this and this.