How to open a new web browser window in the controller in 302 code - spring-boot

Now my code shows 302 code as follows and there is no value in the body, so the web page does not change the page according to the return value. However, I want to automatically open a new page in the web browser by redirecting a different url depending on the return value.
What I use is mysql, thymeleaf, jpa, springboot, spring data jpa.
enter image description here
This is My #Controller code (Not #RestController)
#RequestMapping(method = RequestMethod.POST, value = "/find_email5")
public String findEmail5(FindEmailDto findEmailDto) {
String s = "failed";
try {
Optional<Users> users = userService.findEmail(findEmailDto);
if (users.isPresent()) {
String email = users.get().getEmail();
return ("redirect:/alert" + email);
}
} catch (Exception e) {
return ("/alert?value=" + s);
}
return ("/alert?value=" + s);
}
#GetMapping("/alert")
public String alertPage(#RequestParam("value") String s, Model model) {
model.addAttribute("string", s);
return "alert";
}

Related

Handle Sharp In Controller And Get Id

There was a jsp application. I have just converted to spring boot application. I want to continue to use same links to handle company's information. Old urls are like /Dashboard.jsp#/company/10712. I have tried to handle company id but it didn't wook. How can I handle company id ?
#GetMapping("/Dashboard.jsp#/company/{id}")
public void try(#PathVariable String id) {
System.out.println(id);
}
I have also tried;
adding
server.tomcat.relaxed-path-chars=#
in application properties.
#RequestMapping(value = ERROR_PATH, produces = "text/html")
public Object errorHtml(HttpServletRequest request, HttpServletResponse response) {
if (response.getStatus() == HttpStatus.NOT_FOUND.value()) {
return new ModelAndView("redirect:" + StringUtils.getBaseUrl(request) + "/?page=error", HttpStatus.FOUND);
} else {
return new ModelAndView("redirect:" + StringUtils.getBaseUrl(request) + "/?page=error");
}
}
This function handle 404.
request.getAttribute("javax.servlet.forward.request_uri")
returns /esir/Dashboard.jsp. There is no # and others.

passing parameter from custom filter to web api controller

I am working on a web application in which we are using web-api and oAuth2.
I had stored my UserId in front-end but now for security reason I am storing my UserId in backend against the token generated from oAuth2.
So I have around 800 api's in my application all of them are POST api's and the data is passing in those api's like below
Type 1
[HttpPost]
[Authorize]
[ActionName("GetList")]
[Filters.AuthorizeLoginApi()]
public List<BusinessEntities.Admin.Users> GetList(Dictionary<string, string> Parameters)
{
try
{
if (Parameters != null)
{
BusinessLayer.IAdmin.IUsers a = (BusinessLayer.IAdmin.IUsers)DALFinder.GetInstance(typeof(BusinessLayer.IAdmin.IUsers));
return a.GetList(Convert.ToString(Parameters["LoginText"]), Convert.ToString(Parameters["Name"])
, Convert.ToString(Parameters["Email"]), Convert.ToInt32(Parameters["UserTypeId"]), Convert.ToString(Parameters["IsActive"])
, Convert.ToInt32(Parameters["UserId"])); /*(LoginText, Name, Email, UserTypeId, IsActive, UserId);*/
}
else
{
return new List<BusinessEntities.Admin.Users>();
}
}
catch (Exception ex)
{
Utils.Logger.Instance.LogException(ex);
return new List<BusinessEntities.Admin.Users>();
}
}
In the above code I have a Dictionary parameter in which I am storing my userId
Type 2
[HttpPost]
[Authorize]
[ActionName("Delete")]
[Filters.AuthorizeLoginApi()]
public SPResponse Delete(BusinessEntities.Admin.Users item)
{
SPResponse response = new SPResponse();
try
{
//item.ModifiedByUserId is my UserId
BusinessLayer.IAdmin.IUsers a = (BusinessLayer.IAdmin.IUsers)DALFinder.GetInstance(typeof(BusinessLayer.IAdmin.IUsers));
response = a.Delete(item);
}
catch (Exception ex)
{
response.ReturnMessage = ex.Message;
}
return response;
}
I am doing custom validation in each and every api calls like below
public class AuthorizeLoginApi : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//Code to Get userId from database
//int UserId = data coming from db
//pass the above UserId Parameter into every apis as UserId/ModifiedByUserId
}
}
Now I want to Pass UserId/ModifiedByUserId from OnActionExecuting filter method into my respective API's
How can I achieve this

IE image not getting loaded with X-Content-Type-Options:nosniff

