SSM-2-旅游网站,分页PageHelper,SpringSecurity安全框架的配置和使用,PageHelper分页插件的相关参数

本文详细介绍了在SSM框架下如何使用PageHelper进行分页,包括手动分页和PageHelper插件的使用,解析了相关API并展示了配置实例。此外,还阐述了SpringSecurity安全框架的基础知识,提供了入门使用的步骤,从项目创建到自定义登录页面的配置,帮助读者理解并掌握这两个关键组件。

第一章:分页助手PageHelper

第一节:手动分页

1、页面入口

[外链图片转存失败(img-m9GqrM5X-1568920037564)(img\1.png)]

2、编写分页实体PageBean
package com.itheima.domain;

import java.util.List;

/**
 *
 * 分页的POJO对象
 *      当前页
 *      每页条数
 *      总条数
 *      总页数
 *      当前页数据
 *
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
public class PageBean <T>{

//    当前页 --- 页面传参
    private Integer currPage;
//    每页条数 -- 页面传参
    private Integer pageSize;
//    总条数 -- 数据库查询
    private Long totalCount;
//    总页数 -- 计算
        // Math.ceil(totalCount * 1.0 / pageSize)
    private Integer totalPage;
//    当前页数据 -- 数据库查询
    private List<T> list;

    public Integer getCurrPage() {
        return currPage;
    }

    public void setCurrPage(Integer currPage) {
        this.currPage = currPage;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Long getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Long totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

3、编写Controller
/**
     * 手动分页查询
     *
     * RequestParam; 请求参数绑定
     *      name:别名value, 指定页面参数的名称
     *      required: 是否必要参数
     * @return
     */
    @RequestMapping("/findAll2")
    public ModelAndView findAll2(
            @RequestParam(value = "currPage",required = false, defaultValue = "1")  Integer currPage ,
            @RequestParam(value = "pageSize",required = false, defaultValue = "5")Integer pageSize){
        //准备数据: 分页数据
        PageBean<Product> pageBean = productService.findByPage(currPage,pageSize);
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //添加数据
        modelAndView.addObject("pageBean",pageBean);
        //指定页面
        modelAndView.setViewName("product-list");
        return modelAndView;
    }
4、编写Service

接口

    /**
     * 根据分页参数查询PageBean对象
     * @param currPage
     * @param pageSize
     * @return
     */
    PageBean<Product> findByPage(Integer currPage, Integer pageSize);

实现

@Override
    public PageBean<Product> findByPage(Integer currPage, Integer pageSize) {
        //创建PageBean对象
        PageBean<Product> pageBean = new PageBean<>();
        //封装PageBean
//    当前页 --- 页面传参
//        private Integer currPage;
        pageBean.setCurrPage(currPage);
//    每页条数 -- 页面传参
//        private Integer pageSize;
        pageBean.setPageSize(pageSize);
//    总条数 -- 数据库查询
//        private Long totalCount;
        Long totalCount = productDao.findTotalCount();
        pageBean.setTotalCount(totalCount);
//    总页数 -- 计算
        // Math.ceil(totalCount * 1.0 / pageSize)
//        private Integer totalPage;
        pageBean.setTotalPage((int)Math.ceil(totalCount * 1.0 / pageSize));
//    当前页数据 -- 数据库查询
//        private List<T> list;
        /** 每页展示5条数据
         * 第一页: 1   5
         * 第二页: 6   10
         * 第三页:11  15
         * 第n页: 5n-(5-1)    5n
         * currPage ===> n
         * pageSize ==> 5
         * 第n页:pageSize * currPage-(pageSize-1)=pageSize(currPage-1) +1
         *  currPage*pageSize
         */
        Integer startIndex = pageSize*(currPage-1) +1;
        Integer endIndex = currPage*pageSize;
        List<Product> productList = productDao.findByPage(startIndex, endIndex);
        pageBean.setList(productList);
        return pageBean;
    }
5、编写Dao
/**
     * 分页查询数据
     * @param startIndex
     * @param endIndex
     * @return
     */
    @Select("select t.* from (select p.*,rownum rn from product p) t where t.rn between #{param1} and #{param2}")
    List<Product> findByPage(Integer startIndex, Integer endIndex);
}
6、编写页面
<c:forEach items="${pageBean.list}" var="product">
  
</c:forEach>

