您的位置:首页 > 运维架构 > 网站架构

Hadoop好友推荐系统-项目架构搭建和用户登陆的实现

2017-07-12 21:23 866 查看

项目总目录:基于Hadoop的好友推荐系统项目综述

一、创建Maven项目

创建一个Maven web项目(即war项目),引入依赖如下:

<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.kang</groupId>
<artifactId>Hadoop_FindFriend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>Friend Find  Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>4.1.3.RELEASE</org.springframework.version>
<struts2.version>2.3.1</struts2.version>
<log4j.version>2.0</log4j.version>
<mysql.jdbc.version>5.1.21</mysql.jdbc.version>
<hibernate.version>4.3.1.Final</hibernate.version>
<commons.fileupload.version>1.2.1</commons.fileupload.version>
<javassist.version>3.12.1.GA</javassist.version>
<cxf.version>3.0.2</cxf.version>
<hadoop.version>2.6.0</hadoop.version>
<fastjson.version>1.1.36</fastjson.version>
</properties>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jfree</groupId>
<artifactId>jfreechart</artifactId>
<version>1.0.15</version>
</dependency>

<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>

<!--utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0-rc1</version>
</dependency>

<!-- servlet3 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jasper-compiler</artifactId>
<version>5.5.23</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>tomcat</groupId>
<artifactId>jasper-runtime</artifactId>
<version>5.5.23</version>
<scope>provided</scope>
</dependency>

<!-- cxf -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>${cxf.version}</version>
</dependency>

<!-- 读取字节码包 -->
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>

<!-- commons配置 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons.fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.10</version>
</dependency>

<!-- aspectj -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjlib</artifactId>
<version>1.6.2</version>
</dependency>

<!-- quartz -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.0</version>
</dependency>

<!-- mysql的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.jdbc.version}</version>
</dependency>

<!-- c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>

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

<!-- log4j的依赖 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j.version}</version>
</dependency>

<!-- Struts2-core 依赖 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>

</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16.3</version>
</dependency>

