Hadoop好友推薦系統-項目架構搭建和用戶登陸的實現

原文出自:https://blog.csdn.net/xiaokang123456kao/article/details/74567932

項目總目錄:基於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>cn.edu.lnu</groupId>
  <artifactId>ssh_hadoop</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
   <!-- 集中定義依賴版本號 -->
    <properties>
        <junit.version>4.12</junit.version>
        <spring.version>4.1.3.RELEASE</spring.version>
        <mybatis.version>3.2.8</mybatis.version>
        <mybatis.spring.version>1.2.2</mybatis.spring.version>
        <mybatis.paginator.version>1.2.15</mybatis.paginator.version>
        <pagehelper.version>3.4.2-fix</pagehelper.version>
        <mysql.version>5.1.32</mysql.version>
        <druid.version>1.0.9</druid.version>
        <jstl.version>1.2</jstl.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
        <hadoop.version>2.7.3</hadoop.version>
        <commons-fileupload.version>1.3.2</commons-fileupload.version>    
        <commons-io.version>2.5</commons-io.version>
        <jackson.version>2.4.2</jackson.version>
    </properties>
    
    <dependencies>
            <!-- 單元測試 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
                <scope>test</scope>
            </dependency>
            <!-- Jackson Json處理工具包 -->
            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>${jackson.version}</version>
            </dependency>
            <!-- Mybatis -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis.spring.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.miemiedev</groupId>
                <artifactId>mybatis-paginator</artifactId>
                <version>${mybatis.paginator.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper</artifactId>
                <version>${pagehelper.version}</version>
            </dependency>
            <!-- MySql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.version}</version>
            </dependency>
            <!-- 連接池 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
            <!-- Spring -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- JSP相關 -->
            <dependency>
                <groupId>jstl</groupId>
                <artifactId>jstl</artifactId>
                <version>${jstl.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>${servlet-api.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jsp-api</artifactId>
                <version>${jsp-api.version}</version>
                <scope>provided</scope>
            </dependency>
            <!-- 文件上傳組件 -->
            <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>${commons-io.version}</version>
        </dependency>
        <!-- hadoop jar包 -->
        <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-client</artifactId>  
            <version>${hadoop.version}</version>  
        </dependency> 
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-mapreduce-examples</artifactId>
            <version>${hadoop.version}</version>
        </dependency> 
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>${hadoop.version}</version>
        </dependency>
    </dependencies>
    
  <build>
      <finalName>ssh_hadoop</finalName>
         <plugins>
             <plugin>
                 <artifactId>maven-war-plugin</artifactId>
                 <configuration>
                     <version>3.0</version>
                 </configuration>
             </plugin>
             <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>  
                </configuration>  
            </plugin>  
         </plugins>
     </build>
</project>

搭建SSM框架

1、數據庫屬性文件

db.properties
主要配置驅動類、Mysql的URL、Mysql用戶名和密碼等。

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/friend?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=password

2、SprinngMVC配置文件

springmvc.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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="cn.edu.lnu.controller" />
    <mvc:annotation-driven />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- 資源映射 -->
    <!-- <mvc:resources location="/WEB-INF/css/" mapping="/css/**"/>
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**"/> -->
    
    <!-- 定義文件上傳解析器 -->
    <!-- <bean id="multipartResolver" -->
    <!--     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        設定默認編碼
        <property name="defaultEncoding" value="UTF-8"></property>
        設定文件上傳的最大值5MB,5*1024*1024
        <property name="maxUploadSize" value="5242880"></property>
    </bean>
     -->
    
</beans>

3、配置Mybatis配置文件

SqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置分頁插件 -->
    <!-- <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            設置數據庫類型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六種數據庫        
            <property name="dialect" value="mysql"/>            
        </plugin>
    </plugins> -->
</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:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 數據庫連接池 -->
    <!-- 加載配置文件 -->
    <context:property-placeholder location="classpath:resource/*.properties" />
    <!-- 數據庫連接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
        destroy-method="close">
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="maxActive" value="10" />
        <property name="minIdle" value="5" />
    </bean>
    <!-- 配置sqlsessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 實體類,簡稱 -設置別名  包級別-->
        <property name="typeAliasesPackage" value="cn.edu.lnu.pojo"></property>
        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置掃描包,加載mapper代理對象 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.edu.lnu.mapper"></property>
    </bean>

<!-- 掃描包加載Service實現類 -->
    <context:component-scan base-package="cn.edu.lnu.service"></context:component-scan>
</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_2_5.xsd"
    id="ssh_hadoop" version="2.5">
    <display-name>ldmemory-manager</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index1.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
    
    <!-- 加載spring容器 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- 解決post亂碼 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- springmvc的前端控制器 -->
    <servlet>
        <servlet-name>ldmemory-manager</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextConfigLocation不是必須的, 如果不配置contextConfigLocation, springmvc的配置文件默認在:WEB-INF/servlet的name+"-servlet.xml" -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ldmemory-manager</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

6、創建項目需要的package包

 
之後會對這些包進行詳解,這裏只需要先創建出來。

二、用戶登錄的簡單實現

1、POJO層

用戶登錄類如下:
package cn.edu.lnu.pojo;
/**
 * 用戶實體類
 * @author yxk
 *2018年6月11日
 */
public class User {
	private int id;
	private String description;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	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 User() {
		super();
		// TODO Auto-generated constructor stub
	}
	
}

2、Dao層

抽取出UserMapper接口

package cn.edu.lnu.mapper;

import org.apache.ibatis.annotations.Param;

import cn.edu.lnu.pojo.User;

public interface UserMapper {
	User login(@Param("username")String username,@Param("password")String password); 
}
然後編寫配置文件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="cn.edu.lnu.mapper.UserMapper">
	<!-- 用戶登錄 -->
	<select id="login" parameterType="String" resultType="User">
		select * from loginuser where username = #{username} and password = #{password}
	</select>
</mapper>

3、service層

編寫UserService接口
package cn.edu.lnu.service;

import java.io.IOException;

public interface UserService {
	public boolean login(String username, String password);
}
編寫UserSrviceImpl實現類
package cn.edu.lnu.service.impl;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.edu.lnu.mapper.UserMapper;
import cn.edu.lnu.pojo.User;
import cn.edu.lnu.service.UserService;

/**
 * 用戶模塊
 * 
 * @author yxk 2018年6月11日
 */
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper mapper;
	/*
	 * 用戶登錄(non-Javadoc)
	 * 
	 * @see cn.edu.lnu.service.UserService#login(java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public boolean login(String username, String password) {
		User user = mapper.login(username, password);
		if (user == null) {
			return false;
		}
		return true;
	}

}

4、Controller層

package cn.edu.lnu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.lnu.service.UserService;

/**
 * 用戶登錄模塊
 * 
 * @author 尹顯坤 2018年6月11日
 */
@Controller
@RequestMapping("/login")
public class UserController {

	@Autowired
	private UserService service;

	/*
	 * 系統用戶登錄
	 */
	@RequestMapping("/loginUser_login.action")
	@ResponseBody
	public String login(String username, String password, Model model) {
		boolean flag = service.login(username, password);
		return String.valueOf(flag);
	}

}

5、前臺邏輯

<%@ 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:8080/ssh_hadoop/basic.jsp,測試即可。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章