I have a login method in a GWT RPC Servlet, which gets a user from the session context and therefore determins, if the user is logged in or not. I want to port this method to the request factory approach (to get a proxy entity instead of a DTO).
But where can i place it? I can't place it in the Entity because there i don't have the session context. Whats the right approach here?
My RPC method currently looks like this:
#Override
public UserDTO isLoggedIn() {
// TODO Auto-generated method stub
HttpSession session = getThreadLocalRequest().getSession();
String userName = (String)session.getAttribute("userName");
if(userName !=null){
return new UserDTO(userName);
}
return null;
}
RequestFactory also provides methods for accessing the request and servlet context
HttpSession session = com.google.web.bindery.requestfactory.server.RequestFactoryServlet.getThreadLocalRequest().getSession();
Documentation can be found here:
http://google-web-toolkit.googlecode.com/svn/javadoc/latest/com/google/web/bindery/requestfactory/server/RequestFactoryServlet.html#getThreadLocalRequest()
Related
So, I am working on creating a simple chat app. I'm not using spring security.
So, in front end, the user enters their name which is handled by this controller.
#PostMapping("/addUser")
public User addUser(#RequestBody String name, HttpServletRequest request) {
String session = (String) request.getSession().getAttribute("sessionId");
System.out.println("Session id is " + session);
User newUser = new User(name, session);
userService.addUser(newUser);
System.out.println(newUser);
return newUser;
}
I'm using pre handler method handler interceptor to generate session id for the user. Below is the code:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("Its working");
// TODO Auto-generated method stub
if(request instanceof HttpServletRequest) {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpSession session = servletRequest.getSession();
session.setAttribute("sessionId", session.getId());
System.out.println("Connected with session id : " + session.getAttribute("sessionId"));
}
return true;
}
So, I want to make sure that whenever users are inactive for cetain time, I want to end the session for that user and also remove that user from the arraylist of user where I have kept all the users who register by entering their name (in the front end).
Is it possible to achieve without sprin security or do I have to learn spring security to implement it.
I did try using task scheduler but then I found out in some article that its impossible to call HttpSession there.
You can set the session life (time it can be inactive before being killed) with server.servlet.session.timeout=30m
You can take the user out of your list by implementing a HttpSessionListener.sessionDestroyed - spring-boot-session-listener
if you use WebSocket, You can use heartbeat for your session, on the other hand, if you use rest then you should keep the session in memory(redis, hazelcast, or in-memory (singleton object) like map<key, session>,
(keep in mind, the client should send a disconnect request or you should control it in the backend)
guys.
I have the following code for my http session at Wicket-based application:
public static HttpServletRequest getHttpServletRequest() {
Request request = RequestCycle.get().getRequest();
if (request != null && request instanceof WebRequest) return
HttpServletRequest) request.getContainerRequest();
return null;
}
public static SessionObject getSessionObject() {
HttpServletRequest request = getHttpServletRequest();
HttpSession session = request == null ? null : request.getSession();
SessionObject so = session == null ? null : (SessionObject) session.getAttribute("so");
if (so == null) {
logger.warn("SessionObject is not found in HttpSession!");
}
return so;
}
The session object is initialized at jsp like the following:
jsp:useBean id="so" class="package.SessionObject" scope="session"
I'd like to mock this attribute so into Wicket tests.
Tried to do the following:
bind(SessionObject.class).toInstance(EasyMock.createMock(SessionObject.class));
also
tester = new WicketTester(new MockApplication() {
#Override
public Session newSession(Request request, Response response) {
final Session session = super.newSession(request, response);
session.setAttribute("so", EasyMock.createMock(SessionObject.class));
return session;
}
});
But when I try to call method as:
init(){
a = getSessionObject().getA();
}
getSessionObject() returns null because there are no attribute named "so".
Could you help please me to mock this attribute into session?
You can simplify your helper methods to: Session.get().getAttribute("so").
Your code that writes the value already uses Session#setAttribute().
Try by binding the session: Session#bind(). Unless bound Wicket will create a new instance of Session for each request. Once bound Wicket will acquire HttpSession and store Wicket's Session into it (as attribute).
If this doesn't help then put a breakpoint at Session set/getAttribute() methods and see what happens.
I need to dispatch a web service caller to a new page using Response object:
#Path("controller")
#Stateless
public class ControllerEJB {
HttpSession session;
User user;
String url;
#POST
public Response registerUser(
#QueryParam("fornamn") String fornamn,
#QueryParam("efternamn") String efternamn,
#QueryParam("epost") String epost,
#QueryParam("epost2") String epost2,
#QueryParam("password") String password,
#Context HttpServletRequest request
){
session = request.getSession();
if(user == null)
user = new User();
user.setEmail(epost);
user.setPassword(password);
user.setFornamn(fornamn);
user.setEfternamn(efternamn);
session.setAttribute("user", user);
return Response.status(200)...... // e.g. url is a .jsp
}
What method should I be using?
JAX-RS is designed to build REST services.
REST services should return data, generally serialized using XML or JSON.
I wouldn't recommend to forward JAX-RS requests to a view layer such as JSP or JSF.
That said, i'm not sure you can forward the same way RequestDispatcher.forward(req, res) does.
But you can send a redirection using the following:
return Response.seeOther(new URI("/path/to/your/resource")).build();
But as the documenation says, this should be used in a POST/redirect/GET pattern: you may redirect a POST request to another REST resource using the GET method.
But again, redirecting REST resource to a JSP page is an awkward design.
I would like to get the username from within HttpSessionListener.sessionCreated(). When I say username, I mean specifically that name that is returned by HttpServletRequest.getRemoteUser().
Obviously, there must have been a HttpServletRequest object that caused the session to be created (and hence the sessionCreated() call). But how do I access it from within sessionCreated()? The HttpSessionEvent object passed into sessionCreated() appears to provide no way to get at the HttpServletRequest object that caused the session to be created.
The HttpSessionListener does not have access to the HttpServletRequest object because it is invoked when no request has been madeāto notify of session destruction or creation.
So, a Filter would be better places where you can add username = request.getRemoteUsr() into session.
Example - Filter Code
String username = request.getRemoteUsr() ;
session.setAttribute("username",username);
and then retrive this username in sessionCreated method as
String username = (String)session.getAttribute("username");
i hope you will get the same username of the same request which has created this session in HttpSessionListener sessionCreated() method.
// set
session.setAttribute("username", request.getRemoteUser();
// get
String un = (String) session.getAttribute("username");
You could use a HttpSessionAttributeListener:
public class UsernameHttpSessionAttributeListener implements HttpSessionAttributeListener {
#Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
if (httpSessionBindingEvent.getName().equals("username")) {
// do something
}
}
...
}
Of course, you need to set the attribute username in the HTTP session anywhere, for instance in a servlet filter.
I have an Interceptor on Struts2, and I want for some pages to redirect to the ssl version of them.
Example: http://localhost/xhtml/path.do?ossesionid=value1 to https://localhost/xhtml/path.do?ossesionid=value1
For doing this I created a Interceptor that does this:
public String intercept(ActionInvocation invocation) throws Exception {
// initialize request and response
final ActionContext context = invocation.getInvocationContext();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final HttpServletResponse response = (HttpServletResponse) context
.get(StrutsStatics.HTTP_RESPONSE);
// check scheme
String scheme = request.getScheme().toLowerCase();
// check method
String method = request.getMethod().toUpperCase();
// If the action class uses the SSLProtected marker annotation, then see
// if we need to
// redirect to the SSL protected version of this page
if (invocation.getAction() instanceof SSLProtected) {
if (HTTP_GET.equals(method) && SCHEME_HTTP.equals(scheme)) {
// initialize https port
String httpsPortParam = request.getSession().getServletContext().getInitParameter(HTTP_PORT_PARAM);
int httpsPort = httpsPortParam == null ? HTTPS_PORT : Integer.parseInt(httpsPortParam);
response.setCharacterEncoding("UTF-8");
URI uri = new URI(SCHEME_HTTPS, null, request.getServerName(), httpsPort, response.encodeRedirectURL(request.getRequestURI()), request.getQueryString(), null);
log.debug("Going to SSL mode, redirecting to " + uri.toString());
response.sendRedirect(uri.toString());
return null;
}
}
My problem is that I expect this
https://localhost/xhtml/path.do?ossesionid=value1
and got
https://localhost/xhtml/path.do;jsessionid=value1?osessionid=value1
And I'm Completly lost! help anyone?
i strongly suggest you to use S2-SSL plugin which is more flexible and provides a much better support to handle switch from SSL to non-SSL and vice-versa.
regarding generation of Jsessionid,JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want get session.You have ways to disable the creation of Jsessionid
There are number of way you can disable the creation of this id, please refer to this discussion thread.
I am still not sure what is the problem you are facing with this session-id as it is a very common case in web applications
is-it-possible-to-disable-jsessionid-in-tomcat-servlet