How to display URL link different than page JPS page? - java

I am not sure it this is possible at all. I see that in Facebook when you crate a business page you will get a link with page number, for example:
https://www.facebook.com/degendaUK/
I would like to know if it is possible to create a link like that without having an HTML or JSP page called "DegendaUK" for example.
In my code I have page
http://localhost:8080/offers/empresa?get_Business_ID=29-11-2017-03:39:22R7M5NZ8ZAL
The standard page is called "Empresa" and then I pass the ID so I can query the database.
Is there anyway that instead of my URL I would get
http://localhost:8080/offers/BUSINESS-NAME
without creating a JSP page for each business?
I am using Spring MVC.

You may use Spring #Controller, #RequestMapping and #PathVariable annotations to do this.
#Controller
public class Controller
{
#RequestMapping(value = "/offers/{id}")
public String offer(#PathVariable String id, final Model model)
{
//pass the value from the url to your jsp-view, access it via ${id} from
//there
model.add("id",id);
//render the page "empressa.jsp"
return "empressa";
}
}
Hint: You may need some and in your XML config to make those annotations work.
If your using spring-boot, this should be preconfigured already an work out of the box.
Don't forget to secure those things if they're not public things using spring-security :)

Related

Is there a way to only refresh a view in Spring MVC Controller?

I have a Spring Boot online shop application and my shopping cart component is accessible from several different views.
I make my views in Thymeleaf and those - and + are <a th:href="#{'/products/addToCart/'+${product.id}}">. Now inside my products controller I do some backend work and return a redirect:home but that kind of kills the whole point of putting these - and + there. I'd like it to return the same view from which the request was sent. Can that be done somehow? I don't like the idea of making seperate controllers for every view.
You could use the referer (yes the official header has a typo) request header to know where you navigated from:
public String addProduct(#RequestHeader(value = HttpHeaders.REFERER, required = false) final String referrer) {
// update cart
// redirect to the referred
return "redirect:" + referrer;
}
However, that is probably quite brittle. I'm not sure the referrer URL will always be there.
For something like this, I would probably use JavaScript to do an AJAX request to a dedicated endpoint that returns JSON. You can add #ResponseBody on a method in your controller so the response is not seen as a redirect or a page view, but a JSON string for example.
#ResponseBody
public CartInfo updateCart(...) {
// do update to cart here
// return a CartInfo object. It will be serialized with Jackson to a JSON string
}
In your HTML page, you will need to add some JavaScript to handle the AJAX call using plain JS or your framework of choice.

Custom path resolving static resources Spring

I am working on Spring Boot application. The general problem is the following: I've created REST API, a few controllers. However, I also have some static HTML files, located in "resources/static".
What I want to achieve, is to configure Spring resolvers so that I could access static content without appending ".html". On practise, I expect to access static HTML by path "ip:port/htmlPage" instead of "ip:port/htmlPage.html"
However, I don't want to create methods like this one:
#Controller
public class ViewMaster {
#RequestMapping("/home")
public String home() {
return "home";
}
So, properties like
spring.mvc.view.suffix=.html
not working for me. Any possibilities to avoid creation per page endpoint in a controller?
After reading your question i have tried a lot but unable to serve html from static folder without extention. What works for me is to create an #RequestMapping like this:
#RequestMapping(value="/static/{htmlName}")
String getStaticHtml(#PathVariable String htmlName){
return htmlName;
}
And moved html files to templates folder. So there is no need to create different end points to access html pages, just pass the name of html without extention and this will do the trick

Spring Boot URL display after click on a link

My Spring Boot application is deployed in embedded Tomcat and it can be accessed through the following url http://localhost:8080/displayResults
#RequestMapping(value = "displayResults", method = RequestMethod.GET)
public ModelAndView getResults(ModelMap model) {
List<Bean> beanToDisplay = handler.getData();
return new ModelAndView("Results", "beanToDisplay", beanToDisplay);
}
Now if I click on a link on the page displayed on above mentioned link, it performs some action. The link will take me to http://localhost:8080/displayResultsChanged. However I still display the same page for both the URLs it's just that it performs some calculations in the server.
Now my question is.. I don't want the URL to be displayed as http://localhost:8080/displayResultsChanged instead I still need http://localhost:8080/displayResults as the URL. How do I achieve that?
You should use REST. If you want to stay on the same page and only make some calculations as you said. I can give you a tip or two.
Firstly annotate your controller with #RestController
After, leave one method that leads you to the page you wanted like : displayResults in your example.
Then you need to create a method that returns NOT ModelAndView but List<Bean> in your case.
#RequestMapping(value = "displayResultsChanged ", method = RequestMethod.GET)
public List<Bean> getChangedResults() {
...
}
Now it depends on the client side how to make the call and proces the data that the server returns. If you provide some client side examples maybe you will get more and better answers.

Dynamic URL from database and MVC in JSP

I am learning JAVA and Spring Framework. I wanted to know that is it possible in java to create Dynamic URL in spring framework using values from url and fetching from database.
I am trying to make URL Shortner in Java and I will need to lookup for url's short code in my database and as we all know, url shortner will look like "url/ShorTCode" and my script will look for "ShorTCode" keyword in database and will redirect to associated weblink.
So I wanted to know that is it even possible in JAVA and Spring? And one more thing, if I make something like this "url/yt/VIdeoCode" or "url/fb/UserProfile"
So it will look at yt object which will redirect to youtube link only and fb object which will redirect to facebook user profile.
I want to clarify that I am still learning JAVA, JSP and Spring but I want to keep this thing in my mind while I am learning so I can focus on some particular things.
Thank you all fro helping me.
If you're asking how your controller could respond with a dynamic redirect, the answer is either:
(1) Have the controller return a "redirect:" result instead of view name. It must be followed with an absolute url, and behavior might depend on your spring version and configuration, but basically it looks like this:
#RequestMapping(...)
public String myMethod(){
String url=... // database lookup, e.g. "http://myUrl"
return "redirect:"+url;
}
(2) Less elegant but sometimes useful: get direct access to the response. If your controller method has a parameter of type HttpServletResponse spring will automatically inject it. So:
#RequestMapping(...)
public String myMethod(HttpServletResponse resp){
...
response.sendRedirect(...)
}

Set something into Freemarker page by AOP in SpringMVC

To show the user's name on every Freemarker page, I could call model.addAttribute in every controller as below:
#RequestMapping(value = "index",method=RequestMethod.GET)
public String index(Model model) {
model.addAttribute("currentUser", App.getCurrentUser());
return "index";
}
#index.ftl
<div>${currentUser.userName}</div>
The calling would appear in everywhere of my code. It's really a nightmare. Is there any other way like AOP or Servlet Filter to set stuff into page?
You can use and interceptor for this, please check: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor
This kind of information it would be better to keep it on a session scoped bean holding the user profile, rather than reloading it for every HTTP request.

Categories