spring4+hibernate4+springmvc+nginx+redis实现session共享

开发工具: intellJ idea

框架版本:spring4.3,hibernate4.3

 

新建maven项目,项目结构如下图:

spring4+hibernate4+springmvc+nginx+redis实现session共享_第1张图片

直接上代码:

User.java:

package com.ssh.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
 * Created by forwor on 2018/8/27.
 */
@Entity
@Table(name="T_USER")
public class User {

    @Id
    @GeneratedValue(generator="id")
    @GenericGenerator(name = "id",strategy="identity")
    private Integer id;

    @Column(name="user_name")
    private String userName;

    @Column(name="password")
    private String password;

    @Column(name="age")
    private int age;


    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

==================================================================================================

IUserDao.java:

package com.ssh.entity.dao;

import com.ssh.entity.User;

/**
 * Created by forwor on 2018/8/27.
 */
public interface IUserDao {
    public User getUserInfoByName(String name);
}

==================================================================================================

UserDao.java:

package com.ssh.entity.dao.impl;

import com.ssh.entity.User;
import com.ssh.entity.dao.IUserDao;
import com.util.base.BaseDao;
import org.springframework.stereotype.Repository;
import org.hibernate.Query;
import org.springframework.transaction.annotation.Propagation;


/**
 * Created by forwor on 2018/8/27.
 */
@Repository("userDao")
public class UserDao extends BaseDao implements IUserDao {
    public User getUserInfoByName(String name) {
        String hql = "from User where userName = '"+name+"'";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        return (User) query.uniqueResult();
    }
}

=================================================================================================

BaseDao.java

package com.util.base;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;

/**
 * Created by forwor on 2018/8/27.
 */
public class BaseDao {
    @Autowired
    protected SessionFactory sessionFactory;

    public Session getSession(){
        return sessionFactory.openSession();
    }
}

================================================================================================

LoginController.java:

package com.ssh.loginmana.action;

import com.ssh.entity.User;
import com.ssh.loginmana.ser.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;

/**
 * Created by forwor on 2018/8/27.
 */
@Controller
public class LoginController {
    @Autowired
    private ILoginService loginService;

   // Log log = LogFactory.getLog(this.getClass());

    @RequestMapping(value="/login", method= RequestMethod.POST)
    public String login(@ModelAttribute User user, Model model, HttpSession session, HttpServletRequest request) {
        if(user.getUserName() == null || user.getPassword() == null) {
            return "failure";
        }
        System.out.println("---------------"+user.getUserName());
        User loginUser = loginService.getUserInfoByName(user.getUserName());
        if (loginUser == null) {
            model.addAttribute("error", true);
            model.addAttribute("message", "用户不存在。");
            return "failure";
        }

        if(!user.getPassword().equals(loginUser.getPassword())) {
            model.addAttribute("error", true);
            model.addAttribute("message", "用户名或密码错误。");
            return "failure";
        }

        //request.getSession().setAttribute("USER", user);
        String token = UUID.randomUUID().toString();
        System.out.println(token);
        session.setAttribute("id", token);
        session.setAttribute("login", true);
        session.setAttribute("token", token);
        session.setAttribute("loginDate",new Date());
        session.setAttribute(user.getUserName(), token);
        return "login_success";
    }

    @RequestMapping(value="/login",method=RequestMethod.GET)
    public String login(Model model) throws Exception{
        model.addAttribute("", new User());
        return "login";
    }
}

===============================================================================================

ILoginService.java:

package com.ssh.loginmana.ser;

import com.ssh.entity.User;

/**
 * Created by forwor on 2018/8/27.
 */
public interface ILoginService {
    public User getUserInfoByName(String name);
}

===============================================================================================

LoginService.java:

package com.ssh.loginmana.ser.impl;

import com.ssh.entity.User;
import com.ssh.entity.dao.IUserDao;
import com.ssh.loginmana.ser.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by forwor on 2018/8/27.
 */
@Service("loginService")
public class LoginService implements ILoginService {
    @Autowired
    private IUserDao userDao;

