有关redis的介绍我就不说了,可以参看我前几篇文章,redis快速入门
首先来看一下redis的应用场景
下面是我这个项目的的运行的场景截图
这是我们经常在各博客见到的顶和踩的画面,对于这种场景,我们用非关系型数据库来操作是非常不方便地,不光是查询不方便(写sql语句),而且在高并发的时候,可能会使系统假死,所以redis就派上用场了,它属于非关系型数据库,它直接操作内存,非常快速。
下面直接看代码
首先看看所需的包
除了Spring和Struts2所需的包外 还需连接redis的包 这里是spring-data-redis
本项目是模拟用户实现顶和踩的功能
所以先创一个实体类User
package com.yc.beans;
public class User {
private int ding;//顶
private int cai;//踩
public int getCai() {
return cai;
}
public void setCai(int cai) {
this.cai = cai;
}
public int getDing() {
return ding;
}
public void setDing(int ding) {
this.ding = ding;
}
}
因为是spring+Struts2一起,所以要改web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<!-- spring的配置文件的路径, -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<!-- 配置spring的上下文临听器: 当应用程序一加载到服务器上时,就会调用这个 ContextLoaderListerner, 这个临听器会读取contextConfigLocation配置的spring配置文件,完成
spring容器的初始化.
-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts2的前端过滤器 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
首先看一下客户端请求页面 index.jsp
<%@ page
language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta
http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style>
#head {
font-family: cursive;
font-size: 25px;
color: orange;
cursor: pointer;
}
#content {
height =300px;
font-family: cursive;
font-size: 20px;
}
.ding {
border: 1px solid blue;
height: 60px;
width: 70px;
margin-left: 150px; padding-left10px;
float: left;
background: #FFF;
}
.ding img {
display: inline-block;
margin-