一.导入jar包

<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.tarena</groupId>
<artifactId>tes_ssm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties>
<dependencies>
<!-- spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
<classifier>javadoc</classifier>
</dependency>
<!-- sping mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring mvc辅助 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<!-- spring tx事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mysql connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<!-- 阿里巴巴数据源druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.14</version>
</dependency>

<!-- 文件上传 apache commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>

<!-- 处理微软的office文档 apache poi 导出excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<!-- 阿里巴巴的fastjson工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>

二.  加载三个spring的清单文件

 spring_context.xml spring的上下文的

 spring_mybatis.xml 告知spring实例化mybatis中的的哪些对象

 spring_mvc.xml    告知spring实例化

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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

  <display-name>tes_ssm</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>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:conf/spring_context.xml;

          classpath:conf/spring_mybatis.xml

</param-value>

</context-param>

<!-- spring容器初始化的监听器,会读取全局初始化的数据(xml文件) -->

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

<!-- spring处理中文乱码问题 -->

<filter>

<filter-name>encodingFilter</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>

<init-param>

<param-name>forceEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

 

<!-- spring mvc的入口 加载spring mvc 前端控制器 restful -->

<!-- restful模式,必须注意在spring_mvc.xml中配置,刨除静态资源 -->

<servlet>

<servlet-name>dispatcher_restful</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:conf/spring_mvc.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcher_restful</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>

Spring_context.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:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

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/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd

        http://www.springframework.org/schema/util

        http://www.springframework.org/schema/util/spring-util.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的配置文件使用的 -->

   <context:property-placeholder

      location="classpath:conf/mysql.properties"/>         

   <!-- 加载属性文件,用于在属性文件内通过@Value注解注入java对象中 -->

   <util:properties id="manyProperties"

         location="classpath:conf/page.properties"></util:properties>

  

   <!-- 扫描service包,实例化带有@Service注解 -->

   <context:component-scan base-package="com.tarena.service"></context:component-scan>

   <!-- 扫描util包,实例化带有@Component注解 -->

   <context:component-scan base-package="com.tarena.util"></context:component-scan>

</beans>

Spring_mvc.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:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

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/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd

        http://www.springframework.org/schema/util

        http://www.springframework.org/schema/util/spring-util.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">

 

<!-- 在restful模式下,添加静态资源 -->

<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>

<mvc:resources location="/" mapping="/**"></mvc:resources>

 

<!-- 扫描spring的组件 -->

<context:component-scan base-package="com.tarena.controller"></context:component-scan>

 

 

<!-- 扫描 spring mvc的注解 @RequestMapping @ResponseBody -->

<mvc:annotation-driven></mvc:annotation-driven>

 

<!-- spring mvc 文件上传 -->

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!--能配置多少个property,可以查文档和查询源代码 -->

<!--最大上传文件的大小 -->

<property name="maxUploadSize" value="8388608"></property>

<property name="resolveLazily" value="true"></property>

</bean>

 

</beans>

Spring_mybatis.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:aop="http://www.springframework.org/schema/aop"

xmlns:tx="http://www.springframework.org/schema/tx"

xmlns:p="http://www.springframework.org/schema/p"

xmlns:util="http://www.springframework.org/schema/util"

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/aop

        http://www.springframework.org/schema/aop/spring-aop.xsd

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd

        http://www.springframework.org/schema/util

        http://www.springframework.org/schema/util/spring-util.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">

 

<!-- 数据库连接池 commons-dbcp ,c3p0,proxool,阿里巴巴druid -->

<bean id="alibabaDataSource"

      class="com.alibaba.druid.pool.DruidDataSource"

      init-method="init"

      destroy-method="close">

    <!-- 数据库连接的4项 -->

<property name="driverClassName">

<value>${jdbc_driverClass}</value>

</property>

<property name="url">

<value>${jdbc_url}</value>

</property>

<property name="username">

<value>${jdbc_userName}</value>

</property>

<property name="password">

<value>${jdbc_userPassword}</value>

</property>

<!-- 连接池中的最大连接数 -->

<property name="maxActive">

<value>5</value>

</property>

<!-- 初始化的连接数 -->

<property name="initialSize">

<value>2</value>

</property>

<!-- 获取连接的最大等待时间 -->

<property name="maxWait">

<value>6000</value>

