Java 使用redis

1.创建一个maven web工程 这里 我选择使用Idea 来创建,这就不用说了,我们来看看整个目录树

这里写图片描述

先看我们的pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.redis</groupId>
  <artifactId>RedisDemo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>RedisDemo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <!-- servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc
      在项目中加入Spring mvc
    -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>


    <!-- 事务 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!--  加入Spring test-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.3.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.9</version>
    </dependency>


    <!-- 加入 mybaties -->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.8</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring
     Spring 和 mybatis的整合
     -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- redis jar -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>


    <!-- mysql 的连接 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>

    <!-- dbcp 连接池的jar -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>

    <!-- 日志 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>


    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.7</version>
    </dependency>


  </dependencies>
  <build>
    <finalName>RedisDemo</finalName>
    <resources>
    <!-- 编译过后 加入mapper资源  -->
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>


</project>

在来看看web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <!-- Spring 的主配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>


  <!-- Spring mvc 的配置文件 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


</web-app>

spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 启用spring mvc 注解 -->
    <context:annotation-config/>
    <!-- 拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.pref.interceptor.LoginHandlerInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!-- 配置扫描 路径 -->
    <context:component-scan base-package="com.pref.controller"></context:component-scan>
    <!-- 配置视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

application.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context  
                        http://www.springframework.org/schema/context/spring-context.xsd
                         http://www.springframework.org/schema/tx
                          http://www.springframework.org/schema/tx/spring-tx.xsd
                         http://www.springframework.org/schema/aop
                        http://www.springframework.org/schema/aop/spring-aop.xsd
                        ">
       <!-- 自动扫描 -->
    <context:component-scan base-package="com.pref" ><!-- use-default-filters="false"-->
       <!-- <context:include-filter type="regex" expression="com.pref.bean.*" />
        <context:include-filter type="regex" expression="com.pref.service.impl.*" />
        <context:include-filter type="regex" expression="com.pref.dao.*" />-->
    </context:component-scan>

    <!-- 引入配置文件 -->
       <bean id="propertyConfigurer"
             class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
              <property name="location" value="classpath:jdbc.properties" />
       </bean>

       <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
             destroy-method="close">
              <property name="driverClassName" value="${driver}" />
              <property name="url" value="${url}" />
              <property name="username" value="${username}" />
              <property name="password" value="${password}" />
              <!-- 初始化连接大小 -->
              <property name="initialSize" value="${initialSize}"></property>
              <!-- 连接池最大数量 -->
              <property name="maxActive" value="${maxActive}"></property>
              <!-- 连接池最大空闲 -->
              <property name="maxIdle" value="${maxIdle}"></property>
              <!-- 连接池最小空闲 -->
              <property name="minIdle" value="${minIdle}"></property>
              <!-- 获取连接最大等待时间 -->
              <property name="maxWait" value="${maxWait}"></property>
       </bean>

       <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
   <!--    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
              <property name="dataSource" ref="dataSource" />
              自动扫描mapping.xml文件
              <property name="mapperLocations">
                  <list>
                      <value>classpath*:com/pref/bean/*Mapper.xml</value>
                  </list>
              </property>
       </bean>-->

    <!-- 创建sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- *Mapper.xml中的 <mapper namespace="com.pref.dao.UserDao" > namespace 要和对应dao的接口全路径保持一直 -->
        <property name="mapperLocations" value="classpath*:com/pref/*/*Mapper.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
       <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
              <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <property name="basePackage" value="com.pref.dao"/>
       </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
       <bean id="transactionManager"
             class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
              <property name="dataSource" ref="dataSource" />
       </bean>
    <!-- Spring aop事务管理 -->
    <aop:config>
        <aop:pointcut id="transactionPointcut"
                      expression="execution(* com.pref.service..*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
                     advice-ref="transactionAdvice" />
    </aop:config>
    <!-- 拦截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>
</beans>

在来书写的登录控制器

package com.pref.controller;

import com.pref.bean.User;
import com.pref.service.LoginService;
import com.pref.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created by pref on 2016/7/26.
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;


    /**
     * 登录方法
     * @param user
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @RequestMapping("login")
    public ModelAndView handleRequest(@ModelAttribute User user, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView m = new ModelAndView("success");
        User u = loginService.login(user);
        httpServletRequest.getSession().setAttribute("userId", u.getId() + "");
        //登录成功
        // 把登录成功的对象 保存在redis服务器上
        RedisUtil.send("user" + u.getId(), u);
        m.addObject("user", u);
        return m;
    }
}

书写 实体

package com.pref.bean;

import java.io.Serializable;

/**
 * Created by pref on 2016/7/26.
 */
public class User implements Serializable {
     final long serialVersionUID = 1L;
    private int id;
    private String name;