<!-- hiberante 4 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!-- Spring 框架 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Bean Factory and JavaBeans utilities (depends on spring-core) Define
this if you use Spring Bean APIs (org.springframework.beans.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Aspect Oriented Programming (AOP) Framework (depends on spring-core,
spring-beans) Define this if you use Spring AOP APIs (org.springframework.aop.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context (depends on spring-core, spring-expression, spring-aop,
spring-beans) This is the central artifact for Spring's Dependency Injection
Container and is generally always defined -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Various Application Context utilities, including EhCache, JavaMail,
Quartz, and Freemarker integration Define this if you need any of these integrations -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Transaction Management Abstraction (depends on spring-core, spring-beans,
spring-aop, spring-context) Define this if you use Spring Transactions or
DAO Exception Hierarchy (org.springframework.transaction.*/org.springframework.dao.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library (depends on spring-core, spring-beans, spring-context,
spring-tx) Define this if you use Spring's JdbcTemplate API (org.springframework.jdbc.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA,
and iBatis. (depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you need ORM (org.springframework.orm.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB,
JiBX, Castor, XStream, and XML Beans. (depends on spring-core, spring-beans,
spring-context) Define this if you need OXM (org.springframework.oxm.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and
Portlet Environments (depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another
web framework with Spring (org.springframework.web.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Spring MVC for Servlet Environments (depends on spring-core, spring-beans,
spring-context, spring-web) Define this if you use Spring MVC with a Servlet
Container such as Apache Tomcat (org.springframework.web.servlet.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments (depends on spring-core, spring-beans,
spring-context, spring-web) Define this if you use Spring MVC with a Portlet
Container (org.springframework.web.portlet.*) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>

<!-- Support for testing Spring applications with tools such as JUnit and
TestNG This artifact is generally always defined with a 'test' scope for
the integration testing framework and unit testing stubs -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>

<!-- hadoop dependency -->
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>${hadoop.version}</version>
<exclusions>
<exclusion>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-common</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-jobclient</artifactId>
<version>${hadoop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-examples</artifactId>
<version>${hadoop.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port>80</port>
<path>/friend_find</path>
</configuration>
</plugin>
</plugins>
</build>
</project>


搭建SSH框架

1、数据库属性文件

db.properties

主要配置驱动类、Mysql的URL、Mysql用户名和密码等。

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///:3306/friend
db.username=root
db.password=root


2、struts2配置文件

struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.action.extension" value="action" />
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 指定允许上传的文件最大字节数。默认值是2097152(2M) ,设置为1G-->
<constant name="struts.multipart.maxSize" value="1073741824"/>
<!-- 设置上传文件的临时文件夹,默认使用javax.servlet.context.tempdir -->
<constant name="struts.multipart.saveDir" value="d:/tmp" />

<!--下面配置struts2的Action-->

</struts>


3、配置Hibernate配置文件

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="jdbc.batch_size">20</property>
<property name="connection.autocommit">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 显示sql语句 -->
<property name="show_sql">false</property>
<property name="connection.useUnicode">true</property>
<property name="connection.characterEncoding">UTF-8</property>
<!--   <property name="current_session_context_class" >thread</property>  -->
<!-- 缓存设置 -->
<property name="cache.provider_configuration_file_resource_path">/ehcache.xml</property>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
<property name="cache.use_query_cache">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>

</session-factory>
</hibernate-configuration>


这里使用了ehcache来进行缓存,相应配置文件如下:

ehcache.xml

<ehcache>

<!-- Sets the path to the directory where cache .data files are created.

If the path is a Java System Property it is replaced by
its value in the running VM.

The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path -->
<diskStore path="java.io.tmpdir"/>

<!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.

The following attributes are required for defaultCache:

maxInMemory       - Sets the maximum number of objects that will be created in memory
eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.

-->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
/>

<!--Predefined caches.  Add your cache configuration settings here.
If you do not have a configuration for your cache a WARNING will be issued when the
CacheManager starts

The following attributes are required for defaultCache:

name              - Sets the name of the cache. This is used to identify the cache. It must be unique.
maxInMemory       - Sets the maximum number of objects that will be created in memory
eternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk    - Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.

-->

<!-- Sample cache named sampleCache1
This cache contains a maximum in memory of 10000 elements, and will expire
an element if it is idle for more than 5 minutes and lives for more than
10 minutes.

If there are more than 10000 elements it will overflow to the
disk cache, which in this configuration will go to wherever java.io.tmp is
defined on your system. On a standard Linux system this will be /tmp"
-->
<cache name="sampleCache1"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
overflowToDisk="true"
/>

<!-- Sample cache named sampleCache2
This cache contains 1000 elements. Elements will always be held in memory.
They are not expired. -->
<cache name="sampleCache2"
maxElementsInMemory="1000"
eternal="true"
timeToIdleSeconds="0"
timeToLiveSeconds="0"
overflowToDisk="false"
/> -->

<!-- Place configuration for your caches following -->

</ehcache>


4、添加Spring配置文件

applicationContext.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

<!-- 加载数据库属性配置文件 -->
<context:property-placeholder location="classpath:db.properties" />

<!-- 数据库连接池c3p0配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="${db.url}"></property>
<property name="driverClass" value="${db.driverClassName}"></property>
<property name="user" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
<property name="maxPoolSize" value="40"></property>
<property name="minPoolSize" value="1"></property>
<property name="initialPoolSize" value="1"></property>
<property name="maxIdleTime" value="20"></property>
</bean>

<!-- session工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<!-- 自动扫描注解方式配置的hibernate类文件 -->
<property name="packagesToScan">
<list>
<value>com.kang.model</value>
</list>
</property>
</bean>

<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<!-- 配置事务通知属性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- 定义事务传播属性 -->
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>

<!-- 应用普通类获取bean
<bean id="appContext" class="com.soanl.util.tool.ApplicationUtil"/>-->

<!-- 配置事务切面 -->
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* com.kang.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
<!-- 使用注解方式生成的bean注入xml配置的bean需加上这个配置 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 自动加载构建bean -->
<context:component-scan base-package="com.kang" />
<!--  引入注解   -->
<context:annotation-config />
</beans>


5、修改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/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<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>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<!-- struts2拦截所有请求 -->
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.do,*.action</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>basic.html</welcome-file>
<welcome-file>basic.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>


6、创建项目需要的package包



之后会对这些包进行详解,这里只需要先创建出来。

7、利用maven tomcat插件启动项目测试

在maven build配置中进行相关设置如下:



点击Run运行,查看结果如下:



如果项目正常启动不报错,则说明SSH框架搭建没有问题,我们可以实现我们的业务逻辑代码了。

二、用户登录的简单实现

1、model层

这里首先抽取出一个接口

/**
* 抽象一个接口,所有实体model需要实现这个接口
*/
package com.kang.model;

import java.util.Map;

public interface ObjectInterface {
/**
* 这里根据表名实现属性的自动装配,避免每个实体类都设一个方法
* @param map
* @return
*/
public  Object setObjectByMap(Map<String,Object> map);
}


用户登录类如下:

package com.kang.model;

import java.io.Serializable;
import java.util.Map;

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

@Entity
@Table(name="loginuser")//对应数据库中的loginuser表
/**
* 用户登录表LoginUser,实现序列化和ObjectInterface两个接口
*/
public class LoginUser implements Serializable,ObjectInterface {

private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String password;
private String description;

public LoginUser(){ }
public LoginUser(String username,String password){
this.username=username;
this.password=password;
}

public Object setObjectByMap(Map<String,Object> map){
LoginUser lu = new LoginUser();
lu.setDescription((String)map.get("description"));
lu.setId((Integer)map.get("id"));// 修改是有id的,新增没有id
lu.setPassword((String)map.get("password"));
lu.setUsername((String)map.get("username"));
return lu;//返回用户实体类参数
}
@Id
@GeneratedValue
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 String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}

}


2、Dao层(这里使用泛型实现)

抽取出BaseDao接口

package com.kang.dao;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;

/**
* 基础数据库操作类
*
*/
public interface BaseDAO<T> {

/**
* 保存一个对象
*
* @param o
* @return
*/
public Serializable save(T o);

/**
* 删除一个对象
*
* @param o
*/
public void delete(T o);

/**
* 更新一个对象
*
* @param o
*/
public void update(T o);

/**
* 保存或更新对象
*
* @param o
*/
public void saveOrUpdate(T o);

/**
* 查询
*
* @param hql
* @return
*/
public List<T> find(String  hql);

/**
* 查询集合
*
* @param hql
* @param param
* @return
*/
public List<T> find(String hql, Object[] param);

/**
* 查询集合
*
* @param hql
* @param param
* @return
*/
public List<T> find(String hql, List<Object> param);

/**
* 查询集合(带分页)
*
* @param hql
* @param param
* @param page
*            查询第几页
* @param rows
*            每页显示几条记录
* @return
*/
public List<T> find(String hql, Object[] param, Integer page, Integer rows);

/**
* 查询集合(带分页)
*
* @param hql
* @param param
* @param page
* @param rows
* @return
*/
public List<T> find(String hql, List<Object> param, Integer page, Integer rows);

/**
* 获得一个对象
*
* @param c
*            对象类型
* @param id
* @return Object
*/
public T get(Class<T> c, Serializable id);

/**
* 获得一个对象
*
* @param hql
* @param param
* @return Object
*/
public T get(String hql, Object[] param);

/**
* 获得一个对象
*
* @param hql
* @param param
* @return
*/
public T get(String hql, List<Object> param);

/**
* select count(*) from 类
*
* @param hql
* @return
*/
public Long count(String hql);

public BigInteger sqlCount(String sql);

/**
* select count(*) from 类
*
* @param hql
* @param param
* @return
*/
public Long count(String hql, Object[] param);

/**
* select count(*) from 类
*
* @param hql
* @param param
* @return
*/
public Long count(String hql, List<Object> param);

/**
* 执行HQL语句
*
* @param hql
* @return 响应数目
*/
public Integer executeHql(String hql);

/**
* 执行HQL语句
*
* @param hql
* @param param
* @return 响应数目
*/
public Integer executeHql(String hql, Object[] param);

/**
* 执行HQL语句
*
* @param hql
* @param param
* @return
*/
public Integer executeHql(String hql, List<Object> param);

/**
* @param lists
* @return
*/
Integer saveBatch(List<Object> lists);

}


然后编写实现类BaseDAOImpl

package com.kang.dao;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kang.utli.Utils;
//@Repository为数据层dao的类注解
@Repository("baseDAO")
@SuppressWarnings("all")
public class BaseDAOImpl<T> implements BaseDAO<T> {
private Logger log = LoggerFactory.getLogger(BaseDAOImpl.class);
private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}

private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}

public Serializable save(T o) {
return this.getCurrentSession().save(o);
}

public void delete(T o) {
this.getCurrentSession().delete(o);
}

public void update(T o) {
this.getCurrentSession().update(o);
}

public void saveOrUpdate(T o) {
this.getCurrentSession().saveOrUpdate(o);
}

public List<T> find(String hql) {
return this.getCurrentSession().createQuery(hql).list();
}

public List<T> find(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.list();
}

public List<T> find(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.list();
}

public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
if (page == null || page < 1) {
page = 1;
}
if (rows == null || rows < 1) {
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}

public List<T> find(String hql, List<Object> param, Integer page, Integer rows) {
if (page == null || page < 1) {
page = 1;
}
if (rows == null || rows < 1) {
rows = 10;
}
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
}

public T get(Class<T> c, Serializable id) {
return (T) this.getCurrentSession().get(c, id);
}

public T get(String hql, Object[] param) {
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0) {
return l.get(0);
} else {
return null;
}
}

public T get(String hql, List<Object> param) {
List<T> l = this.find(hql, param);
if (l != null && l.size() > 0) {
return l.get(0);
} else {
return null;
}
}

public Long count(String hql) {
return (Long) this.getCurrentSession().createQuery(hql).uniqueResult();
}

public BigInteger sqlCount(String sql){
return (BigInteger)this.getCurrentSession().createSQLQuery(sql).uniqueResult();
}

public Long count(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return (Long) q.uniqueResult();
}

public Long count(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return (Long) q.uniqueResult();
}

public Integer executeHql(String hql) {
return this.getCurrentSession().createQuery(hql).executeUpdate();
}

public Integer executeHql(String hql, Object[] param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.length > 0) {
for (int i = 0; i < param.length; i++) {
q.setParameter(i, param[i]);
}
}
return q.executeUpdate();
}

public Integer executeHql(String hql, List<Object> param) {
Query q = this.getCurrentSession().createQuery(hql);
if (param != null && param.size() > 0) {
for (int i = 0; i < param.size(); i++) {
q.setParameter(i, param.get(i));
}
}
return q.executeUpdate();
}

@Override
public Integer saveBatch(List<Object> lists) {
Session session = this.getCurrentSession();
//      org.hibernate.Transaction tx = session.beginTransaction();
int i=0;
try{
for ( Object l:lists) {
i++;
session.save(l);
if( i % 50 == 0 ) { // Same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
if(i%1000==0){
System.out.println(new java.util.Date()+":已经预插入了"+i+"条记录...");
}
}
}}catch(Exception e){
e.printStackTrace();
}
//      tx.commit();
//      session.close();
Utils.simpleLog("插入数据数为:"+i);
return i;
}

}


这里用到了Utils中的一些方法:

package com.kang.utli;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.ServletActionContext;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.kang.model.ObjectInterface;

/**
* 工具类
*/
public class Utils {

private static PrintWriter writer = null;

/**
* 简单日志
*
* @param msg
*/
public static void simpleLog(String msg) {
System.out.println(new java.util.Date() + ":" + msg);
}

/**
* 获得表的实体类的全路径
*
* @param tableName
* @return
*/
public static String getEntityPackages(String tableName) {
return "com.fz.model." + tableName;
}

/**
* 根据类名获得实体类
*
* @param tableName
* @param json
* @return
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
@SuppressWarnings("unchecked")
public static Object getEntity(String tableName, String json) throws ClassNotFoundException, InstantiationException,
IllegalAccessException, JsonParseException, JsonMappingException, IOException {
Class<?> cl = Class.forName(tableName);// 根据全类名创建对应的实体类对象
ObjectInterface o = (ObjectInterface) cl.newInstance();// 利用了多态
Map<String, Object> map = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();// 转换json时需要的对象
try {
// convert JSON string to Map
map = mapper.readValue(json, Map.class);
return o.setObjectByMap(map);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 向PrintWriter中输入数据
*
* @param info
*/
public static void write2PrintWriter(String info) {
try {
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
writer = ServletActionContext.getResponse().getWriter();

writer.write(info);// 响应输出
// 释放资源,关闭流
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* @param flag
*/
public static void write2PrintWriter(boolean flag) {
write2PrintWriter(String.valueOf(flag));
}
}


3、service层

package com.kang.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.kang.dao.BaseDAO;
import com.kang.model.LoginUser;
import com.kang.utli.Utils;

/**
* 数据库service
*
*/
@Service("dBService")
public class DBService {

private Logger log = LoggerFactory.getLogger(DBService.class);
@Resource
private BaseDAO<Object> baseDao;

/**
* 用户登录检查
*
* @param username
* @param password
* @return
*/
public boolean getLoginUser(String username, String password) {
String hql = "from LoginUser lu where lu.username='" + username + "'";
List<Object> lus = baseDao.find(hql);
if (lus.size() < 1) {
log.info("没有此用户,username:{}", username);
return false;
}
if (lus.size() > 1) {
log.info("登录检查多个重名用户,请检查数据库,用户名为:{}", username);
return false;
}
LoginUser lu = (LoginUser) lus.get(0);
if (lu.getPassword().equals(password)) {
log.info("用户:'" + username + "' 登录成功!");
return true;
}
return false;
}

/**
* 测试表中是否有数据
*
* @param tableName
* @return
*/
public boolean getTableData(String tableName) {
String hql = "from " + tableName + " ";
List<Object> td = baseDao.find(hql);
if (td.size() > 0) {
return true;
}
return false;
}

/**
* 获得tableName的所有数据并返回
*
* @param tableName
* @return
*/
public List<Object> getTableAllData(String tableName) {
String hql = "from " + tableName + " ";
List<Object> list = null;
try {
list = baseDao.find(hql);
} catch (Exception e) {
e.printStackTrace();
}
return list;
}

/**
* 分页获取tableName 所有数据
*
* @param tableName:类实体名
* @param rows
* @param page
* @return
*/
public Map<String, Object> getTableData(String tableName, int rows, int page) {
String hql = "from " + tableName;
String hqlCount = "select count(1) from " + tableName;
List<Object> list = baseDao.find(hql, new Object[] {}, page, rows);
Map<String, Object> jsonMap = new HashMap<String, Object>();
jsonMap.put("total", baseDao.count(hqlCount));
jsonMap.put("rows", list);
return jsonMap;
}

/**
* 保存数据
*
* @param tableName
* @param list
* @return
*/
public boolean saveTableData(List<Object> list) {

try {
baseDao.saveBatch(list);
} catch (Exception e) {
e.printStackTrace();
return false;
}

return true;
}

public boolean deleteById(String tableName, String id) {
String hql = "delete " + tableName + "  tb where tb.id='" + id + "'";
try {
Integer ret = baseDao.executeHql(hql);
log.info("删除表{},删除了{}条记录!", new Object[] { tableName, ret });
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

public boolean deleteTable(String tableName) {
String hql = "delete " + tableName;
try {
Integer ret = baseDao.executeHql(hql);
log.info("删除表{},删除了{}条记录!", new Object[] { tableName, ret });
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

/**
* 更新或者插入表 不用每个表都建立一个方法,这里根据表名自动装配
*
* @param tableName
* @param json
* @return
*/
public boolean updateOrSave(String tableName, String json) {
try {
// 根据表名获得全类名并创建相应的实体类,并赋值
Object o = Utils.getEntity(Utils.getEntityPackages(tableName), json);
baseDao.saveOrUpdate(o);
log.info("保存表{}!", new Object[] { tableName });
} catch (Exception e) {

e.printStackTrace();
return false;
}
return true;
}

/**
* 初始化登录表
*
* @param tableName
* @return
*/
public boolean insertLoginUser() {
try {
baseDao.executeHql("delete LoginUser");
baseDao.save(new LoginUser("admin", "admin"));
baseDao.save(new LoginUser("test", "test"));
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

}


4、action层

package com.kang.action;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.kang.service.DBService;
import com.kang.utli.Utils;
import com.opensymphony.xwork2.ActionSupport;

@Component("loginUserAction")
//@component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>)
public class LoginUserAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Logger log = LoggerFactory.getLogger(LoginUserAction.class);
/*
* 使用指定类初始化日志对象
* 在日志输出的时候,可以打印出日志信息所在类
* 如:Logger logger = LoggerFactory.getLogger(com.Book.class);
* logger.debug("日志信息");将会打印出: com.Book : 日志信息
*/
@Resource
private DBService dBService;

private String password;
private String username;

public void login(){
log.info("User:{} 正在登陆系统...",username);
try{
boolean flag = dBService.getLoginUser(username, password);
Utils.write2PrintWriter(flag);
}catch(Exception e){
e.printStackTrace();
}

}
/**
* @return the dBService
*/
public DBService getdBService() {
return dBService;
}
/**
* @param dBService the dBService to set
*/
public void setdBService(DBService dBService) {
this.dBService = dBService;
}
/**
* @return the username
*/
public String getUsername() {
return username;
}
/**
* @param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}

}


5、在struts配置文件中配置该action

<package name ="login" namespace="/login" extends="struts-default">
<action name ="loginUser_*" method="{1}" class="com.kang.action.LoginUserAction" />
</package>


6、前台逻辑

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

<script type="text/javascript">
$(function() {

var formParam = {
url : 'login/loginUser_login.action',
success : function(result) {
//  var r = $.parseJSON(result);
//if (r.success) {
console.info(result);
if(result=='true'){
$('#user_login_loginDialog').dialog('close');

//  $('#sessionInfoDiv').html(formatString('[<strong>{0}</strong>],欢迎你!', r.obj.loginName));

//  $('#layout_east_onlineDatagrid').datagrid('load', {});
} else {
$.messager.show({
title : '提示',
msg : '用户名或密码错误!'
});
}
}
};

$('#user_login_loginInputForm').form(formParam);

$('#user_login_loginDialog').show().dialog({
modal : true,
title : '系统登录',
closable : false,
buttons : [
// {
//  text : '注册',
//  handler : function() {
//      $('#user_reg_regDialog').dialog('open');
//  }
//},
{
text : '登录',
handler : function() {
$('#user_login_loginInputForm').submit();
}
} ]
});

var sessionInfo_userId = '${sessionInfo.userId}';
if (sessionInfo_userId) {/*目的是,如果已经登陆过了,那么刷新页面后也不需要弹出登录窗体*/
$('#user_login_loginDialog').dialog('close');
}

});
</script>
<div id="user_login_loginDialog" style="display: none;width: 300px;height: 210px;overflow: hidden;">
<div id="user_login_loginTab">
<div style="overflow: hidden;">
<div>
<div class="info">
<div class="tip icon-tip"></div>
<div>用户名是"admin",密码是"admin"</div>
</div>
</div>
<div align="center">
<form method="post" id="user_login_loginInputForm">
<table class="tableForm">
<tr>
<th>登录名</th>
<td><input name="username" class="easyui-validatebox" data-options="required:true" value="admin" />
</td>
</tr>
<tr>
<th>密码</th>
<td><input type="password" name="password" class="easyui-validatebox" data-options="required:true" style="width: 150px;" value="admin" /></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>


7、测试

通过maven的tomcat插件启动项目,访问页面:http://localhost/friend_find,测试即可。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: