Created an application. Page A displays a droplist containing list of values. If user clicks on particular account, will display a chart. We have similar button right to the acccount droplist. Those are separate JSP's. If user clicks on Page A, then selected account name should move to those 4 jsp page. I have tried via URL. But not getting. Please help.
JSP 1
<a id="priorityCallAnalysis" class="item"> <button type ="button" onclick="getPriorityCall()">Priority </button> </a>
<form:form action="somepage" method="post" commandName="somedata"
id="taskDetails" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Choose Account*</label>
<form:select path="accountName" class="form-control"
id="accountName" onchange="getDashboard()">
<form:option value="" label="--select--"></form:option>
<c:forEach items="${accountList}" var="accountName">
<form:option value="${accountName}" label="${accountName}"></form:option>
</c:forEach>
</form:select>
</div>
</div>
</div>
</form:form>
function getPriorityCall()
{
var accountName = $("#accountName").val();
alert(accountName);
window.location="priorityCall.html?accountName="+accountName+"";
}
Controller
#RequestMapping(value="/priorityCall")
public ModelAndView priorityCall(Map<String, Object> model,#RequestParam ("accountName") String accName)
{
System.out.println("entry");
SampleBean template = new SampleBean ();
model.put("template ", template );
List<String> accountList = Service.getAccountList();
model.put("accountList", accountList);
model.put("accName", accName);
return new ModelAndView("analByPrior","","");
}
JSP : analByPrior
<form:form action="#" method="post" commandName="somedata"
id="taskDetails" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>Choose Account*</label>
<form:select path="accountName" class="form-control"
id="accountName" onchange="getAssignmentGroups()">
<form:option value="" label="--select--"></form:option>
<c:forEach items="${accountList}" var="accName">
<form:option value="${accName}" selected="true"> ${accName}</form:option>
</c:forEach>
</form:select>
</div>
</div>
</div>
</form:form>
UPDATE
While clicking on Priority Button, this controller is getting called, instead of PriorityCall.. I dont know y..
#RequestMapping("/priorityCallAnalysis")
public String someAction(#ModelAttribute("accountName") TicketInfo data, Map<String, Object> map,
HttpServletRequest request) {
TicketInfo somedata = new TicketInfo();
map.put("somedata",somedata);
System.out.println(somedata);
System.out.println("acc=" + request.getParameter("accountName"));
/* do some process and send back the data */
map.put("somedata", data);
map.put("accountName", request.getParameter("accountName"));
return "analysisByPriority";
}
First in the .jsp file you can use a global variable to store context path and use this variable as prefix in all the relative paths.
<script>var context = "${pageContext.request.contextPath}"</script>
Now within your js function use the context path and call the controller.
function getPriorityCall(){
var accountName = $("#accountName").val();
alert("contextPath: "+context); // will print your {appName}
window.location=context+"/priorityCall?accountName="+accountName;
}
So your URI looks like below in your request call.
http://localhost:8080/{appName}/priorityCall?accountName={acountName}
PS:
benefit of use this ${pageContext.request.contextPath} is if you change your appName later you dont need to change it in views. It will automatically get the latest contextPath.
If you are using Firefow browser install the firebug add-on and Use it for to verify your requests. So you can validate your URI with params.(If its chrome use Inspect Element to validate URI)
Related
I have form action with textarea and submit button
<form method="post" action="/analyze">
<div class="form-group">
<label for="text">Input text:</label>
<textarea class="w-100" name="text" id="text" cols="30" rows="10"></textarea>
</div>
<div class="form-group d-flex justify-content-center">
<input type="submit" class="btn__submit btn btn-dark my-auto" value="Обработать">
</div>
</form>
<div class="row">
<div class="col">
<p th:text="#{nertext}"></p>
</div>
</div>
When I click submit button, i want to get processed text from server in Spring Boot and paste in tag p in div col.
Java Controller
#RequestMapping(value = "/analyze", method = RequestMethod.POST)
public String analyzeText(#RequestParam String text, Model model) {
System.out.print(classifier.classifyToString(text, "tsv", false));
String asd = classifier.classifyToString(text, "tsv", false);
model.addAttribute("nertext", asd);
return "/analyze";
}
How can i do submit without reload page
Use the Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and the onsubmit event listener (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit) to submit the form with JavaScript without reloading the page:
let form = document.getElementById("the-form");
form.onsubmit = function (e) {
e.preventDefault();
fetch(form.action, {
method: "post",
body: new FormData(form)
}).then(response => {
// do something with the response...
});
}
The e.preventDefault() makes sure that the page is not reloaded when you click the submit button. This assumes your form has the id the-form, like this:
<form id="the-form" method="post" action="/analyze"> ... </form>
Hi I'm new with Spring and I'm having problems in passing data between two pages using two different controllers.
I would like to know how I can handle this situations.
In my index.html I have a button that should redirect me to a new page passing some data. When i click the button it redirects me to the step2 page but I don't have to objects. How can I solve this? Is the GET method correct? Do I have to use the form just for passing some data between pages and controllers?
Below is what I have.
Index.html
<form th:action="#{/step2}" method="GET">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
Step2Controller
#RequestMapping(value="step2", method = RequestMethod.GET)
public ModelAndView step2(ModelAndView modelAndView, #ModelAttribute("user") User user,
#ModelAttribute("mapSelectedServices") HashMap<String,List<ServiceOffered>> mapSelectedServices,
BindingResult bindingResult){
modelAndView.addObject("user", user);
modelAndView.addObject("mapSelectedServices", mapSelectedServices);
modelAndView.setViewName("step2");
return modelAndView;
}
Sorry for all the questions, but I'm new to spring development.
HTML page:
<form th:action="#{/step2}" method="POST">
<input type="hidden" th:value="${mapSelectedServices}" name="mapSelectedServices"/>
<input type="hidden" th:value="${user}" name="loggedUser"/>
<div class="form-group d-flex align-items-center justify-content-between">
<button type="submit" class="btn btn-danger btn-rounded ml-auto" >SEE PRICES
<i class="fas fa-long-arrow-alt-right ml-2"></i>
</button>
</div>
</form>
Controller method:
public ModelAndView goToPgae2(#ModelAttribute ModelClass aClass)
{
ModelAndView mv=new ModelAndView("SecondHtlmPageName");//setting view name here
mv.addAttribute("aClass",aClass);
return mv;
}
Model Class with the specific variables passed from one page to another:
class ModelClass {
public Stirng mapSelectedServices; //use appropriate data type.
public String loggedUser;
//create getters and setters
}
Second page
<div>${aClass.loggedUser}</div>
DONE.
This way you can go to second page . And if you want to redirect to second page and the model attributes should be available there then you need to use flashattribute.
I have a class User and a class Project wich has an arraylist with users.
I have a Project page with a list of all my projects and when i click on one, it takes me to the page of that project by sending the id of that project in the url.
On my detail project page i want to add users that i created.
The users are displayed on a modal in a table with a button to add them.
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<h1 class="text-center">UserList</h1>
<br><br>
<table class="table table-hover">
<thead>
<tr>
<th>Photo</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Function</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<c:forEach var="u" items="${users}">
<tr>
<td><img src="${u.getPhoto()}"
alt="Alternate Text" class="img-responsive" /></td>
<td>${u.getFirstname()}</td>
<td>${u.getLastname()}</td>
<td>${u.getFunction()}</td>
<td>${u.getEmail()}</td>
<td><Button type="Button" class="btn btn-default">Add</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
</div>
</div>
My question is how do i send the id of the user and the id of the project i want them to be added to my controller?
I know i can pass an id with the url but i dont want to open a new page.
I want to send the ID of the user and the project to my controller by clicking on the add button to my controller so i can use those in my method called addUserToProject()
JSP
First, make a hidden input with selected project id, so you can get it later:
<input type="hidden" id="currentProjectId" value="12">
Second, set attribute name of add buttons equal userId:
<td><Button type="Button" name="${u.getId()}" class="btn btn-default">Add</button></td>
Javascript:
Define onclick linstener for each "add button" and get the current user id from the button:
$(".btn").click(function(event) {
event.preventDefault();
var currentProjectId= $('#currentProjectId').val();
var userId = $(this).attr("name");
addUser(currentProjectId, userId);
});
Make ajax request and post the ids to controller:
function addUser(currentProjectId, selectedUserId) {
$.ajax({
type : "POST",
contentType : "application/json",
url : "/addUserToProject",
data :{ projectId: currentProjectId, userId: selectedUserId},
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
console.log("DONE");
}
});
}
Finally, controller accepts ids using #RequestParam:
#RequestMapping(value = "/addUserToProject", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String Submit(#RequestParam("projectId") Integer projectId ,#RequestParam("userId ") Integer userId ) {
//insert user
return "ok";
}
From a rendered page you only have two options either you do a normal form post or use Ajax if you dont want to open a new url.
I'm tryring to get an id from url but getParameter return null
this is how I'm sending the id in the url (tool.jsp):
Execute
this the doGet method where I want the id value
protected void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
ToolDAO dao=new ToolDAO();
String id= req.getParameter("id");
Tool t=dao.getToolById(Integer.parseInt(id));
String first = req.getParameter("first");
byte[] bytes = first.getBytes(StandardCharsets.ISO_8859_1);
first= new String(bytes, StandardCharsets.UTF_8);
if(first!=null)
{
String [] input=first.split(" ");
System.out.println("input"+input[0]);
EXEJAVA exe=new EXEJAVA();
FileRead f=new FileRead();
f.writeinputfile(input);
ArrayList l=exe.executetool(t.getTool_path_exe());
req.setAttribute("l",l);
req.setAttribute("first", first);
req.getRequestDispatcher("executetool.jsp").forward(req, res);
}
and this is the form (executetool.jsp)
<form accept-charset="UTF-8" name="form" action="executetool" method="get">
<div class="centre">
<div class="row">
<div class="inline-div">
<label for="ta1">Text in Latin script</label>
<textarea cols="60" rows="15" id="first" name="first" class="inline-
txtarea">${first}</textarea>
</div>
<div class="inline-div">
<input type="button" value="Clear" onclick="javascript:eraseText();">
</div>
<div class="inline-div">
<label for="ta2" >Text in Arabic script</label>
<textarea cols="60" rows="15" id="second" name="second" class="inline-
txtarea"><c:forEach items="${l}" var="s">${s} </c:forEach>
</textarea>
</div>
</div>
</div>
</form>
Since it's method get the url keeps changing everytime the page is refreshed and so the "id=something" part gets replaced by the value of the two text areas that I have in the form what sould I do to always keep that part in the url?
Place a hidden field instead
<input type='hidden' name='id' value='${l.tool_id}'>
Then use input type submit for the button, not a generic <a> tag as that won't submit the form unless you have a javascript code somewhere that will submit the form for you.
You can also place the id in the action attribute of the form.
<form accept-charset="UTF-8" name="form" action="executetool?id=${l.tool_id}" method="get">
I'm attempting to utilize a REST API which is created using Spring by using AngularJS controllers. All I want to do, is send the credentials from the form using AngularJS to the Spring controllers in the back end; however, they don't seem to be communicating at all. Whenever I push the login button, the page simply refreshes. I placed loggers in the Spring controller I'm attempting to call, but they never print anything out which means the controller is never being called.
AngularJS controller:
angular.module('landing', [ 'ngRoute' ])
.controller('authentication',
function($rootScope, $scope, $http, $location) {
$scope.credentials = {};
$scope.login = function() {
$http.post('http://localhost:8090/login', $.param($scope.credentials), {
headers : {
"content-type" : "application/json"
}
}
};
});
The Spring controller I'm attempting to utilize:
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<BusinessUser> login(#RequestBody BusinessUser inputUser) {
logger.info(inputUser.getUsername());
logger.info(inputUser.getPassword());
BusinessUser requestedUser = businessUserService.findByUsername(inputUser.getUsername());
if(requestedUser != null)
if(BCrypt.checkpw(inputUser.getPassword(), requestedUser.getPassword()))
return new ResponseEntity<>(requestedUser, HttpStatus.OK);
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
Lastly, here's the form:
<body data-spy="scroll" data-target=".navbar" ng-app="landing">
<div id="home" class="border-shadow">
<div class="container-fluid container-background-color">
<div class="row border-shadow">
<div class="col-lg-7">
<h2 class="heading-margin main-color"><img class="imagesize" src="images/icon.png"/><b>Test Company</b></h2>
</div>
<div class="col-lg-5" ng-controller="authentication">
<form role="form" ng-submit="login()">
<div class="form-group row row-margin">
<div class="col-lg-5">
<input type="text" class="form-control" ng-model="credentials.username" placeholder="Username" required>
</div>
<div class="col-lg-5">
<input type="password" class="form-control" ng-model="credentials.password" placeholder="Password" required>
Forgot Your Password
</div>
<div class="col-lg-2">
<button type="submit" class="btn btn-success">Log in</button>
</div>
</div>
</form>
</div>
</div>
</div>
I can send requests using a Chrome add on called "Postman" and the results come back perfectly, so it's an AngularJS problem. Any idea what's wrong?
EDIT This is a Spring Boot project by the way.