<div class="box-footer">
					<div class="pull-left">
						<div class="form-group form-inline">
							总共${pageBean.totalPage} 页,共${pageBean.totalCount} 条数据。 每页
							<select id="pageSize" οnchange="gotoPage(1)" class="form-control">
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="5" selected="selected">5</option>
								<option value="10">10</option>
							</select> 条
						</div>
					</div>

					<div class="box-tools pull-right">
						<ul class="pagination">
							<%--在超链接中访问js函数,必须加前缀:javascript--%>
							<li><a href="javascript:gotoPage(1)" aria-label="Previous">首页</a></li>
							<li><a href="javascript:gotoPage(${pageBean.currPage-1})">上一页</a></li>

							<%--begin:从哪儿开始--%>
							<%--end:到哪儿结束--%>
							<c:forEach begin="1" end="${pageBean.totalPage}" var="i">
								<li><a href="javascript:gotoPage(${i})">${i}</a></li>
							</c:forEach>
							<li><a href="javascript:gotoPage(${pageBean.currPage+1})">下一页</a></li>
							<li><a href="javascript:gotoPage(${pageBean.totalPage})" aria-label="Next">尾页</a></li>
						</ul>
					</div>

$("#pageSize option[value=${pageBean.pageSize}]").prop("selected","selected");

		function gotoPage(currPage){
		    //获取每页显示的条数
			var pageSize = $("#pageSize").val();
		    if(currPage < 1){
		        return ;
			}
			if(currPage > ${pageBean.totalPage}){
		        return ;
            }
		    location.href="${pageContext.request.contextPath}/product/findAll?currPage="+currPage+"&pageSize="+pageSize;
		}

第二节:分页助手PageHelper的使用

1、PageHelper简介

PageHelper是国内非常优秀的一款开源的mybatis分页插件,它支持基本主流与常用的数据库,例如mysql、oracle、mariaDB、DB2、SQLite、Hsqldb等。

网址:https://pagehelper.github.io/

本项目在 github 的项目地址:https://github.com/pagehelper/Mybatis-PageHelper

本项目在 gitosc 的项目地址:http://git.oschina.net/free/Mybatis_PageHelper

2、PageHelper的环境搭建

添加PageHelper坐标(之前的pom中已将包含该坐标)

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>

配置mybatis的PageHelper插件,mybatis的配置已经集成到spring的配置文件中了,所以在配置SqlSessionFactory时指定插件

 <!--引入分页插件 - 方法1 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--数据源-->
    <property name="dataSource" ref="dataSource"></property>
    <!--mybatis的其他配置 -->
    <property name="plugins">
        <array>
            <bean class="com.github.pagehelper.PageInterceptor">
                <property name="properties">
                    <props>
                        <!-- 分页的相关配置参数 详细参数解析见附录 -->
                        <prop key="helperDialect">oracle</prop>
                    </props>
                </property>
            </bean>
        </array>
    </property>
</bean>
______________________________________________________________________________
 <!--引入分页插件 - 方法2 -->
<!--引入mybatis的配置文件-->
<property name="configLocation" value="classpath:SqlMapConfig.xml"></property>


<!--创建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>
        <!--引入分页插件,不用指定数据库方言, mybatis自动选择-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>
3、PageHelper的快速入门

在ssm_web的test测试目录中创建PageHelperTest测试类

    @Override
    public void testFindByPageHelper(Integer currPage, Integer pageSize) {
//        为分页助手初始化参数
        PageHelper.startPage(currPage, pageSize);
//        查询全部
        List<Product> productList = productDao.findAll();
    }
4、PageHelper的API解析
4.1 设置分页参数

在你需要进行分页的 MyBatis 查询方法前调用PageHelper.startPage 静态方法即可,紧跟在这个方法后的第一个MyBatis 查询方法会被进行分页。

public static <E> Page<E> startPage(int pageNum, int pageSize) {
    return startPage(pageNum, pageSize, true);
}

参数:pageNum:当前页;pageSize:当前页显示的条数

4.2 获得分页相关数据

创建PageInfo对象,将查询结果作为参数传递进构造,则可以通过PageInfo获得分页的相关信息:

 @Override
    public void testFindByPageHelper(Integer currPage, Integer pageSize) {
//        为分页助手初始化参数
        PageHelper.startPage(currPage, pageSize);
//        查询全部
        List<Product> productList = productDao.findAll();
//        创建PageInfo对象 -- 相当于自定义PageBean :需要通过构造传入查询的集合对象 , 页面最多显示5个页码
        PageInfo<Product> pageInfo = new PageInfo<>(productList, 5);
        System.out.println("当前页:"+ pageInfo.getPageNum());
        System.out.println("每页条数:"+ pageInfo.getPageSize());
        System.out.println("总页数:"+ pageInfo.getPages());
        System.out.println("总条数:"+ pageInfo.getTotal());
        System.out.println("数据:"+ pageInfo.getList().size());
        System.out.println("上一页页码:"+ pageInfo.getPrePage());
        System.out.println("下一页页码:"+ pageInfo.getNextPage());
        System.out.println("是否第一页:"+ pageInfo.isIsFirstPage());
        System.out.println("是否最后一页:"+ pageInfo.isIsLastPage());
        System.out.println("页面显示的第一个页码:"+pageInfo.getNavigateFirstPage());
        System.out.println("页面显示的最后一个页码:"+pageInfo.getNavigateLastPage());

    }
5、分页查询集成PageHelper
5.1、页面入口

[外链图片转存失败(img-ViHkxuJA-1568920037567)(img\3.png)]

5.2、编写Controller
/**
     * 分页助手查询
     *
     * RequestParam; 请求参数绑定
     *      name:别名value, 指定页面参数的名称
     *      required: 是否必要参数
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(
            @RequestParam(value = "currPage",required = false, defaultValue = "1")  Integer currPage ,
            @RequestParam(value = "pageSize",required = false, defaultValue = "5")Integer pageSize){
        //准备数据: 分页数据
        PageInfo<Product> pageInfo = productService.findByPageHelper(currPage, pageSize);
        //创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        //添加数据
        modelAndView.addObject("pageInfo",pageInfo);
        //指定页面
        modelAndView.setViewName("product-list");
        return modelAndView;
    }
5.3、编写Service

接口

    /**
     * 根据分页助手查询
     * @param currPage
     * @param pageSize
     * @return
     */
    PageInfo<Product> findByPageHelper(Integer currPage, Integer pageSize);

实现

 @Override
    public PageInfo<Product> findByPageHelper(Integer currPage, Integer pageSize) {
//        指定分页参数
        PageHelper.startPage(currPage, pageSize);
//        查询全部
        List<Product> productList = productDao.findAll();
//        创建PageInfo对象
        PageInfo<Product> pageInfo = new PageInfo<>(productList,3);

        return pageInfo;
    }
5.4、编写Dao
  @Select("select * from product")
    List<Product> findAll();
5.5、编写页面
<c:forEach items="${pageInfo.list}" var="product">
  
</c:forEach>

<!-- .box-footer-->
				<div class="box-footer">
					<div class="pull-left">
						<div class="form-group form-inline">
							总共${pageInfo.pages} 页,共${pageInfo.total} 条数据。 每页
							<select id="pageSize" οnchange="gotoPage(1)" class="form-control">
								<option value="2">2</option>
								<option value="3">3</option>
								<option value="5" selected="selected">5</option>
								<option value="10">10</option>
							</select> 条
						</div>
					</div>

					<div class="box-tools pull-right">
						<ul class="pagination">
							<%--在超链接中访问js函数,必须加前缀:javascript--%>
							<li><a href="javascript:gotoPage(1)" aria-label="Previous">首页</a></li>
							<li><a href="javascript:gotoPage(${pageInfo.prePage})">上一页</a></li>

							<%--begin:从哪儿开始--%>
                            <%--"页面显示的第一个页码:"pageInfo.getNavigateFirstPage();--%>
							<%--"页面显示的最后一个页码:"pageInfo.getNavigateLastPage();--%>
							<%--end:到哪儿结束--%>
							<c:forEach begin="${pageInfo.navigateFirstPage}" end="${pageInfo.navigateLastPage}" var="i">
								<li><a href="javascript:gotoPage(${i})">${i}</a></li>
							</c:forEach>
							<li><a href="javascript:gotoPage(${pageInfo.nextPage})">下一页</a></li>
							<li><a href="javascript:gotoPage(${pageInfo.pages})" aria-label="Next">尾页</a></li>
						</ul>
					</div>
          
$("#pageSize option[value=${pageInfo.pageSize}]").prop("selected","selected");

		function gotoPage(currPage){
		    //获取每页显示的条数
			var pageSize = $("#pageSize").val();
		    if(currPage < 1){
		        return ;
			}
			if(currPage > ${pageInfo.pages}){
		        return ;
            }
		    location.href="${pageContext.request.contextPath}/product/findAll?currPage="+currPage+"&pageSize="+pageSize;
		}

第二章:SpringSecurity安全框架

第一节:SpringSecurity的简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

  • “认证”,是为用户建立一个他所声明的主体。主体一般是指用户,设备或可以在你系 统中执行动作的其他系统。
  • “授权”,指的是一个用户能否在你的应用中执行某个操作,在到达授权判断之前,身份的主题已经由身份验证过程建立了。

第二节:SpringSecurity的入门使用

1、创建itheima_springSecurity项目(war)

[外链图片转存失败(img-P18W5IL6-1568920037568)(img\4.png)]

