Dynamic URL from database and MVC in JSP - java

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(...)
}

Related

CAS redirect to URL on succesfull login

Here a solution is described to handle redirects to a custom URL based on a condition via use of AccessStrategy.
This however is part of the unauthorized login logical flow therefore results into a still not-logged in user arriving at the end url we redirect to. (via getUnauthorizedUrl)
If we want to redirect the user based on a condition, say via injecting an action to the webflow, how can we manipulate the return URL to be changed into a custom one?
WebUtils.getService(requestContext) include getters of the source/originalUrl but no obvious way to set/manipulate said value through an action bean.
p.s. Currently using CAS version 5.3.x
Responses for normal web applications from CAS are built using WebApplicationServiceResponseBuilder.
If you examine this block you will find that the final response is built using WebApplicationServiceResponseBuilder bean. It is only created conditionally, if an existing bean is not already found in the context by the same name. So to provide your own, you just need to register a bean with the same name using your own #Configuration class.
#Bean
public ResponseBuilder<WebApplicationService> webApplicationServiceResponseBuilder() {
return new MyOwnWebApplicationServiceResponseBuilder(...);
}
...and then proceed to design your own MyOwnWebApplicationServiceResponseBuilder, perhaps even by extending WebApplicationServiceResponseBuilder and overriding what you need where necessary to build the final redirect logic conditionally.
To learn about how #Configuration classes work in general, you can:
Review this post
or this post
or consult the documentation for Spring and/or Spring Boot.

Get more servlet request variables using wildcards [duplicate]

This question already has answers here:
Wildcard path for servlet?
(2 answers)
Closed 7 years ago.
I'm sorry, I come from a PHP web world.
I'm used to using a router in frameworks like Laravel to send to controllers and get parameters. I know how to get get and post parameters using servlets by routing things with the web.xml servlet-mapping and using * wildcards, but am unfamiliar with how to get those url wildcards with the HttpServletRequest variable passed through doGet or doPost.
Is there anything where I can grab the wildcards of those urls, such as, if the url was a username or a particular page I didn't want to hard code into the web.xml? I'm sure there is.
Id like to know things like what I can get in PHP's $_SERVER variables for reading data about the incoming request. Stuff like cookies are also needed. Can someone give me a quick pointer with Java Servlets?
EDIT:
Or maybe I should just stick the variables to where variables belong and not make "pages" out of fake variables. I'm also open to that idea as well.
My main problem is that I don't know how to get url wildcards in doGet or doPost after it's routed from web.xml, so I'd either like to know how or be told that's a stupid thing to do and not do it at all.
Check out Spring MVC. With Spring Controllers you get to do URL paths like
#RequestMapping("/fixed/{id}/{user}")
public String getSomeData(#PathVariable("id") String id, #PathVariable("user") String user) {
...
}
or even
#RequestMapping("/{id}/**")
public void doSomething(#PathVariable("id") int id, HttpServletRequest request) {
String remainingUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
...
}

How to understand server/client data transfer in Angular, when coming from JSP?