    public User getUserInfoByName(String name){
        return userDao.getUserInfoByName(name);
    }
}

==================================================================================================

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: forwor
  Date: 2018/8/27
  Time: 17:32
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    
    登陆


这里是8181端口

<% String[] up = {}; //获取所有的cookie信息 Cookie[] cookies = request.getCookies(); //遍历cookies if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("userInfo")) { String ui = cookie.getValue(); //zhangsan:123 up = ui.split(":"); } } } %> 用户名:
密码:

================================================================================================

login-success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    登陆成功


登陆成功,当前位于Tomcat7页面

SessionID:<%=session.getId()%>
SessionIP:<%=request.getServerName()%>
SessionPort:<%=request.getServerPort()%>
LoginTime:<%=session.getAttribute("loginDate")%>

=================================================================================================

web.xml:



    
        jsp/login.jsp
    
    
        org.springframework.web.util.Log4jConfigListener
    
    
        log4jConfigLocation
        classpath:log4j.properties
    

    
    
        contextConfigLocation
        
            classpath:applicationContext.xml
        
    

    
    
        spring
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            
            classpath:spring-mvc.xml
        
        
        1
    

    
        spring
        *.fw
    
    


    
    
        org.springframework.web.context.ContextLoaderListener
    

    
    
        encodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
            UTF-8
        
        
            forceEncoding
            true
        
    
    
        encodingFilter
        /*
    
    
        springSessionRepositoryFilter
        org.springframework.web.filter.DelegatingFilterProxy
    
    
        springSessionRepositoryFilter
        /*
    

    
        Scutiry Filter
        com.ssh.sysmana.SecuFilter
    

    
        Scutiry Filter
        *.fw
    

    
        SpringOpenSessionInViewFilter
        org.springframework.orm.hibernate4.support.OpenSessionInViewFilter
    
    
        SpringOpenSessionInViewFilter
        /*
    

================================================================================================

依赖包: pom.xml:



    4.0.0

    com.forwor
    ssh_nginx_redis_session
    1.0-SNAPSHOT

    
    
        4.3.1.RELEASE
        4.3.5.Final
        1.2
        1.1.2
        3.0-alpha-1
        1.9.8
        2.5.0
        5.1.38
        0.9.1.2
        1.2.17
        1.3.1
        1.16.10
    

    
        
        
            junit
            junit
            3.8.1
            test
        

        
        
            org.springframework
            spring-core
            ${spring.version}
        
        
            org.springframework
            spring-aop
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        
        
            org.springframework
            spring-beans
            ${spring.version}
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-context-support
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        
        
            org.springframework
            spring-expression
            ${spring.version}
        
        
        
            org.springframework
            spring-jms
            3.1.1.RELEASE
        

        
            org.springframework
            spring-orm
            ${spring.version}
        
        
            org.springframework
            spring-test
            ${spring.version}
        
        

        
        
            org.hibernate
            hibernate-core
            ${hibernateVersion}
        

        
        
            org.hibernate
            hibernate-ehcache
            ${hibernateVersion}
        

        
        
            jstl
            jstl
            ${jstlVersion}
        
        
            taglibs
            standard
            ${taglibVersion}
        
        
            javax.servlet
            servlet-api
            ${servletVersion}
            provided
        

        
        
            mysql
            mysql-connector-java
            ${mysqlVersion}
        

        
        
            c3p0
            c3p0
            ${c3p0Version}
        

        
            com.mchange
            c3p0
            0.9.5.2
        

        
        
            org.codehaus.jackson
            jackson-mapper-asl
            ${jsonVersion}
            jar
            compile
        

        
        
            com.fasterxml.jackson.core
            jackson-core
            ${jacksonVersion}
        
        
            com.fasterxml.jackson.core
            jackson-annotations
            ${jacksonVersion}
        

        
            com.fasterxml.jackson.core
            jackson-databind
            ${jacksonVersion}
        

        
        
            log4j
            log4j
            ${log4jVersion}
        

        
        
            commons-fileupload
            commons-fileupload
            ${fileuploadVersion}
        

        
        
            org.projectlombok
            lombok
            ${lombokVersion}
            provided
        
        
        
            org.springframework.session
            spring-session-data-redis
            1.3.1.RELEASE
            pom
        
        
            redis.clients
            jedis
            2.7.2
        

        
        
            log4j
            log4j
            1.2.17
        
        
            junit
            junit
            4.12
        
    

demo下载路径:https://download.csdn.net/download/qingyou193301/10631715

 

你可能感兴趣的:(Java,spring,springmvc,hibernate,nginx,redis)