</property>

<!-- 连接池的最大空闲 -->

<property name="maxIdle">

<value>2</value>

</property>

<!-- 连接池的最小空闲 -->

<property name="minIdle">

<value>2</value>

</property>

<!-- 自动清除无用的连接 -->

<property name="removeAbandoned">

<value>true</value>

</property>

<!-- 自动清除无用的连接的等待时间 -->

<property name="removeAbandonedTimeout">

<value>180</value>

</property>

<!-- 连接属性 -->

<property name="connectionProperties">

<value>clientEncoding=UTF-8</value>

</property>     

</bean>

<!-- 实例化MyBatis的SqlSessionFactoryBean对象-->

<!--mybatis配置,读取配置文件(扫描配置文件)-->

    <bean id="sqlSessionFactory"

        class="org.mybatis.spring.SqlSessionFactoryBean"

p:dataSource-ref="alibabaDataSource"

p:configLocation="classpath:conf/configuration.xml"

p:mapperLocations="classpath:mapper/*.xml">

 

    </bean>

    <!-- 扫描所有XXXMapper的对象 ,

                       基于sqlSessionFactory,和导包中的接口

                       创建出接口所对应的代理对象

     -->

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"

        p:basePackage="com.tarena.dao"

p:sqlSessionFactoryBeanName="sqlSessionFactory">

   

    </bean>

   

    <!-- spring 事务管理开始 -->        

   

    <!-- Spring jdbc 的事务管理器 -->

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="alibabaDataSource"/>

    </bean>

   

    <!-- 扫描事务有关的注解@Transactional -->

    <tx:annotation-driven transaction-manager="txManager"/>

  

    <!-- Spring事务管理结束 -->

</beans>

Mysql.properties

jdbc_driverClass=com.mysql.jdbc.Driver

jdbc_url=jdbc:mysql://localhost:3306/tesdb

jdbc_userName=root

jdbc_userPassword=root

 

Page.properties

pageSize=3

showNum_a=5

Configuration.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>

 

<typeAliases>

                 <typeAlias type="com.tarena.entity.User" alias="User"/> 

                 <typeAlias type="com.tarena.entity.Role" alias="Role"/> 

              <typeAlias type="com.tarena.entity.UserRole" alias="UserRole"/> 

               <typeAlias type="com.tarena.vo.Page" alias="Page"/> 

</typeAliases>

 

 

</configuration>

三. 创建java类

     com.tarena.controller   springmvc的控制器

     com.tarena.service     com.tarena.service.impl     业务操作

     com.tarena.dao   com.tarena.dao.impl        持久化操作(原生的api,接口)

     com.tarena.entity      domain ,pojo        实体包

     com.tarena.vo           值对象包

     com.tarena.util          工具包

四.登录部分:

login.html

<!DOCTYPE html>

<html lang="zh-CN">

  <head>

    <meta charset="utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->

    <meta name="author" content="Robin Liu">

 

    <title>TES Login From</title>

 

    <link rel="icon" href="favicon.ico">

    <!-- Bootstrap core CSS -->

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- 登录界面的CSS -->

    <link href="css/login.css" rel="stylesheet">

    <!-- jQuery文件。务必在bootstrap.min.js 之前引入 -->

    <script src="js/common/jquery-1.11.3.min.js"></script>

    <!-- 最新的 Bootstrap 核心 JavaScript -->

    <script src="js/common/bootstrap.min.js"></script>

   

    <!-- 自定义的js -->

    <script type="text/javascript" src="js/basepath.js"></script>

    <script type="text/javascript" src="js/cookie.js"></script>

    <script type="text/javascript" src="js/login.js"></script>

 

  </head>

 

  <body>

    <nav class="navbar navbar-inverse navbar-fixed-top">

      <div class="container-fluid">

        <div class="navbar-header">

          <a class="navbar-brand" href="#"><img src="images/logo.png"></a>

          <a class="navbar-brand" href="#"><strong>易学系统</strong></a> 

        </div>

        <div id="navbar" class="navbar-collapse collapse">

        </div>

      </div>

    </nav>

    <div class="container">

      <form class="form-signin">

        <h2 class="form-signin-heading">请登录</h2>

        <label for="inputName" class="sr-only">账号</label>

        <input type="text" id="inputName" class="form-control" placeholder="账号" required autofocus>

        <label for="inputPassword" class="sr-only">Password</label>

        <input type="password" id="inputPassword" class="form-control" placeholder="密码" required>

        <div class="checkbox">

          <label>

            <input id="rememberId" type="checkbox" value="记住账号"> 记住账号

          </label>

        </div>

        <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>

      </form>

    </div> <!-- /container -->

  </body>