2、导入SpringSecurity的坐标(pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<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.itheima</groupId>
  <artifactId>itheima_springsecurity</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <spring.security.version>5.0.1.RELEASE</spring.security.version>
  </properties>
  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <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>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-taglibs</artifactId>
      <version>${spring.security.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <!-- java编译插件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <configuration>
          <!-- 指定端口 -->
          <port>8080</port>
          <!-- 请求路径 -->
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
3、配置spring-security.xml

在类加载路径resources下创建spring-security.xml配置文件,配置认证和授权信息

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <!--
        配置拦截的规则
        auto-config="使用自带的页面"
        use-expressions="是否使用spel表达式",如果使用表达式:hasRole('ROLE_USER')
    -->
    <security:http auto-config="true" use-expressions="false">
        <!-- 配置拦截的请求地址,任何请求地址都必须有ROLE_USER的权限 -->
        <security:intercept-url pattern="/**" access="ROLE_USER"/>
    </security:http>
    
    <!-- 配置认证信息 -->
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

</beans>
4、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <!--Spring监听器指定配置文件位置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-security.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置委派代理过滤器: filter-name必须是:springSecurityFilterChain  -->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>
5、测试

访问index.jsp页面,如果当前用户没有登录认证的话,则跳转到SpringSecurity的内置登录页面

[外链图片转存失败(img-aBaRvitL-1568920037568)(img\5.png)]

6、配置自定义登录页面
 
7、login.html页面
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<h1>自定义的登录页面</h1>
<form action="login" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username" /></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password" /></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input type="submit" value="登录" />
                <input type="reset" value="重置" /></td>
        </tr>
    </table>
</form>
</body>
</html>
8、success.html页面
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
success html<br>
<a href="logout">退出</a>
</body>
</html>
9、error.html页面
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>登录失败
</body>
</html>

第三节:项目集成SpringSecurity

1、添加spring-security.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:security="http://www.springframework.org/schema/security"
       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.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security.xsd">

    <!-- 不拦截静态资源和样式 -->
    <security:http pattern="/css/**" security="none"/>
    <security:http pattern="/img/**" security="none"/>
    <security:http pattern="/plugins/**" security="none"/>

    <!-- 把登陆页面不拦截 -->
    <security:http pattern="/login.jsp" security="none"/>

    <!--
        配置拦截的规则
        auto-config="使用自带的页面"
        use-expressions="是否使用spel表达式",如果使用表达式:hasRole('ROLE_USER')
    -->
    <security:http auto-config="true" use-expressions="false">
        <!-- 配置拦截的请求地址,任何请求地址都必须有ROLE_USER的权限 -->
        <security:intercept-url pattern="/**" access="ROLE_USER"/>
     <!-- 配置具体的页面跳转 -->
        <!--指定安全框架使用的页面-->
        <!--login-page: 指定登录页面
            login-processing-url: 登录请求路径-登录时必须使用该路径
            default-target-url:登录成功后进入的页面
            authentication-failure-url;认证失败之后要进入的页面
        -->
        <security:form-login
                login-page="/login.jsp"
                login-processing-url="/login"
                default-target-url="/index.jsp"
        ></security:form-login>

        <!-- 关闭跨域请求 -->
        <security:csrf disabled="true"/>

        <!-- 退出 -->
        <security:logout invalidate-session="true" logout-url="/logout" logout-success-url="/login.html"/>

    </security:http>

    <!-- 在内存中临时提供用户名和密码的数据 -->
    <security:authentication-manager>
        <security:authentication-provider>
            <security:user-service>
                <security:user name="admin" password="{noop}admin" authorities="ROLE_USER"/>
            </security:user-service>
        </security:authentication-provider>
    </security:authentication-manager>

</beans>
2、修改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>ssm_web</display-name>


  <!--1、配置spring的监听器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml,classpath:spring-security.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--2、配置SptingMVC的前端控制器-->
  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--服务器启动就创建该Servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--3、乱码的解决方案-->
  <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>

  <!--4、springsecurity委派过滤器-->
  <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <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>
</web-app>
3、创建用户表和用户实体
create sequence user_seq;

CREATE TABLE sys_user(
  id number PRIMARY KEY,
  username VARCHAR2(50) unique,
  email VARCHAR2(50) ,
  password VARCHAR2(80),
  phoneNum VARCHAR2(20),
  status number
)

insert into sys_user values(user_seq.nextval, 'zhangsan','zhangsan@itcast.cn',
      '123', '12345678901', 1);
  
insert into sys_user values(user_seq.nextval, 'zhaosi','zhaosi@itcast.cn',
      '123', '12345678902', 1);
package com.itheima.domain;

public class SysUser {

    private Long id;
    private String username;
    private String email;
    private String password;
    private String phoneNum;
    private int status;

    //省略getter和setter方法... ...
}

4、修改spring-security.xml,修改认证方式为查询数据库
<!-- 在内存中临时提供用户名和密码的数据 -->
<security:authentication-manager>
	<!-- 提供服务类,去数据库查询用户名和密码 -->
	<security:authentication-provider user-service-ref="userService"/>
</security:authentication-manager>
5、编写UserService业务代码

userService接口,接口集成UserDetailsService接口,安全框架的用户认证接口类:
UserDetailsService接口:基本上就是根据前端提交上来的用户名从数据库中查找这个账号的信息,然后比对密码。再进一步,可能还会添加一个字段来判断,当前用户是否已被锁定。这个接口就是这么用的。即把这些信息取出来,然后包装成一个对象交由框架去认证。

/**
 *
 * UserDetailsService: 接口中提供了一个方法:loadUserByUsername
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
public interface UserService extends UserDetailsService{
}

userServiceImpl实现

package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.SysUser;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    /**
     * 通过用户名得到用户对象
     * 创建用户详情对象,返回
     * @param username
     * @return UserDetails: 用户详情
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名获取用户(SysUser)对象
        SysUser sysUser = userDao.findByUsername(username);
        if(sysUser != null){
            //创建角色的集合对象
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            //创建临时的角色对象
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_USER");
            //对象添加到集合中
            authorities.add(grantedAuthority);
            /**
             * 参数1:用户名
             * 参数2:密码
             * 参数3:角色列表对象
             */
            UserDetails user = new User(sysUser.getUsername(),"{noop}"+sysUser.getPassword(), authorities);

            return user;
        }
        return  null;
    }
}