I have a good basic knowledge of how to create web applications using java and jsp, together with Expression Language and JSTL. I am trying to learn how to use Angular.js for my front end.
I've gone through several tutorials, and I am starting to get a fair grip of the basics. But I have yet to figure out how to transfer data from the server, to the front end. Most tutorials I've found, describe how to send data from the front end, to the server.
I know that a RESTful api back end is recommended for Angular web apps. Unfortunately, I have no experience with this, and I find it hard to learn both angular and RESTful at the same time. If possible, I would love to make a work around, so that I can use my existing server solution, and learn one element at the time.
Server side setup
Now, in my old setup, using javax.servlet.http.HttpServlet, i call the service(HttpServletRequest, HttpServletResponse)-method. Inside the method, i add attributes to the request, like this:
request.setAttribute("attribute1", "1");
request.setAttribute("attribute2", "2");
request.setAttribute("attribute3", "3");
Then, because of a front controller pattern, I pass these request variables on to a redirect like this:
request.getRequestDispatcher("/WEB-INF/" + myPageVar + ".jsp").
forward(request, response);
For now, I would ideally like to keep this server side setup.
Current client side data access:
In the current setup, I can now access the initiated variables in two different ways. Either in a javascript script, like below (does not work with objects, only simpler attributes like strings (including JSON)). the next lines of code is picked from a jsp-page that the servlet would have redirected to.
var attribute1 = ${requestScope.attribute1};
or in the html, like this (would work with objects):
<c:set var="attribute1" value="${requestScope.attribute1}"></c:set>
I guess that I could incorporate Expression Language, and use javascript variables to initialize variables in my angular modules, directives and controllers, but I would prefer to do it purely in Angular.
Are these attributes accessible in any way, using angular? I've been trying to read up on $http, and $scope, but there is a jungle of non-relevant info on those, which I haven't been able to navigate through yet.
If the data you want to make accessible to angular should be ready when user lands on the page, it could make sense to put data in javascript variable in jsp page as you suggest.
Since your var is in global scope you can get in your angular controller like this:
$scope.att1 = attribute1;
However if you want to update your data without re-rendering the whole page (and that is what you want pretty soon) you should use $http to call a servlet that returns json. You can relatively simply make this servlet without jax-rs by overriding doGet in httpServlet and use a lightweight json lib (like gson). This example will do it:
//Set up pojo and make it into json string:
SomeClass pojo =new SomeClass();
pojo.setX("this is X");
JSONObject jsonObject = new Gson().toJson(pojo);
String jsonStr=jsonObject.toJSONString();
//Modify response and write json string
httpServletResponse.setStatus(200);//We are ok
httpServletResponse.setContentType("application/json");
httpServletResponse.setCharacterEncoding("UTF-8");
Writer writer = httpServletResponse.getWriter();
writer.write(jsonStr);
writer.close();
//Thats it
In a simple setup you handle this response in your controller like this:
$http({method: 'GET', url: 'http://yourservleturl' })
.success(function(jsonStringFromServlet){
$scope.newData = jsonStringFromServlet;
})
.error(function(){
$scope.error = true;
});
In page-html you access the data with
<div>This is your new x: {{newData.x}}</div>
Don't use jsps at all, don't set attributes.
Only use static html, thats the benefit ! You can write angular directives that perform the funcationality of jsp includes, and have much cleaner code (no embedded jstl, java. just pure html).
Create server side code that returns json. Then your angular js code calls the rest api and populates the client side model.
If you have something that needs populating on startup, use javascript appropriately.
Here is a typical java method that returns json, using Jersey (similar to Spring MVC, resteasy, restlets, spark, apache cxf etc etc) :
#PATH("/myPojo")
#GET
public Response getPojo(Long id) {
Pojo pojo = myService.getPojo(id)
return Response.ok()
.entity(pojo)
.build();
}
In angualr you can then create, for example, $myPojoService.getPojo() that is injected to relevant controllers and calls this endpoint. When called it probably returns the pojo as json and then probably populates the $scope.model.pojo json object. Then the two way databinding of angular updates your gui ... and Boom, you are a full stack engineer/ front end dev!
There are a lot of different ways to accomplish this. This is just what I ended up using.
To expose values in your JSP to Angular you'll need to write them out in script tags and build up Javascript vars with them. Then you can access them from Angular. I'm doing this to pass-in authenticated user account information from server side to my angular code. Your JSP would contain code such as:
<script>
window.CURRENT_USER = {
id: <%=currentUser.getId()%>,
name: "<%=currentUser.getName()%>",
email: "<%=currentUser.getEmail()%>",
prevLogin: new Date(<%=currentUser.getPrevLoginAt().getTime()%>),
prevLoginIp: "<%=currentUser.getPrevLoginIp()%>"
};
</script>
Then in your angular controllers, you can access it like this:
var currentUser = $window.CURRENT_USER;
A better approach (mentioned by Jacob Nicolaisen) would be to use the Google GSon library to actually generate the JSON objects instead of hand coding them.)

Get http response as a String using spring

is their a neat way to pass a model to jsp, render the jsp and return the html as string using Spring. The html is then used in an e-mail that is fired off programmitcally, I do not want to use freemarker, but maybe I should ?
The url being requested is part of the same app.
I want one of my service layer classes to be able to call a view and use the html as a String.
You can call requestDispatcher.include(request, response) method.
You will need to implement the request and response objects. The request object will provide all information to the dispatcher which page should be rendered, the response object you will pass to the call will then capture the result to a string (using e.g. a StringBuilder).
See e.g. this tutorial for more info.
I'm guessing a servlet filter will do the trick? Not really a Spring solution, but easy enough to do.
Also this answer seems relevant, although it is DWR that you may not necessarily want to use in this instance.
You can use Velocity to create an email template:
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "emailTemplate.vm", model);
There is a complete chapter in the Spring reference docs of how Spring can be used to send emails of various types.

Java using Spring restful URL

I am using Java with Spring framework.
I have a multiaction controller which is having lots of service methods, and I want to to create restful URLs like as following:
http://server.com/url/events/multiActionMethod1
http://server.com/url/events/multiActionMethod2
http://server.com/url/events/multiActionMethod3
http://server.com/url/events/multiActionMethod4
http://server.com/url/events/multiActionMethod5
How can I achieve above tasks?
I think maybe something isn't coming through clearly in your question. It reads like all you're looking for is this:
#RequestMapping("/events/multiActionMethod1")
public ReturnType multiActionMethod1(SomeParameter param) {
//request handling logic
}
is there more to the question you could elaborate on?
edit: ugh no, none of that is in 2. You'd need 2.5 for annotations and 3 if you want support for using parts of the url as parameters. The easiest thing to do if you really want it to work that way in an older version is slap a URL rewriter on the front and convert it to regular query string before it hits spring.

Categories