</html>

login.js

//window.onload=function(){}

$(function(){

//alert("login.js");

// 从cookie中寻找有key为loginName的cookie的值,

//如果有,就放在用户名的文本框中,没有就给框中放一个空字符串

$("form input[type=text]").val(getCookie("loginName"));

console.log("login.js");

$("form").submit(function(){

return login_form();//return false,不让页面的form表单提交

});

});

//登录方法

function login_form(){

console.log("login_form");

//获取登录的用户名和密码

var lName=$("form input[type=text]").val();

var lpwd=$("form input[type=password]").val();

var remember=$("#rememberId").get(0).checked;

//console.log(lName+"   "+lpwd+"   "+remember);

alert(lName+"   "+lpwd+"   "+remember);

//发送异步ajax请求去服务器

$.ajax({

url:basePath+"user/login",

type:"get",

data:{"loginName":lName,"password":lpwd},

dataType:"json",

success:function(result){

//得到服务器返回的json数据result

//根据json数据做dom编程

if(result.status==1){

if(remember){

//要求记录账号,记录在cookie中

//添加cookie  loginName=wt_zss@126.com 存活5个小时

addCookie("loginName",lName,5)

}

window.location.href="index.html";

}else if(result.status==0){

alert(result.message)

}

 

},

error:function(){

alert("请求失败!");

}

});

 

 

return false;

}

UserController.java

 

package com.tarena.controller;

 

import javax.annotation.Resource;

import javax.servlet.http.HttpSession;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.tarena.entity.User;

import com.tarena.service.UserService;

import com.tarena.vo.Result;

 

@Controller

@RequestMapping("user/")

public class UserController {

@Resource(name="userService")

private UserService userService;

 

@RequestMapping(value="login",method=RequestMethod.GET)

@ResponseBody

public Result login(String loginName,

            String password,

            HttpSession session) {

System.out.println(loginName+"   "+password);

Result result=new Result();

User user=new User();

user.setLoginName(loginName);

user.setPassword(password);

//调用具体的登录业务

result=this.userService.login(user);

if(result.getStatus()==1) {

session.setAttribute("loginName", loginName);

}

 

return result;

}

}

UserServiceImpl.java

package com.tarena.service.impl;

 

import javax.annotation.Resource;

 

import org.springframework.stereotype.Service;

 

import com.tarena.dao.UserMapper;

import com.tarena.entity.User;

import com.tarena.service.UserService;

import com.tarena.util.PageUtil;

import com.tarena.vo.Page;

import com.tarena.vo.Result;

@Service("userService")

public class UserServiceImpl implements UserService {

    @Resource(name="userMapper")//从容器中取出的是代理对象

private UserMapper userMapper;

    @Resource(name="pageUtil")

    private PageUtil pageUtil;

   

 

@Override

public Result login(User user) {

Result result=new Result();

 

String id=this.userMapper.login(user);

if(id!=null) {

result.setStatus(1);

result.setMessage("登录成功!");

}else {

result.setStatus(0);

result.setMessage("登录失败!");

}                

return result;

}

 

@Override

public Result findRolesByPage(Page page) {

Result result=new Result();

//处理roleKeyWord的模糊关键字的的通配符

page.setRoleKeyWord(

"undefined".equals(page.getRoleKeyWord())? "%%" : "%"+page.getRoleKeyWord()+"%");

page.setPageSize(pageUtil.getPageSize());

 

 

return result;

}

 

}

UserMapper.java

package com.tarena.dao;

 

import com.tarena.entity.User;

 

public interface UserMapper {

/**

 * 登录的操作数据库的方法

 * @param user 传入的数据

 * @return 数据的id

 *         id!=null  记录存在 登录成功

 *         id=null   记录不存在 登录失败

 */

public String login(User user);

}

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.tarena.dao.UserMapper">

 

<!-- 登录 -->

<select id="login"

        parameterType="User"

        resultType="java.lang.String">

select

     user_id

from t_user