6、修改login.jsp的表单
<form action="login">
  
</form>

附录:PageHelper分页插件的相关参数

  1. helperDialect:分页插件会自动检测当前的数据库链接,自动选择合适的分页方式。 你可以配置helperDialect属性来指定分页插件使用哪种方言。配置时,可以使用下面的缩写值:
    oracle,mysql,mariadb,sqlite,hsqldb,postgresql,db2,sqlserver,informix,h2,sqlserver2012,derby
    **特别注意:**使用 SqlServer2012 数据库时,需要手动指定为 sqlserver2012,否则会使用 SqlServer2005 的方式进行分页。
    你也可以实现 AbstractHelperDialect,然后配置该属性为实现类的全限定名称即可使用自定义的实现方法。
  2. offsetAsPageNum:默认值为 false,该参数对使用 RowBounds 作为分页参数时有效。 当该参数设置为 true 时,会将 RowBounds 中的 offset 参数当成 pageNum 使用,可以用页码和页面大小两个参数进行分页。
  3. rowBoundsWithCount:默认值为false,该参数对使用 RowBounds 作为分页参数时有效。 当该参数设置为true时,使用 RowBounds 分页会进行 count 查询。
  4. pageSizeZero:默认值为 false,当该参数设置为 true 时,如果 pageSize=0 或者 RowBounds.limit = 0 就会查询出全部的结果(相当于没有执行分页查询,但是返回结果仍然是 Page 类型)。
  5. reasonable:分页合理化参数,默认值为false。当该参数设置为 true 时,pageNum<=0 时会查询第一页,pageNum>pages(超过总数时),会查询最后一页。默认false 时,直接根据参数进行查询。
  6. params:为了支持startPage(Object params)方法,增加了该参数来配置参数映射,用于从对象中根据属性名取值, 可以配置 pageNum,pageSize,count,pageSizeZero,reasonable,不配置映射的用默认值, 默认值为pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero
  7. supportMethodsArguments:支持通过 Mapper 接口参数来传递分页参数,默认值false,分页插件会从查询方法的参数值中,自动根据上面 params 配置的字段中取值,查找到合适的值时就会自动分页。 使用方法可以参考测试代码中的 com.github.pagehelper.test.basic 包下的 ArgumentsMapTestArgumentsObjTest
  8. autoRuntimeDialect:默认值为 false。设置为 true 时,允许在运行时根据多数据源自动识别对应方言的分页 (不支持自动选择sqlserver2012,只能使用sqlserver),用法和注意事项参考下面的场景五
  9. closeConn:默认值为 true。当使用运行时动态数据源或没有设置 helperDialect 属性自动获取数据库类型时,会自动获取一个数据库连接, 通过该属性来设置是否关闭获取的这个连接,默认true关闭,设置为 false 后,不会关闭获取的连接,这个参数的设置要根据自己选择的数据源来决定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值