I have a controller wich handles URL studentEdit.html. When I pass to controller value 'get' using AJAX I need to redirect to another page viewStudents.html, but nothing happens. I stay on the same page. The method returns the ModelAndView, but why it does not redirect to another page I do not know.
I also tried to set url as:
redirect:viewStudents.html and redirect:viewStudents
but it did not helped.
#RequestMapping(value = "/studentEdit.html", method = RequestMethod.GET)
public ModelAndView getStudentProfile(#RequestParam(value = "get", required = false) String get) {
if(get != null && get.equals("get")) {
return new ModelAndView("redirect:/viewStudents.html");
} else {
ModelAndView mav = new ModelAndView("studentEdit");
return mav;
}
}
function getStudent() {
$.ajax({
type: "GET",
url: "/IRSystem/studentProfileEdit.html",
data: "get=" + 'get',
success: function(response) {
},
error: function(e) {
alert('Error' + e);
}
});
}
I would appreciate any information, thank you.
If you want to redirect to another page after request, there is no need to use AJAX.
A simple link should be enough:
click me
What happens when you click on the link:
a GET request to /IRSystem/studentProfileEdit.html is performed
get=get is passed as request data
by default, user is redirected to link's href (i.e /IRSystem/studentProfileEdit.html), but you can redirect him somewhere else
Assuming the rest of your code is correct, using <a> as mentioned above together with redirect:/viewStudents.html should redirect as desired.
Also check the docs about redirect: prefix to make sure your redirect is interpreted correctly.
Related
I'm making an ajax request and I have two situations, where if everything is ok I return a page which will be rendered in a modal else return empty string and don't show any modal at all.
Here is a sample of how should my controller look like:
#PostMapping(value = "/path")
public String serve(final Model model)
{
if (everything_fine)
{
return "path_to_page_which_will_be_handled_by_view_controller";
}
return StringUtils.EMPTY;
}
and the ajax request is something like this:
$.ajax({
type: 'POST',
url: '/path',
error: function (data) {
//handle error
},
success: function (data) {
if (data) {
// render response in modal
} else {
// show some other stuff
}
}
});
For the situation where jsp is returned request works fine, when empty string is returned I get 404 and ajax request goes on the error branch when finished. I guess this is because view controller doesn't find any view for the empty string returned, do you have any idea how can I accomplish my scenario?
You trying to return empty path to browser and you get 404. It's normal.
Try to return String with path to controller that returns empty page:
#PostMapping(value = "/path")
public String serve(final Model model)
{
if (everything_fine)
{
return "path_to_page_which_will_be_handled_by_view_controller";
}
return "path_to_EMPTY_page_which_will_be_handled_by_view_controller";
}
Eventually split this in two requests, one to get the data on which deciding if the modal will be shown or not, and finally request the modal contents if needed.
I have backend springboot that does the redirect
#RequestMapping(value = "/test/page", method = RequestMethod.POST)
public #ResponseBody void getPage(#RequestBody custRequest req, HttpServletRequest request, HttpServletResponse response) {
response.sendRedirect("https:www.google.com");
}
And the service call like this
getPage(user: User) {
const bodyString = JSON.stringify(user);
const header = new HttpHeaders({ 'Content-Type': 'application/JSON' ,
'Accept' : 'text/html' });
return this.httpclient.post('/test/page', bodyString, {headers: header, responseType: 'text'} );
}
Button when clicked.
onSubmit(user: User) {
if (user && user.userID && user.password) {
this.user.session = this.uuid;
this.loginService.getLogin(user).subscribe(
(res) => {
console.log('post res');
console.log(res);
// window.location.href = data.url; sanitizer
this.data = this.sanitizer.sanitize(SecurityContext.HTML, res);
},
error => {
console.log('Error', error);
},
() => {
console.log('POST is completed');
});
But in the result page I am not getting a proper landing page. Instead I am staying in the same page and the console would print
<!doctype html>
<html lang="en">
<head>
...
</html>
My question is how do I show the actual content?
Simply put, your code fetches the source code of google.com. I'm not sure whether this is the behaviour you want, or you want just a browser redirect. Please explain in more detail what you're trying to achieve. Despite not understanding, I'll do my best to answer.
To do a browser redirect, just do window.location.href = "http://www.w3schools.com";
If you want to fetch a page and show the content of an external page, I think iframe would be the most straight-forward approach.
The one below is NOT RECOMMENDED if the response is a full html page as it's invalid HTML (i.e. can't have html, head, body inside body). It'll also probably download unnecessary files.
Otherwise, create a property in the angular component, let's name it 'myHTML'. Then bind that to the innerHTML property of a html element you create
<div [innerHTML]="myHTML"></div>
Then once you fetch your URI (I recommend doing it directly -- GET to the final url, the way you did it is odd) just assign the response to the 'myHTML' property
I am trying to set up a login page for my website, however at the moment I am stuck on the sendRedirect method, as it doesn't appear to load a new page when required.
My login page is a .jsp file that passes the username and password information via AngularJS $scope to the servlet, which contains the following code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Redirecting...");
response.sendRedirect("https://www.youtube.com/");
return;
}
The System.out.println("Redirecting..."); works, however it does not redirect to the URL provided, no matter what that is. I have read other advice which mentioned to add the return; line, and I have tried other URLs specific to my project (e.g. index.jsp, \index.jsp, etc.), however none of these have made a difference and it still does not work.
Would window.location be a more suitable approach for this? What code should I be modifying here?
So I've made the webpage finally redirect correctly and I'm posting this just in case someone else stumbles upon the same issue.
As mentioned in previous comments, the response should be sent from the Java servlet to AngularJS, I have made the redirection occur as follows in my logincontroller.js file:
var app = angular.module('myApp', []);
function LoginController($scope, $http, $window)
{
$scope.login = function()
{
$http({
url: 'login',
method: 'POST',
data:
{
'username': $scope.username,
'password': $scope.password
}
}).success(function(data, status, headers, config) {
alert("SUCCESS! Data: " + data);
$scope.details = data;
$window.location.href = "home.jsp"; //This line redirects.
}).error(function(data, status, headers, config) {
alert('ERROR!');
});
};
};
I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
Goal: To load different jsp's into a div of main.jsp dynamically on the basis of user click.
This is what I have done so far -
Java Script
function getPageContent( pageName, containerID, path ){
$.ajax({
type : "GET",
url : "getPageContent/"+pageName+".test",
cache : false,
data: "path=" + path,
success : function(response) {
alert(response);
$("#"+containerID).load( response );
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
Controller
#RequestMapping(value="getPageContent/{pageName}")
public String dynamicIncludePage( ModelMap model, #PathVariable String pageName,
#RequestParam(value="path") String path, HttpSession session ){
if( pageName.equals("manageDashBoard") ){
List<Report> reports = reportService.getAllReportsByUserID( (int)session.getAttribute("userID") );
model.addAttribute("reports", reports);
}
return path+"/"+pageName;
}
main.jsp
I am calling the JS method
getPageContent( 'manageDashBoard', 'containerID', 'home' );
path for manageDashBoard.jsp is --> EVIP14ReportSS\src\main\webapp\WEB-INF\views\home\manageDashBoard.jsp
But the spring is trying to locate the jsp in the below path --> EVIP14ReportSS\getPageContent\WEB-INF\views\home\manageDashBoard.jsp
Please suggest what is wrong.
Thanks
I am not sure if your paths are correct. You should check that anyway.
But for sure you should change way how you are rendering page using AJAX and Spring.
You should change return type from String to
public #ResponseBody JsonObjectToRender dynamicIncludePage( ModelMap model, #PathVariable String pageName,
#RequestParam(value="path") String path, HttpSession session )
JsonObjectToRender is your custom object with some properties. In success handler JsonObjectToRender you should analyze and render part of the page depending on that object.