Intro
I have spring MVC application I'm loading image from controller. For security purpose, I added X-Content-Type-Options:nosniff to my Spring application
By setting the following in springConfig xml <security:content-type-options/>
Problem : after this IE is not loading the images responded by controller. I suspect the content type is not set in the response. Because another site which is responding X-Content-Type-Options:nosniff and Content-Type:image/png; is working fine.
TRY1
I tried to change my controller to set content type. But it is not happening.
#RequestMapping(value = "/getUserImage" , produces = org.springframework.http.MediaType.IMAGE_PNG_VALUE)
public #ResponseBody
void getUserImage(
#RequestParam(value = "userId", required = false) int userId,
HttpServletRequest request, HttpServletResponse response) {
try {
//Get file and add it to response
IOUtils.copy(inputStream, response.getOutputStream());
response.getOutputStream().flush();
response.setContentType(org.springframework.http.MediaType.IMAGE_PNG_VALUE);
response.setHeader("Content-Type","image/png");
response.flushBuffer();
inputStream.close();
} catch (Exception e){
}
}
TRY2
I tried to add response header as the same way in method interceptor but still no luck.
But the same thing working in Chrome and Firefox.
Try this :
#RequestMapping(value = "/image/{personId}")
#ResponseBody
public HttpEntity<byte[]> getPhoto(#PathVariable int personId) {
Person person = this.personService.getPersonById(personId);
if (person != null && person.getProfileThumbnail() != null) {
try {
byte[] image;
try {
image = org.apache.commons.io.FileUtils.readFileToByteArray(new File(msg + "/" + person.getUsername() + "/" + personId + ".png"));
} catch (FileNotFoundException e) {
image = org.apache.commons.io.FileUtils.readFileToByteArray(new File(defaultProfilePath));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
headers.setContentLength(image.length);
return new HttpEntity<>(image, headers);
} catch (IOException ignored) {
}
}
}
What I am basically doing is checking if there is an image on File-system for the user, if not then I am loading a default image. Right now it works on all browser, so even if personid is 0, I get default image back, with the else cause, which I have not posted here.

Spring MVC handle Exceptions and how to show in same view

If I handle exceptions with #ControllerAdvice and #ExceptionHandler How can I show error message to user in the same View. For ex. suppose user in "customer/new" view. and invoke "save" action, then it will go to controller and I call methods service layer. but if internal exception occurred in service layer, I want to show error message on same "customer/new" View.
I have written a separate class to handle exceptions as follow.
#ControllerAdvice
public class DefaultControllerHandler {
#ExceptionHandler({MyProjectException.class, DataAccessException.class})
public ResponseEntity<String> handleInternalErrorException(Exception e) {
logger.error(e.getMessage(), e);
return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Appreciate your ideas.
Thanks!
You can use flash redirect attributes.
#RequestMapping(value = "/administrator/users", method = RequestMethod.POST)
public String adminAddUser(#ModelAttribute("user") #Valid User user, BindingResult bindingResult, Model model, RedirectAttributes redirectAttrs) {
String redirectUrl = "/administrator/users";
try {
userService.save(user);
} catch (YourServiceException e) {
redirectAttrs.addFlashAttribute("errorMessage", "error occured: " + e.getMessage());
redirectAttrs.addFlashAttribute("userObject", user);
redirectUrl = "/administrator/users?form"; // If error - return to same view
}
return "redirect:" + redirectUrl;
}
#RequestMapping(value = "/administrator/users", params = "form", method = RequestMethod.GET, produces = "text/html")
public String adminUsersList(#ModelAttribute("errorMessage") final String errorMessage, #ModelAttribute("userObject") final User user Model model) {
if(user == null) {
user = new User();
}
model.addAttribute("user", user);
if(errorMessage != null) {
model.addAttribure("errorMessage", errorMessage);
}
return "administrator/users/create";
}
In that case you must have section on your users.jsp page to show errorMessaage. Something like this:
<c:if test="${not empty errorMessage}">${errorMessage}</c:if>
If you can fetch url path and redirectAttributes from controller method - you can do this through #ControllerAdvice
The only solution I can think about is make your call to the service layer AJAX and then redirect only if there are no errors, if not display the error message.
It might look something like this in your Javascript file
$("#someButton").click(function(){
//make your ajax call
if (noError){
window.location.href = contextPath+"/somePath";
}
else{
//display your error message
}
});

Spring MVC + GWT : Redirect Issue

I am using Spring annotated MVC framework in an app which I am developing.
Following is the issue I am facing:
I have Controller which does a redirect, after a POST:
#RequestMapping(value = "/emdm-viewer-redirect.do", method = RequestMethod.POST)
public ModelAndView getMetricKeysAndRedirect(#RequestParam Object jsonObject, Model model)
{
ModelAndView modelAndView = new ModelAndView("redirect:/mdm-viewer.do");
.....
.....
....//make some service calls and populate value1
...
modelAndView.addobject("param1", value1);
return modelAndView;
}
I have another controller which is mapped to URL mdm-viewer.do (The redirect URL mentioned above):
#RequestMapping(value = "/mdm-viewer.do", method = RequestMethod.GET)
public String getMDMViewer(Model model) {
return "mdmViewer"; //returns a mdmViewer.jsp
}
Please note that the mdmviewer.jsp is a GWT entrypoint which is in classpath.
I have my firebug window open which tells me that a GET request was made for mdm-viewer.do, but it gives me a blank response. In fact, it does not redirect to the new jsp and stays on the same page from where the POST request was made.
However, if I copy the firebug URL and open it in a new window of my browser, I see the expected results.
Any ideas what I am doing wrong here? Tried to google it a lot, but can't find a similar issue anywhere.
Eventually, I returned a ModelAndView back from the POST method using a
#ResponseBody
And in my GWT Module, I used the response.getText() output to do a
#Override
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
JSONObject jsonObject = (JSONObject) JSONParser.parse(response.getText());
String viewName = jsonObject.get("viewName").isString().stringValue();
JSONObject jsonParams = jsonObject.get("model").isObject();
Set<String> chartKeys = jsonParams.keySet();
String redirectURL = viewName + "?";
for (String keyString : chartKeys) {
redirectURL = redirectURL + keyString + "=" + jsonParams.get(keyString).isString().stringValue() + "&";
}
Window.open(GWT.getHostPageBaseURL() + redirectURL, "_self", "");
}
}

Resources