自定义httpSession

11 篇文章 0 订阅
10 篇文章 0 订阅

一个http请求,会在tomcat中创建一个request对象,一个request对象中会有一个session对象,及会话对象,标识是某个客户端的请求,并可以存储客户端的一些身份信息

 

 

自定义session

package com.fen.dou.controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;
import java.util.Enumeration;

public class CustomHttpSession implements HttpSession {
    private String id;

    CustomHttpSession(String id){
        this.id = id;
    }

    @Override
    public long getCreationTime() {
        return 0;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public long getLastAccessedTime() {
        return 0;
    }

    @Override
    public ServletContext getServletContext() {
        return null;
    }

    @Override
    public void setMaxInactiveInterval(int i) {

    }

    @Override
    public int getMaxInactiveInterval() {
        return 0;
    }

    @Override
    public HttpSessionContext getSessionContext() {
        return null;
    }

    @Override
    public Object getAttribute(String s) {
        return null;
    }

    @Override
    public Object getValue(String s) {
        return null;
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return null;
    }

    @Override
    public String[] getValueNames() {
        return new String[0];
    }

    @Override
    public void setAttribute(String s, Object o) {

    }

    @Override
    public void putValue(String s, Object o) {

    }

    @Override
    public void removeAttribute(String s) {

    }

    @Override
    public void removeValue(String s) {

    }

    @Override
    public void invalidate() {

    }

    @Override
    public boolean isNew() {
        return false;
    }
}

 

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
public class SpringSessionController {

    @GetMapping("query")
    @ResponseBody
    public String query(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.setAttribute("hello","123123123");
        System.out.println("----------sessionId-----------"+session.getId());
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies){
                System.out.println(cookie.getName() + " " + cookie.getValue());
            }
        }
        return String.valueOf(session.getAttribute("hello"));

    }
}
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@WebFilter(urlPatterns = {"/*"},filterName = "ycUpdateSessionFilter")
public class UpdateSessionFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =  ((HttpServletRequest) servletRequest);
        HttpServletResponse response =  ((HttpServletResponse) servletResponse);
        Cookie[] cookies = request.getCookies();
        UpdateSessionRequestWrapper updateSessionRequestWrapper = null;
        if(cookies != null && cookies.length > 0){
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("ycSessionId")){
                    CustomHttpSession httpSession = new CustomHttpSession(cookie.getValue()) ;
                    updateSessionRequestWrapper = new UpdateSessionRequestWrapper(request,httpSession);
                }
            }
        }
        if(updateSessionRequestWrapper == null){
            CustomHttpSession httpSession = new CustomHttpSession(UUID.randomUUID().toString()) ;
            Cookie cookie = new Cookie("ycSessionId",httpSession.getId());
            response.addCookie(cookie);
            updateSessionRequestWrapper = new UpdateSessionRequestWrapper(request,httpSession);
        }

        filterChain.doFilter(updateSessionRequestWrapper,servletResponse);
    }
}
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;

public class UpdateSessionRequestWrapper   extends HttpServletRequestWrapper {
    private HttpSession httpSession;
    public UpdateSessionRequestWrapper(HttpServletRequest request,HttpSession httpSession) {
        super(request);
        this.httpSession = httpSession;
    }
    @Override
    public HttpSession getSession() {
        return httpSession;
    }
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您想要在Java Web应用程序中重写HttpSession,可以通过实现`HttpSession`接口的自定义类来实现。 下面是一个示例代码: ```java import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; public class CustomSession implements HttpSession { private final String id; private final Map<String, Object> attributes; private boolean isNew = true; public CustomSession(String id) { this.id = id; this.attributes = new HashMap<>(); } @Override public Object getAttribute(String name) { return attributes.get(name); } @Override public Enumeration<String> getAttributeNames() { return new Vector<>(attributes.keySet()).elements(); } @Override public void setAttribute(String name, Object value) { attributes.put(name, value); } @Override public void removeAttribute(String name) { attributes.remove(name); } @Override public String getId() { return id; } @Override public long getCreationTime() { throw new UnsupportedOperationException(); } @Override public long getLastAccessedTime() { throw new UnsupportedOperationException(); } @Override public ServletContext getServletContext() { throw new UnsupportedOperationException(); } @Override public void setMaxInactiveInterval(int interval) { throw new UnsupportedOperationException(); } @Override public int getMaxInactiveInterval() { throw new UnsupportedOperationException(); } @Override public HttpSessionContext getSessionContext() { throw new UnsupportedOperationException(); } @Override public boolean isNew() { return isNew; } public void setNew(boolean isNew) { this.isNew = isNew; } } ``` 在上面的代码中,`CustomSession`类实现了`HttpSession`接口,并重写了`getAttribute`、`setAttribute`、`removeAttribute`、`getId`和`isNew`等方法。在`CustomSession`中,使用一个`Map`来存储Session中的属性值。 然后,您需要在`HttpSessionListener`中创建`CustomSession`对象,并将其存储在一个`Map`对象中,例如: ```java import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class CustomSessionListener implements HttpSessionListener { private final Map<String, HttpSession> sessions = new HashMap<>(); @Override public void sessionCreated(HttpSessionEvent se) { CustomSession session = new CustomSession(se.getSession().getId()); sessions.put(session.getId(), session); } @Override public void sessionDestroyed(HttpSessionEvent se) { sessions.remove(se.getSession().getId()); } public HttpSession getSession(String id) { return sessions.get(id); } } ``` 在上面的代码中,`CustomSessionListener`实现了`HttpSessionListener`接口,并重写了`sessionCreated`和`sessionDestroyed`方法。在`sessionCreated`方法中,创建了一个新的`CustomSession`对象,并将其存储在一个`Map`对象中。在`sessionDestroyed`方法中,从`Map`中删除`CustomSession`对象。 最后,在`HttpSessionFilter`中获取`CustomSession`对象,例如: ```java import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class CustomSessionFilter implements Filter { private final CustomSessionListener sessionListener = new CustomSessionListener(); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = sessionListener.getSession(req.getSession().getId()); if (session == null) { session = new CustomSession(req.getSession().getId()); sessionListener.getSessionMap().put(session.getId(), session); } chain.doFilter(new CustomHttpServletRequest(req, session), response); } } ``` 在上面的代码中,`CustomSessionFilter`实现了`Filter`接口,并重写了`doFilter`方法。在`doFilter`方法中,获取`CustomSession`对象,并将其存储在`Map`对象中。然后,使用`CustomHttpServletRequest`包装`HttpServletRequest`对象,并调用`chain.doFilter`方法。 这样就完成了HttpSession的重写。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值