How to Delegate the Session from One service to another Service - java

i am new to service and java.i will explain my workflow.
Client will call one synchronous service to service 1. service 1 do some operation and will delegate the session to service 2.then service 1 become free and ready to do some other work.service 2 do some operation and response back to client. is this possible like delegate the work to some other service and reply back to client. below Diagram makes you more clear.
in servlet we can redirect the response (response.sendredirect(url)) to some url like service or html page.but i think that response just redirect to some different url not the session right. so i want to know whether above workflow is possible ? if its possible please give some piece of code or ref link .

You can use RequestDispatcher class to forward the request to service 2;
RequestDispatcher rd = context_object.getRequestDispatcher('url to service 2');
rd.forward(request, response);
Inside service 2, you can use
request_object.getSession();
to get the original session object

Related

Best way to use Websocket with Spring Boot and Vuejs

I try to use Websocket with spring boot backend (as an API) and Vuejs frontend.
I take a simple use case to expose my question. Some users are logged on my website, and there is a messaging feature. User A send a message to User B. User B is actually logged, and I want to notify User B that a new message is arrived.
I see 3 ways to do it with websockets :
1 - When User A send message, an Axios post is call to the API for saving message, and, if the Axios response is success, I call something like
this.stompClient.send("/app/foo", JSON.stringify(bar), {})
2 - When User A send message, I only call something like
this.stompClient.send("/app/foo", JSON.stringify(bar), {})
and it's my controller's method (annotated with #MessageMapping("/xxxx") #SendTo("/topic/yyyy")) that call facade, service, dao to first, save message, then return message to subscribers
3 - I keep my actuals controllers, facade, services and DAO, and juste add when save is successfull something like :
#Autowired SimpMessagingTemplate webSocket;
...
#GetMapping("/send-message")
public ResponseEntity sendMessage(#AuthenticationPrincipal User user, ....) {
service.saveMessage(....);
webSocket.convertAndSend("/ws/message-from", message);
without a new controller contains #MessageMapping("/xxxx") #SendTo("/topic/yyyy"). User B is just subscibed to "/ws/message-from"
Could you help me.
In the 3 way there is a good method ?
Thanks you.
The one and two method has no much difference as you use axios from npm for sending request and the other one you can directly,while the third one you use controller,and facade dao at single place.it is about architecture and how you wanna send your requests for your framework,as a requirement.
They serve best at their level,till you come with specific requirement.
The suggestion would be to use axios.
It has advantages:
supports older browsers (Fetch needs a polyfill)
has a way to abort a request
has a way to set a response timeout
has built-in CSRF protection
supports upload progress
performs automatic JSON data transformation
works in Node.js

How to send values from one jsp page to other but redirect to some other page?

I want to send values from jsp1.jsp to jsp2.jsp but redirect jsp1.jsp to jsp3.jsp . I used the following code in servlet for jsp1
response.sendRedirect("welcome1.jsp");
request.setAttribute("usern",user);
RequestDispatcher rd = request.getRequestDispatcher("afterlogin.jsp");
rd.forward(request,response);
but it keeps on giving this error "org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP".
you can use the possiblites of sessions in those case so you can access the parameter in jsp2 and redirect the jsp 1 to 3
https://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://java.candidjava.com/tutorial/Servlet-Jsp-HttpSession-Login-logout-example.htm
You can use a HttpSession object as a user session, or use the ServletContext object for sharing global application information. Then use methods getAttribute (String attb) and setAttribute (String attb, String value) for sharing information within JSPs. The issue when you use a request is that the domain of the request is constraining you to use this information only when you receive this request.
You can also use JavaBeans to share information within JSPs
EDIT: Have you included your Java code inside a scriptlet? Using <% your code here %>
when you are using the sendRedirect function it will immediately redirect to that page it will not read next line code.
So according to your code your compiler is smart enough to check it so it is giving you an error.
please see below
1) SendRedirect ():
This method is declared in HttpServletResponse Interface.
Signature: void sendRedirect(String url)
1)In case of sendRedirect request is transfer to another resource to different domain or different server for further processing.
2)When you use SendRedirect container transfers the request to client or browser so URL given inside the sendRedirect method is visible as a new request to the client.
3)In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4)SendRedirect is slower because one extra round trip is required because completely new request is created and old request object is lost.Two browser request required.
5)But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.
2) Forward():
This method is declared in RequestDispatcher Interface.
Signature: forward(ServletRequest request, ServletResponse response)
1)When we use forward method request is transfer to other resource within the same server for further processing.
2)In case of forward Web container handle all process internally and client or browser is not involved.
3)When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request
4)Using forward () method is faster then send redirect.
5)When we redirect using forward and we want to use same data in new resource we can use request. setAttribute() as we have request object available.
more in : https://www.javatpoint.com/q/3577/difference-between-requestdispatcher-and-sendredirect