where

     user_loginname=#{loginName} and

     user_password=#{password}

</select>

 

 

</mapper>

五.登出功能:

header.html

<div class="container-fluid">

<div class="navbar-header">

  <a class="navbar-brand" href="#"><img src="images/logo.png"></a>

  <a class="navbar-brand" href="#"><strong>易学</strong></a>

</div>

<div id="navbar" class="navbar-collapse collapse">

  <ul class="nav navbar-nav navbar-right">

    <li><a href="index.html"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> 首页</a></li>

    <li><a href="#" data-toggle="modal" data-target="#message_dialog"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span> 消息 <span class="badge">5</span></a></li>

    <li><a href="#" data-toggle="modal" data-target="#editPasswd"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span> 修改密码</a></li>

    <!-- <li><a href="#"><span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span> 帮助</a></li> -->

    <li><a id="logoutId" href="#"><span class="glyphicon glyphicon-off" aria-hidden="true"></span> 退出</a></li>

  </ul>

</div>

</div>

Main.js

//@ sourceURL=main.js

 

$(function(){

$("#logoutId").click(function(){

//logout();

//logout1();

logout2();

});

});

//登出的方法

function logout(){

$.ajax({

url:basePath+"main/logout",

type:"get",

dataType:"json",

success:function(result){

if(result.status==1){

window.location.href="login.html";

}

},

error:function(){

alert("请求失败!");

}

});

}

function logout1(){

$.ajax({

url:basePath+"main/logout1",

type:"get",

dataType:"json",

success:function(result){

alert(result.flag);

if(result.flag=="success"){

window.location.href="login.html";

}

},

error:function(){

alert("请求失败!");

}

});

}

function logout2(){

$.ajax({

url:basePath+"main/logout2",

type:"get",

dataType:"json",

success:function(result){

alert(result.flag+"  "+result.key1+"    "+result.key2);

if(result.flag=="success"){

window.location.href="login.html";

}

},

error:function(){

alert("请求失败!");

}

});

}

 

}

MainController.java

package com.tarena.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.util.HashMap;

import java.util.Map;

 

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.alibaba.fastjson.JSON;

import com.tarena.vo.Result;

 

@Controller

@RequestMapping("main/")