    private String userPwd;
    private String userName;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    public String getUserName() {
        return userName;
    }

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

对应的UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pref.dao.UserDao">
    <resultMap id="userResultMap" type="com.pref.bean.User">
        <id column="id" property="id" javaType="java.lang.Integer"/>
        <result column="name" property="name" javaType="java.lang.String"/>
        <result column="user_name" property="userName" javaType="java.lang.String"/>
        <result column="user_pwd" property="userPwd" javaType="java.lang.String"/>
    </resultMap>


    <select id="findUserById" resultMap="userResultMap" parameterType="java.lang.Integer">
    select id,user_name,user_pwd from t_user tu where tu.id=#{id}
  </select>

    <select id="findUserByUserNameAndUserPwd" resultMap="userResultMap">
    select tu.id id,tu.user_name user_name,tu.user_pwd user_pwd,tu.name name from
     t_user tu where tu.user_name=#{userName}
     and tu.user_pwd=#{userPwd}
  </select>
</mapper>

登录的业务接口

package com.pref.service;

import com.pref.bean.User;

/**
 * Created by pref on 2016/7/26.
 */
public interface LoginService {

    /**
     * 登陆业务
     * @param user
     * @return
     */
    public User login(User user);

}

业务实现类

package com.pref.service.impl;

import com.pref.bean.User;
import com.pref.dao.UserDao;
import com.pref.service.LoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * Created by pref on 2016/7/26.
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserDao userDao;

    /**
     * @param user
     * @return
     */
    public User login(User user) {
        user = userDao.findUserByUserNameAndUserPwd(user.getUserName(), user.getUserPwd());
        return user;
    }
}

持久层接口

package com.pref.dao;

import com.pref.bean.User;
import org.apache.ibatis.annotations.Param;


/**
 * Created by pref on 2016/7/26.
 */
public interface UserDao {

     User findUserById(int id);

    /**
     * 根据账号密码 查询用户
     * @param userName
     * @param userPwd
     * @return
     */
      User findUserByUserNameAndUserPwd(@Param("userName") String userName,@Param("userPwd") String userPwd);

}

请求redis 工具类

package com.pref.util;

import redis.clients.jedis.Jedis;

import java.io.*;

/**
 * Created by pref on 2017/3/14.
 */
public class RedisUtil {

    private static Jedis jedis;

    //静态代码块
    static {
        jedis = new Jedis("192.168.24.130");
    }


    /**
     * 保存对象
     * @param key
     * @param serializable
     */
    public static void send(String key,Serializable serializable) {

        jedis.set(key.getBytes(),serialize(serializable));

    }

    /**
     * 获取对象
     * @param key 键
     * @return
     */
    public static Object get(String key) {

        return unserizlize(jedis.get(key.getBytes()));

    }

    /**
     * 序列化
     * @param obj
     * @return
     */
    public static byte[] serialize(Object obj) {
        ObjectOutputStream obi = null;
        ByteArrayOutputStream bai = null;
        try {
            bai = new ByteArrayOutputStream();
            obi = new ObjectOutputStream(bai);
            obi.writeObject(obj);
            byte[] byt = bai.toByteArray();
            return byt;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 反序列化
     * @param byt
     * @return
     */
    public static Object unserizlize(byte[] byt) {
        if(byt==null){
            return null;
        }
        ObjectInputStream oii = null;
        ByteArrayInputStream bis = null;
        bis = new ByteArrayInputStream(byt);
        try {
            oii = new ObjectInputStream(bis);
            Object obj = oii.readObject();
            return obj;
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

}

关于redis内存数据库安装 大家可以参考 这个
http://blog.csdn.net/pref_mail/article/details/62238085
当然 我们还需要一个来做登录拦截的拦截器

package com.pref.interceptor;

import com.pref.bean.User;
import com.pref.util.RedisUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 登录拦截
 * Created by pref on 2017/3/15.
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //获取请求的URL  
        String url = httpServletRequest.getRequestURI();
        //URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的,其它的URL都进行拦截控制  
        if (url.indexOf("login") >= 0) {
            return true;
        }
        String id = (String) httpServletRequest.getSession().getAttribute("userId");
        User user = (User) RedisUtil.get("user" + id);
        System.out.println(user + "拦截器");
        if (user != null) {
            return true;
        }
        httpServletResponse.sendRedirect("login.jsp");

        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

在写个简单的登录页面和成功页面

<form action="login.htm" method="post" >

  <p>账号:<input type="text" name="userName" /></p>
  <p>密码:<input type="password" name="userPwd" /></p>
  <input type="submit" />
</form>

页面效果 很丑!!
这里写图片描述

成功效果
这里写图片描述

第一次写bolg 写的不好 请多多指教,欢迎大家提问。
这个是http://download.csdn.net/detail/pref_mail/9783683 demo的下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值