Unable to return to the desired URL or view of the JSP - forms

<script type="text/javascript" src="${pageContext.request.contextPath}/resources/js/jquery.validate.min.js"></script>
<script>
function setHiddenVal(){
var goAhead = true;
var myVal="I am hidden value";
document.getElementById("secretValue").value = myVal;
if (goAhead == true) {
document.forms["register-form"].submit();
}
}
</script>
</head>
<body>
<!--Main Container Starts here-->
<div class="main_container">
<div class="header">
<div class="right_panel">
<h2 align="center"><u>User Master</u></h2>
<div class="top-form">
<div>
**<form:form action="/usermaster" modelAttribute="CustomerForm" id="register-form" method="POST">**
<table cellspacing="0" cellpadding="0" border="" class="form1">
<tr>
<td class="label">Name:</td>
<td>
<form:input path="firstname"/>
</td>
</tr>
<tr>
<td class="label">Password:</td>
<td>
<form:input path="password"/>
</td>
</tr>
</tbody>
</table>
<div>
<table>
<tr>
<td> </td>
<td>
<input type="button" class="btn blue px16" value="Search" />
<input type="button" name="submit" id="btnsubmit" value="Submit" onclick="setHiddenVal();"/>
<input type="button" class="btn blue px16" value="Clear" />
<input type="button" class="btn blue px16" value="Change Password" />
<input type="button" class="btn blue px16" value="Manage User Notification Profile" />
</td>
</tr>
</table>
</div>
</form:form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</body>
</html>
so above one is my code for jsp and below is the code of controller
#RequestMapping(value={"/usermaster" }, method = RequestMethod.POST)
public final String addUserMaster(#ModelAttribute("CustomerForm") CustomerForm pricing, Map<String, Object> map,
Model model, HttpServletRequest request) {
System.out.println("the first name is "+pricing.getFirstname());
System.out.println("the password is "+pricing.getPassword());
return "usermaster";
}
#RequestMapping(value={"/showusermaster" }, method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
But my page gets open up using a popup with the url:
C:\Users\ganganshu.s\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\YW6383E8\usermaster
so it should open like
http://localhost:8080/enbee/usermaster
Could you please tell me what should I put in the form action.. as I think some mistake is there in the form action does in spring MVC we put the action like in the case I mentioned above.
Spring confg file is given below :
<mvc:interceptors>
<bean class="com.enbee.admin.interceptor.AuthenticationInterceptor" />
<!-- Declare a view resolver-->
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="1" />
and the jsp name is usermaster.jsp
and in the sidemenu.jsp I have changed to this :
<li>User Master</li>

Change the method parameter of RequestMapping annotation to RequestMethod.POST:
#RequestMapping(value="/usermaster", method = RequestMethod.POST)
public final String addUserMaster(...){
...
}
so that when you submit your form to the URL /usermaster using method="POST" this method will get executed.
You also need to have a method (mapped to an URL) that will show this page to the user. You can use a method as below for this:
#RequestMapping(value = "/showusermaster", method = RequestMethod.GET)
public String showPage(ModelMap model){
model.addAttribute("CustomerForm", new CustomerForm());
return "usermaster";
}
With this method in place, the URL
http://localhost:8080/enbee/showusermaster
will show the usermaster.jsp page to the user. Now when you submit this form, the above addUserMaster method will be invoked.
You don't have to create new jsp file. The url /showusermaster will return the usermaster.jsp to the user, where the user can add form values and submit the form:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<c:url var="submitUrl" value="/usermaster">
<form:form id="form" action="${submitUrl}" modelAttribute="CustomerForm" method="POST">
Now when the user clicks on the submit button, this form will be submitted to /usermaster URL and will be handled by addUserMaster method.

Try to specify the content type returned by your controller method, adding produces = "text/html" param to your #RequestMapping annotation.

Related

Thymeleaf, default values does not appear in my update form