Forwarding to httpRequest that is not the current HttpRequest

I'm making a Java webapp which uses the Spring 4 framework.
When a user makes any request, if the user is not logged in, I use an interceptor to store this request object inside the user's session. Afterwards I redirect the user to a login screen.
When the user succesfully logs in, I want the login controller to not return a model and view (for example, the homepage) but instead fetch the stored previous request from the session and "execute" it as if the user just launched that request.
I'm having some problems with filling in some variables:
public ModelAndView login(RedirectAttributes redirectAttributes)
{
... //Do login stuff.
HttpServletRequest previousRequest = (HttpServletRequest) httpServletRequest.getSession().getAttribute("previousRequest");
httpServletRequest.getRequestDispatcher(previousRequest.getServletPath()).forward(previousRequest, ????????);
//end of method, I must return a ModelAndView but I don't have any view, I just want the request to be forwarded??
return null; //???????????
}
When getting the request dispatcher, you need to give it an url. I used httpServletRequest.getServletPath() but I'm not sure if this is correct.
When forwarding, you need to give a request and response object. But I don't have the response object at this time. I could perhaps also store the response object just like I did with the request. Or is there any other way? What would happen if I supply the CURRENT reponse object instead of the PREVIOUS response object?
My method expects me to return a modelandview, but I don't have any. How can I tell Spring to stop doing its normal "modelandview" scheme and instead start working on the forwarding of the request?
The setup described above is impossible in Jboss. You cannot forward and pass an arbitrary request object, because the servlet container will display an error. The forward method is meant to forward the CURRENT request object that is begin processed by the container.
A possible strategy, although still not ideal, is to wrap the stored request together with a freshly incoming request, and override the important methods like getParameters()´ andgetAttribute()´ to use the stored request instead of the actual request. This is the way Spring security solves this.
It seems to be impossible to tell a servletcontainer to stop handling the current request and redirect or forward to an arbitrary request object you just so happen to have available in your servlet.

Obtain servlet response when using Cross-Context

I'm using cross-context to call a servlet in another server application: Servlet /bar from server application 'A' calls /foo servlet on server application 'B'.
I'm using this very nice solution, just as in the Abhijeet Ashok Muneshwar answer, I forward the request from server application A to the /foo servlet on server application B.
I'm using the class RequestDispatcher () to send a request, but the response is returned in the same call?
RequestDispatcher rd = context.getRequestDispatcher("/Servlet2");
rd.forward(request, response);
How can I process and return the response from server application B in A's servlet.
Thanks.
If you use a forward, that passes control to the target of the forward. The other option with a RequestDispatcher is to do an include.
If you want more control than that, you'll have to use an HTTP client to retrieve the response and then apply whatever processing you want to but using an HTTP client this way is not something I'd recommend. You'd be better off refactoring your application so you can use RequestDispatcher.include.

call httpclient from servlet

pseudo code
service(..){
//httpclient get http://www.facebook.com
}
the above is pseudo code for java servlet, when user call this servlet service(..) from browser repeatly
for instance
1. call http://localhost:8080/callService?url=facebook.com/index.php
2. call http://localhost:8080/callService?url=facebook.com/editprofile.php
can these subsequent request using the same "session" ?
Checkout HttpState class to handle cookie and session. Here is the sample code.

Categories

Resources