public class MainController {

@RequestMapping(value="logout",method=RequestMethod.GET)

@ResponseBody//依赖的是jackson 

public Result logout(HttpSession session) {

System.out.println("logout");

Result result=new Result();

 

session.invalidate();//清空session中的所有的数据

result.setStatus(1);

return result;

}

@RequestMapping(value="logout1",method=RequestMethod.GET)

public void logout1(HttpSession session,

              HttpServletResponse response) {

try {

System.out.println("logout1");

Result result=new Result();

 

session.invalidate();//清空session中的所有的数据

response.setContentType("text/html;charset=utf-8");

 

String json="{\"flag\":\"success\"}";

PrintWriter out=response.getWriter();

out.print(json);

out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

@RequestMapping(value="logout2",method=RequestMethod.GET)

public void logout2(HttpSession session,

              HttpServletResponse response) {

try {

System.out.println("logout2");

Result result=new Result();

 

session.invalidate();//清空session中的所有的数据

 

Map<String,String> map=new HashMap<String,String>();

map.put("flag", "success");

map.put("key1","value1");

map.put("key2","value2");

 

//借助fastjson工具把map集合对象转换成json字符串

String json=JSON.toJSONString(map);

 

System.out.println(json);

 

 

PrintWriter out=response.getWriter();

out.print(json);

out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

 

}

}

 

注:escape(字符串);把字符串数据统一成一种码制,

Js中的null或"",这样的数据不能提交给服务器,服务器不接收null和""。

 

Role.html

<!-- 页签导航 -->

<div role="tabpanel">

  <ul class="nav nav-tabs" role="tablist">

    <li role="presentation" class="active"><a href="#rolePanel" aria-controls="rolePanel" role="tab" data-toggle="tab" >列表</a></li>

    <li role="presentation"><a href="#addPanel" aria-controls="addPanel" role="tab" data-toggle="tab">新增</a></li>

  </ul>

</div>

 

<!-- 页签面板-->

<div class="tab-content">

 

  <div role="tabpanel" class="tab-pane active" id="rolePanel">

    <div class="panel panel-default">

      <div class="panel-body">

 

        <div class="row">

          <div class="col-lg-6">

            <div class="input-group">

              <input id="role_KeyWord" type="text" class="form-control" placeholder="Search for...">

              <span class="input-group-btn">

                <button class="btn btn-primary" type="button">搜 索</button>

              </span>

            </div>

          </div>

        </div>

 

        <table class="table table-striped">

          <thead>

            <tr>

              <th class="col-md-1">#</th>

              <th class="col-md-3">编码</th>

              <th class="col-md-1">名称</th>

              <th class="col-md-1">操作</th>

            </tr>

          </thead>

          <tbody>

            <tr>

              <td>1</td>

              <td>1</td>

              <td>超级管理员</td>

              <td>

              </td>

            </tr>

            <tr>

              <td>2</td>

              <td>2</td>

              <td>讲师</td>

              <td>

              </td>

            </tr>

            <tr>

              <td>3</td>

              <td>3</td>

              <td>学员</td>

              <td>

              </td>

            </tr>

            <tr>

              <td>4</td>

              <td>00000011-4455-6677-8899-AABBCCDDEEFF</td>

              <td>评论管理员</td>

              <td>

                <a href="" data-toggle="modal" data-target="#editRole" ><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑</a>

                <a href="" data-toggle="modal" data-target=".bs-example-modal-sm"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>

              </td>

            </tr>

            <tr>

              <td>5</td>

              <td>00000011-4455-6677-8899-AABBCCDDEEFF</td>

              <td>活动管理员</td>

              <td>

                <a href="" data-toggle="modal" data-target="#editRole" ><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑</a>

                <a href="" data-toggle="modal" data-target=".bs-example-modal-sm"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>

              </td>

            </tr>

          </tbody>

        </table>

 

      </div>

    </div>

 

    <!-- 分页导航 -->

    <nav class="col-md-4 col-md-offset-4">

      <ul class="pagination">

        <li>

          <a href="#" aria-label="Previous">

            <span aria-hidden="true">&laquo;</span>

          </a>

        </li>

        <li class="active"><a href="#">1</a></li>

        <li><a href="#">2</a></li>

        <li><a href="#">3</a></li>

        <li><a href="#">4</a></li>

        <li><a href="#">5</a></li>

        <li>

          <a href="#" aria-label="Next">

            <span aria-hidden="true">&raquo;</span>

          </a>

        </li>

      </ul>

    </nav>

  </div>

 

  <!-- 新增角色 -->

  <div role="tabpanel" class="tab-pane" id="addPanel">

    <div class="panel panel-default">

      <div class="panel-body">

        <form class="form-horizontal">

          <!-- inputs -->

          <div class="form-group">

            <label class="col-md-3 control-label" for="courseName">角色名称:</label>

            <div class="col-md-8">

              <input type="text" id="courseName"  class="form-control">

            </div>

          </div>

          <!-- buttons -->

          <div class="form-group">

            <div class="col-md-8 col-md-offset-3">

              <button type="submit" class="btn btn-primary">确  认</button>

            <button type="reset" class="btn btn-primary">重  置</button>

            </div>

          </div>

        </form>

      </div>

    </div>

  </div>

 

</div>

<!-- /tab-content-->

 

<!-- 删除活动的Modal界面 -->

<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">

  <div class="modal-dialog modal-sm">

     <div class="modal-content">

      <div class="modal-header">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

        <h4 class="modal-title" id="myModalLabel">删除角色</h4>

      </div>

      <div class="modal-body">

                  确认删除该记录?

      </div>

      <div class="modal-footer">

        <button id="delete_role_btn" type="button" class="btn btn-primary">确  认</button>

        <button type="button" class="btn btn-primary" data-dismiss="modal">取  消</button>

      </div>

    </div>

  </div>

</div>

 

<!-- 修改活动的界面 -->

<div class="modal fade" id="editRole" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

  <div class="modal-dialog" role="document">

    <div class="modal-content">

      <div class="modal-header" align="center">

        <h4 class="modal-title" id="myModalLabel"><strong>编 辑 角 色</strong></h4>

      </div>

      <div class="modal-body">

      <form class="form-horizontal">

        <div class="form-group">

          <label class="col-md-3 control-label" for="coursename">角色名称:</label>

          <div class="col-md-8">

           <input type="text" id="courseName"  class="form-control">

          </div>

          </div>

          <div class="form-group">

            <div class="col-md-8 col-md-offset-3">

              <button type="submit" class="btn btn-primary">确  认</button>

              <button type="button" class="btn btn-primary" data-dismiss="modal">取  消</button>

            </div>

          </div>

        </form>

      </div>

    </div>

  </div>

</div>

Role.js

//@ sourceURL=role.js

var roleId;//全局变量

var roleName="";

$(function(){

//alert("role.js");

//当点击"角色管理"时查询说有数据的第一页

findRolesByPage(1);

//给角色的模糊查询的"搜索"按钮添加事件

$("#rolePanel .row button").click(function(){

findRolesByPage(1);

});

//给添加角色的"确定"按钮添加事件

$("#addPanel form").submit(function(){

return addRole();

});

//给删除的modal框的"确认"按钮添加click事件

$("#delete_role_btn").on("click",function(){

deleteRole();

});

//给修改的modal框的"确认"按钮添加click事件

$("#editRole button:eq(0)").click(function(){

return updateRole();

});

});

//修改角色

function updateRole(){

//获取新的角色信息

var newRoleName=$("#editRole input[type=text]").val();

if(newRoleName!=roleName){

$.ajax({

url:basePath+"role/updateRole",

type:"post",

data:{"id":roleId,"name":newRoleName},

dataType:"json",

success:function(result){

if(result.status==1){

//更新页面的角色名字为新角色名字

$("#tr_id"+roleId).find("td:eq(2)").text(newRoleName);

//关闭更新modal框

$("#editRole").modal("hide");

roleName=newRoleName;

 

}else if(result.status==0){

alert(result.message);

}

},

error:function(){

alert("请求失败!");

}

});

}

 

return false;

}

function updateClick(rid,rname){

roleId=rid;

//解决更新旧值的时候显示最原始的值的问题

if(roleName==""){

roleName=rname;

$("#editRole input[type=text]").val(rname);

}else if(roleName!=rname){

$("#editRole input[type=text]").val(roleName);

}

 

 

}

function deleteClick(rid){

//alert("rid="+rid);

roleId=rid;

}

//删除角色

function deleteRole(){

 

$.ajax({

url:basePath+"role/deleteRole/"+roleId,

type:"delete",

dataType:"json",

success:function(result){

if(result.status==1){

//说明数据库中的数据被删除了,页面的数据也要动态删除

$("#tr_id"+roleId).remove();

//把删除的框关掉

$('.bs-example-modal-sm').modal('hide');

}else if(result.status==0){

alert(result.message);

}

 

},

error:function(){

alert("请求失败!");

}

});

}

//添加角色

function addRole(){

//获取新的角色

var newRoleName=$("#addPanel form input[type=text]").val();

 

//异步ajax提交

if(newRoleName.length>0){

$.ajax({

url:basePath+"role/newRole/"+newRoleName,

type:"post",

dataType:"json",

success:function(result){

//回馈提示信息

alert(result.message);

},

error:function(){

alert("请求失败!");

}

});

}

 

return false;

}

//当点击"角色管理"时查询说有数据的第一页

function findRolesByPage(currentPage){

 

//获取数据

//当前页数据,从参数传递过来的

//模糊的关键字

var roleKeyWord=$("#role_KeyWord").val();

if(roleKeyWord==null || roleKeyWord==""){

//说白了,就是服务不接收null或""

roleKeyWord="undefined";

}

 

//发送异步ajax请求

$.ajax({

url:basePath+"role/findRolesByPage",

type:"get",

data:{"currentPage":currentPage,"roleKeyWord":roleKeyWord},

dataType:"json",

success:function(result){

if(result.status==1){

//拿到服务端返回的json数据

var page=result.data;

var roles=page.data;

//有数据了,准备做dom编程

//清空表格中的数据

$("#rolePanel table tbody").html("");//obj.innerHTML=""

//清空分页条

$("#rolePanel .pagination").html("");

//给表格添加具体的角色信息

$(roles).each(function(n,value){

//n:名字随便起,代表的是遍历到第几个元素,从0开始

//value:名字随便起,代表的当前遍历的元素

if(value.name!='讲师' && value.name!='超级管理员' && value.name!='学员'){

var tr1='<tr id="tr_id'+value.id+'">'+

              '<td>'+(n+1)+'</td>'+

              '<td>'+value.id+'</td>'+

              '<td>'+value.name+'</td>'+

              '<td>'+

                '<a href="" onclick="updateClick(\''+value.id+'\',\''+value.name+'\')" data-toggle="modal" data-target="#editRole" ><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>编辑</a>'+

                '<a href="" onclick="deleteClick(\''+value.id+'\')" data-toggle="modal" data-target=".bs-example-modal-sm"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除</a>'+

              '</td>'+   

            '</tr>';

$("#rolePanel table tbody").append(tr1);

}else{

var tr2='<tr id="tr_id'+value.id+'">'+

              '<td>'+(n+1)+'</td>'+

              '<td>'+value.id+'</td>'+

              '<td>'+value.name+'</td>'+

             ' <td>'+

              '</td>'+

            '</tr>';

$("#rolePanel table tbody").append(tr2);

}                                        

});

//构建分页条组件

if(page.totalPage>1){//page.aNum.length>1

//处理前一页

var previousLink='<li>'+

          '<a href="javascript:findRolesByPage('+page.previousPage+')" aria-label="Previous">'+

                  '<span aria-hidden="true">&laquo;</span>'+

                  '</a>'+

                  '</li>';                                        

$("#rolePanel .pagination").append(previousLink);

//处理中间的超链接

$(page.aNum).each(function(n,value){

var middleLink='<li><a href="javascript:findRolesByPage('+value+')">'+value+'</a></li>';

$("#rolePanel .pagination").append(middleLink);

});                                        

//处理后一页

var nextLink='<li>'+

          '<a href="javascript:findRolesByPage('+page.nextPage+')" aria-label="Next">'+

                  '<span aria-hidden="true">&raquo;</span>'+

                  '</a>'+

                  '</li>';

$("#rolePanel .pagination").append(nextLink);

}

 

}else if(result.status==0){

alert("没有角色数据");

}

},

error:function(){

alert("请求失败!");

}

});

 

}

RoleController.java

package com.tarena.controller;

 

import javax.annotation.Resource;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

 

import com.tarena.entity.Role;

import com.tarena.service.RoleService;

import com.tarena.vo.Page;

import com.tarena.vo.Result;

 

@Controller

@RequestMapping("role/")

public class RoleController {

@Resource(name="roleService")

private RoleService roleService;

 

@RequestMapping(value="findRolesByPage",method=RequestMethod.GET)

@ResponseBody

public Result findRolesByPage(Page page) {

System.out.println("findRolesByPage-->"+page);

Result result=null;

 

result=roleService.findRolesByPage(page);

 

return result;

}

@RequestMapping(value="newRole/{roleName}",method=RequestMethod.POST)

@ResponseBody

public Result addRole(@PathVariable("roleName") String roleName) {

System.out.println("roleName="+roleName);

Result result=null;

 

result=this.roleService.addRole(roleName);

 

return result;

 

}

@RequestMapping(value="deleteRole/{roleId}",method=RequestMethod.DELETE)

@ResponseBody

public Result deleteRole(@PathVariable("roleId") String roleId) {

System.out.println("roleId="+roleId);

Result result=null;

 

result=this.roleService.deleteRole(roleId);

 

return result;

 

}

@RequestMapping(value="updateRole",method=RequestMethod.POST)

@ResponseBody

public Result updateRole(Role role) {

System.out.println("roleId="+role.getId()+"   roleName="+role.getName());

Result result=null;

 

result=this.roleService.updateRole(role);

 

return result;

 

}

}

RoleServiceImp.java

package com.tarena.service.impl;

 

import javax.annotation.Resource;

 

import org.springframework.stereotype.Service;

 

import com.tarena.dao.RoleMapper;

import com.tarena.entity.Role;

import com.tarena.service.RoleService;

import com.tarena.util.PageUtil;

import com.tarena.util.UUIDUtil;

import com.tarena.vo.Page;

import com.tarena.vo.Result;

@Service("roleService")

public class RoleServiceImpl implements RoleService {

@Resource(name="pageUtil")

private PageUtil pageUtil;

 

@Resource(name="roleMapper")

private RoleMapper roleMapper;

 

@Override

public Result findRolesByPage(Page page) {

System.out.println("service-->findRolesByPage()");

Result result=new Result();

//处理roleKeyWord的模糊关键字的的通配符

page.setRoleKeyWord(

"undefined".equals(page.getRoleKeyWord())? "%%" : "%"+page.getRoleKeyWord()+"%");

page.setPageSize(pageUtil.getPageSize());

 

//计算总记录数

int totalCount=this.roleMapper.getRoleCount(page);

page.setTotalCount(totalCount);

//计算总页数

int totalPage=(totalCount%page.getPageSize()==0)? (totalCount/page.getPageSize()) : (totalCount/page.getPageSize())+1;

page.setTotalPage(totalPage);

 

//计算前一页

if(page.getCurrentPage()==1) {

page.setPreviousPage(1);

}else {

page.setPreviousPage(page.getCurrentPage()-1);

}

//计算下一页

if(page.getCurrentPage()==totalPage) {

page.setNextPage(totalPage);

}else {

page.setNextPage(page.getCurrentPage()+1);

}

//获取当前页的数据

 

page.setData(this.roleMapper.getRoleByPage(page));

 

//获取超链接个数

page.setaNum(pageUtil.getFenYe_a_Num(page.getCurrentPage(), page.getPageSize(), totalCount, totalPage));

result=new Result();

result.setStatus(1);

result.setData(page);//绑定page数据到result对象

//System.out.println("page="+page);

return result;

}

 

@Override

public Result addRole(String roleName) {

Result result=new Result();

//数据库插入是需要role_id 和  role_Name

Role role=new Role();

role.setId(UUIDUtil.getUUID());

role.setName(roleName);

int rowAffect=this.roleMapper.addRole(role);

if(rowAffect==1) {

result.setStatus(1);

result.setMessage("添加角色成功!");

}else {

result.setStatus(0);

result.setMessage("添加角色失败!");

}                

return result;

}

 

@Override

public Result deleteRole(String roleId) {

Result result=new Result();

 

int rowAffect=this.roleMapper.deleteRole(roleId);

if(rowAffect==1) {

result.setStatus(1);

result.setMessage("删除成功!");

}else {

result.setStatus(0);

result.setMessage("删除失败!");

}

 

return result;

}

 

@Override

public Result updateRole(Role role) {

Result result=new Result();

 

int rowAffect=this.roleMapper.updateRole(role);

if(rowAffect==1) {

result.setStatus(1);

result.setMessage("更新角色成功!");

}else {

result.setStatus(0);

result.setMessage("更新角色失败!");

}

 

return result;

}

}

RoleMapper.java

package com.tarena.dao;

 

import java.util.List;

 

import com.tarena.entity.Role;

import com.tarena.vo.Page;

 

public interface RoleMapper {

//分页查询

public int getRoleCount(Page page);

public List<Role> getRoleByPage(Page page);

//添加角色

public int addRole(Role role);

//删除角色

public int deleteRole(String roleId);

//更新角色

public int updateRole(Role role);

 

 

}

RoleMapper.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.tarena.dao.RoleMapper">

    <resultMap type="Role" id="roleMap">

            <id property="id" column="role_id"/>

            <result property="name" column="role_name"/>

    </resultMap>

<!-- 分页查询角色信息 -->

<!-- 获取总记录数,为了计算中页数 -->

<select id="getRoleCount"

        parameterType="Page"

        resultType="java.lang.Integer">

select

count(role_id)

from t_role

where role_name like #{roleKeyWord}        

</select>

<!-- 获取当前页的数据 -->

<select id="getRoleByPage"

        parameterType="Page"

        resultMap="roleMap">

select

role_id,

role_name

from t_role

where role_name like #{roleKeyWord}

limit #{begin},#{pageSize}      

</select>

<!-- 添加角色 -->

<insert id="addRole"

        parameterType="Role">

insert into t_role

(role_id,role_name)

values

(#{id},#{name})       

</insert>

<!-- 删除角色 -->

<delete id="deleteRole"

        parameterType="java.lang.String">

delete from t_role

where role_id=#{id}       

</delete>

 

<!-- 更新角色 -->

<update id="updateRole"

        parameterType="Role">

update t_role set

  role_name=#{name}

where role_id=#{id}

 

</update>

</mapper>

 

posted on 2018-04-11 16:30  莱蒙小菜鸡  阅读(105)  评论(0)    收藏  举报