I'm learning java and I'm practicing with thymeleaf. I made an little app where I have a list of persons (arraylist). I can add a person through a form but also edit a person from the list to update the person's firstname, lastname or birthdate through a form. Here is my problem I want when I edit a person to have its default values(firstname, lastname, bithdate) on the update form so that we can then change only the fields of interest. I have this code:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Update Person</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Update a Person:</h1>
<!-- some tests I made to test if the value appears in the field -->
<!-- <input type="text" name="id" th:value="${person.id}" /> -->
<!-- <input type = "text" name = "firstName" th:value = "${person.firstName}" /> -->
<!-- <input type = "text" name = "sometext" th:value = "hello world" /> -->
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
<br/>
<!-- Check if errorMessage is not null and not empty -->
<div th:if="${errorMessage}" th:utext="${errorMessage}"
style="color:red;font-style:italic;">
...
</div>
</body>
</html>
None of my default values appears in the fields except for the id. Whether I use th:field="{id}" or name="id" th:value="${person.id}". Both synthax work but the others (ie: th:field="{firstName}" or name = "firstName" th:value = "${person.firstName}" same goes for lastname and birthdate), nothing works. I even tried th:value = "hello world" (commented in the above code), it does appear! So why my person firstname, lastname, bithdate don't appear? What is wrong? My person.list html works though:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Person List</title>
<link rel="stylesheet" type="text/css" th:href="#{/css/style.css}"/>
</head>
<body>
<h1>Person List</h1>
Add Person
<br/><br/>
<div>
<table border="1">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date of Birth</th>
<th>Edit</th>
<th>Delete Name</th>
</tr>
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
<td><a th:href="#{/updatePerson/{id}(id=${person.id})}">
<span>
<img src="https://img.icons8.com/clouds/40/000000/edit.png">
</span>
</a></td>
<td>
<form th:action="#{/deletePerson}" th:method="POST">
<input type = "hidden" name = "firstName" th:value = "${person.firstName}" />
<input type = "hidden" name = "lastName" th:value = "${person.lastName}" />
<input type = "hidden" name = "id" th:value = "${person.id}" />
<input type = "hidden" name = "birthDate" th:value = "${person.birthDate}" />
<button type = "submit" >
<span>
<img src="https://img.icons8.com/metro/26/000000/delete.png" />
</span>
</button>
</form>
</td>
</tr>
</table>
</div>
<div>
<form th:action="#{/changeDao}" th:method="POST">
<select name="daoChoice">
<option th:value="none" disabled>Choisissez votre Dao</option>
<option id="jdbc" th:value="JDBC">Jdbc</option>
<option id="memory" th:value="MEMORY" th:selected="${isMemory}">Memory</option>
</select>
<button type="submit">Valider</button>
</form>
</div>
<div>
<form th:action="#{/excelLoad}" th:method="GET">
<button type="submit">Local Load</button>
</form>
</div>
<div>
<form th:action="#{/UploadFile}" method="POST" enctype="multipart/form-data">
<table>
<tr>
<td><label>Upload and Add to the table</label></td>
<td><input type="file" th:value = "file" th:name="file" /></td>
</tr>
<tr>
<td><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</div>
<div>
<form th:action="#{/exportToExcel}" th:method="POST">
<button type="submit">Export to Excel</button>
</form>
</div>
</body>
</html>
Above my personList.html, person's firstName lastName and birthdate is printed correctly with this code:
<tr th:each ="person : ${list}">
<td th:utext="${person.firstName}">...</td>
<td th:utext="${person.lastName}">...</td>
<td th:text="${#temporals.format(person.birthDate,'dd-MM-yyyy')}">...</td>
but why in my update form this is not working ?
I'm a newbie in java programming and also in thymeleaf (also newbie), so I'd really appreciate some explanations along some tips! thanks a lot!
I found it with another post where there was a simple explanation about the key/value pair in modelAddAttribute:
You can access variables value by ${key}.
Example
model.addAttribute("key", value);
Understanding that I found my mistake in my controller:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("person", person);
return "updatePerson";
}
Before it was:
#RequestMapping(value = { "/updatePerson/{id}" }, method = RequestMethod.GET)
public String showUpdatePersonPage(#PathVariable("id") int id, Person person, Model model) {
person = personDao.findPerson(id);
model.addAttribute("personToModify", person);
return "updatePerson";
}
And in my html the code was:
<form th:action="#{/updatePerson/{id}(id=${person.id})}"
th:object="${person}" method="POST">
First Name:
<input type="text" th:field="*{firstName}"/>
<br/>
Last Name:
<input type="text" th:field="*{lastName}" />
<br/>
Date of Birth (DD/MM/YYYY):
<input type="date" th:field="*{birthDate}" />
<br/>
ID:
<input type="text" th:field="*{id}" />
<br/>
<input type="submit" value="Update" />
</form>
So that was because the key name used "personToModify" couldn't be found in the html as the object name used wasn't properly named:
th:object="${person}"
I can't see your Person class or controller but, for example, keeping it clean, you can create PersonForm class which can look like (might need to change Date)
import java.util.Date;
public class PersonForm {
private String firstName;
private String lastName;
private Date birthDate;
public PersonForm() {
}
public PersonForm(Person person) {
this.firstName = person.getFirstName();
this.lastName = person.getLastName();
this.birthDate = person.getBirthDate();
}
As you can see, it has fields which needs to populated and you set them in constructor, you can also apply validation annotations here if needed.
In your controller you would need to retrieve Person and using it, create and add PersonForm as model attribute. i.e.
#GetMapping("/person/edit/{id}") // you might not use id, might be username
public String editPerson(#PathVariable Long id, Model model) {
Person person = personRepository.getOne(id); // or service
PersonForm personForm = new PersonForm(person);
model.addAttribute("personForm", personForm);
// other stuff
// return html
}
and then change th:object="${person}" to th:object="${personForm}"
Now all th:field="*{firstName}" and others should be populated.

Check only one checkbox and uncheck previous checked checkbox

I wanted that when I change my selection in my checkbox the only selected checkbox will be selected and the previous selected checkbox will be uncheck.
My code is working but i really wanted to select only one checkbox.
In my view.
<center><table></center>
<tr>
<th><center>
List of Names</center></th>
<th colspan="3">
Actions
</th></tr>
<tr ng-repeat="role in roles">
<td>
<label>
<ion-checkbox ng-model="isChecked" ng-
change="format(isChecked,role,$index)"
ng-init="isChecked=false"><div class="wew">
{{role}}
</div></ion-checkbox>
</label>
</td>
<td>
<button ng-hide="!isChecked" ng-click="present()">P </button> </td>
<td>
<button ng-hide="!isChecked" ng-click="late()">L</button></td>
<td><button ng-hide="!isChecked" ng-click="absentss()">A</button></td>
<td><button ng-hide="!isChecked" ng-click="delete()">D</button></td>
</tr> </table>
And I think in my controller is the part where i need to change my codes to achieved the correct result.
$scope.isChecked = false;
$scope.selected = [];
$scope.format = function (isChecked, role, index) {
if (isChecked==true) {
$scope.selected.push(role);
}
else {
var _index = $scope.selected.indexOf(role);
$scope.selected.splice(_index, 1);
}
var students = $scope.selected;
console.log(students);
for( var s=0; s<students.length; s++) {
$scope.stud = [
students[s]
]
};
Thank you in advanced! I hope that someone can help in this matter.
Checkboxes are for multiple selections within a group.
Use radio buttons instead.
Example With AngularJs
This is way you can also implement.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
angular.module('app', []).controller('appc', ['$scope',
function($scope) {
$scope.selected = 'other'; //default selection
}
]);
</script>
</head>
<body ng-app="app" ng-controller="appc">
<label>SELECTED: {{selected}}</label>
<div>
<input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male
<br>
<input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female
<br>
<input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other
</div>
</body>
</html>

Groovy-grails sql.rows in gsp table

Hi i want to display a list of the results from my database in a gsp.I have put the resultes in a g:each but the result is coming to a line and not in the table.
My service is this:
def listAction(){
def sql = new Sql(dataSource)
return sql.rows ("SELECT * FROM mn")
my controller is this:
def list() {
[contacts : contactListService.listAction()]
}
and gsp
<g:each in="${contacts}" var="contact" status="i">
<td>${contact.id}</td>
<td>${contact.name}</td>
<td><g:link action="edit" id="${contact.id}" class="btn btn-info" role="button">Edit</g:link>
<g:link action="delete" id="${contact.id}" button type="button" class="btn btn-danger">Delete</g:link></td>
</g:each>
Each element should be wrapped in a new row.
<g:each in="${contacts}" var="contact" status="i">
<tr>
<td>${contact.id}</td>
<td>${contact.name}</td>
<td><g:link action="edit" id="${contact.id}" class="btn btn-info" role="button">Edit</g:link>
<g:link action="delete" id="${contact.id}" button type="button" class="btn btn-danger">Delete</g:link>
</td>
</tr>
</g:each>

calling a rest service on submission of form

I have a form which has some values. When i submit the form i want the current logged in user's userid to be passed in the path to call a rest service handler in my controller. I don't know what to write in the form action to make it happen.
my controller handler
#RequestMapping(value="/redemptionRedirect1/{userId}", method=RequestMethod.GET)
public #ResponseBody Transaction submitRedemption(#PathVariable("userId") long userId ,#ModelAttribute("redemption") Transaction transaction)
{
boolean flag;
Authentication auth =SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User user=userService.getUser(name);
transaction.setUser(user);
flag = transactionService.addRedemptionTransactions(transaction);
return transaction;
}
>
my jsp
<body>
<form id="account" action="redemptionRedirect1/${user.userId}" method="get">
<table>
<tr><td>Amount: </td><td><input type="text" maxlength="5" value='<c:out value="${amount}"/>' readonly="readonly"/></td></tr>
<tr><td>
Bank Accounts: </td><td><select id="bankaccounts">
<c:forEach items="${baccounts}" var="account">
<option value='<c:out value="${account.accountNumber}"/>'>
<c:out value="${account.name}"/>
</option>
</c:forEach>
</select>
</td></tr>
<tr><td>Demat Account: </td><td><input type="text" placeholder='<c:out value="${daccount.dematName}"/>' value='<c:out value="${daccount.dematAccountNumber}"/>' readonly="readonly"/></td></tr>
<tr><td><input type="submit" value="Confirm"/></td></tr>
</table>
<div style="visibility: hidden;"><input id="user" type="text" value='<c:out value="${user.userId}"/>'/></div>
<div id="personFormResponse"></div>
</form>
</body>

spring mvc multiple form on jsp

Hello guys is it possible to have multiple forms on single jsp and also with a single button?
Here is my jsp page where i hava two forms, i know this way it is, it only save the second form.
<html>
<head>
<title>Update General Info</title>
<script type="text/javascript">
function validateForm()
{
var name=document.getElementById("name").value;
var surname=document.getElementById("surname").value;
var email=document.getElementById("email").value;
var amka=document.getElementById("amka").value;
if (name.length == 0)
{
alert("Name must be filled out");
return false;
} else if(surname.length == 0){
alert("Surname must be filled out");
return false;
}else if(email.length == 0){
alert("Email must be filled out");
return false;
}else if(amka.length == 0){
alert("Amka must be filled out");
return false;
}
}
</script>
</head>
<body>
<h1>Update General Info</h1>
<c:if test="${!empty user}">
<c:url var="saveArticleUrl" value="/articles/updateGeneralSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="user" method="POST" >
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Team</th>
<th>Name</th>
<th>Surname</th>
<th>Username</th>
<th>Password</th>
<th>Email</th>
<th>AMKA</th>
<th>Status</th>
<th>Department</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${user.id}"></form:input></td>
<td><form:input readonly="true" path="team" value="${user.team}"></form:input></td>
<td><form:input id="name" path="name" value="${user.name}"></form:input></td>
<td><form:input id="surname" path="surname" value="${user.surname}"></form:input></td>
<td><form:input readonly="true" path="username" value="${user.username}"></form:input></td>
<td><form:input type="password" readonly="true" path="password" value="${user.password}"></form:input></td>
<td><form:input id="email" path="email" value="${user.email}"></form:input></td>
<td><form:input id="amka" path="amka" value="${user.amka}"></form:input></td>
<td><form:input id="status" path="status" value="${user.status}"></form:input></td>
<td><form:select path="department">
<c:forEach items="${departments}" var="dep">
<c:if test="${dep.dep_name==user.department }">
<OPTION selected VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
<c:if test="${dep.dep_name!=user.department }">
<OPTION VALUE="${dep.dep_name}"><c:out value="${dep.dep_name}"/></OPTION>
</c:if>
</c:forEach>
</form:select></td>
</tr>
</table>
</form:form>
</c:if>
<c:if test="${!empty phones}">
<c:url var="saveArticleUrl" value="/articles/updatePhoneSave.html" />
<form:form onsubmit="return validateForm()" modelAttribute="updatePh" method="POST" action="${saveArticleUrl}">
<table bgcolor="DBEADC" border=1>
<tr>
<th>Id</th>
<th>Phone</th>
<th>Mobile</th>
<th>Fax</th>
</tr>
<tr>
<td><form:input readonly="true" path="id" value="${phones.id}"></form:input></td>
<td><form:input id="phone" path="phone" value="${phones.phone}"></form:input></td>
<td><form:input id="mobile" path="mobile" value="${phones.mobile}"></form:input></td>
<td><form:input path="fax" value="${phones.fax}"></form:input></td>
</tr>
</table>
<input type="submit" value="Update" />
</form:form>
</c:if>
</body>
</html>
and the controllers
RequestMapping(value = "updateGeneral" , method = RequestMethod.GET)
public ModelAndView updateGeneral(#ModelAttribute("user") Users user ,#ModelAttribute("updatePh") Phone updatePh, #RequestParam("id")Integer id){
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", articleService.getUser(id));
model.put("departments", articleService.listDepartments());
//twra mpike
model.put("phones", articleService.getPhones(id));
return new ModelAndView("updategeneral",model);
}
//evala akoma ena modelattri
#RequestMapping(value = "updateGeneralSave" , method = RequestMethod.POST)
public ModelAndView updateGeneralSave(#ModelAttribute("user") Users user){
articleService.updateUser(user);
return new ModelAndView("redirect:/articles/listusers.html");
}
#RequestMapping(value = "updatePhoneSave" , method = RequestMethod.POST)
public ModelAndView updatePhonesave(#ModelAttribute("updatePh") Phone updatePh){
articleService.updatePhone(updatePh);
return new ModelAndView("redirect:/articles/listusers.html");
}
You can have multiple forms in a JSP, but you can NOT send both at the same time.
You should mix both forms and both actions, retrieve all information in the action/controller and save phone and user information. Another options would be to use Ajax to send one of the form and send the other as usually.
By the way, your problem has nothing to do with Spring.
yes of courses, you can make your button to submit both your forms. But you have do it with ajax.
You need to loop through the forms on the webpage using document.forms[i] and with each form individually call the submit
Your only option is doing for ajax, you have to realize that if you Controller method will render a page after the first submit your second submit doing by HTTP will never take effect.
function submitForm(form, index){
$.ajax({
dataType: "json",
method: "POST",
url: "your controller url",
data:$('#form').serialize(),
success: function (data) {
if(index > 0){
submitForm(form+=1, index--)
}
}
});
}
You can do following trick like
Instead of sumbit button have only normal button as
<input type="button" value="Update" onClick="submit2forms();"/>
and on click of this button call below javascript method as
<script language="javascript">
function submit2forms() {
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
</script>