使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法

使用SpringMVC框架搭建Web项目工程是目前非常流行的web项目创建方式。同时Spring Security也为我们提供了登录验证和权限控制等内容。在这篇博客中,我们将详细描述如何从0开始配置一个基于SpringMVC框架和SpringSecurity权限控制的网站。主要,需要实现搭建好Eclipse开发环境。可参考Eclipse的Web开发环境搭建——从零开始入门介绍。本项目已经上传到GitHub中,请查看https://github.com/df19900725/WebTempalte

原文地址:http://www.datalearner.com/blog/1051506305139364

一、创建Web项目

在这里,我们首先创建一个Dynamic Web Project项目。填好项目名称之后,直接点击Finish即可(不用next,这里我们用后面默认的配置)。然后,右键单击项目名称,依次选择Configure - Convert To Maven Project。将该项目转换成Maven的项目。这样,一个基于Maven的Web项目就建好了。可能有人问为啥不直接使用Maven创建。因为Eclipse的Maven插件提供的Web原型版本太低,而且常年不更新,和新的jdk版本搭配在一起很容易出错。所以我们采用这种方式。


使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第1张图片
使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第2张图片

二、配置pom.xml文件

使用SpringMVC和SpringSecurity插件需要依赖一些包。我们使用Maven的方式添加,同时,我们还需要一些连接数据库的包。我们一同在下面加进去。把下面的插件添加之后,这个网站系统就支持SpringMVC和SpringSecurity的各项功能了。后面我们将一步一步说明。

<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.0modelVersion>
  <groupId>hfutecgroupId>
  <artifactId>WebTemplateartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>warpackaging>

  
  <build>
    <sourceDirectory>srcsourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.6.1version>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
      <plugin>
        <artifactId>maven-war-pluginartifactId>
        <version>3.0.0version>
        <configuration>
          <warSourceDirectory>WebContentwarSourceDirectory>
        configuration>
      plugin>
    plugins>
  build>

  <dependencies>

    
    <dependency>
        <groupId>commons-logginggroupId>
        <artifactId>commons-loggingartifactId>
        <version>1.1.1version>
    dependency>

    
    <dependency>
        <groupId>commons-dbutilsgroupId>
        <artifactId>commons-dbutilsartifactId>
        <version>1.6version>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.34version>
    dependency>

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>druidartifactId>
        <version>1.0.12version>
    dependency>

    
    <dependency>
        <groupId>jstlgroupId>
        <artifactId>jstlartifactId>
        <version>1.2version>
    dependency>

    
    <dependency>
        <groupId>org.springframework.securitygroupId>
        <artifactId>spring-security-taglibsartifactId>
        <version>4.0.2.RELEASEversion>
    dependency>

    

    <dependency>
        <groupId>org.springframework.securitygroupId>
        <artifactId>spring-security-webartifactId>
        <version>4.0.2.RELEASEversion>
    dependency>

    <dependency>
        <groupId>org.springframework.securitygroupId>
        <artifactId>spring-security-configartifactId>
        <version>4.0.2.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.springframework.securitygroupId>
        <artifactId>spring-security-coreartifactId>
        <version>4.0.2.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>4.1.4.RELEASEversion>
    dependency>

    
    
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.5.0version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.5.0version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.5.0version>
    dependency>

    
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>4.3.6.RELEASEversion>
    dependency>

    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjrtartifactId>
        <version>1.7.3version>
    dependency>

    
    <dependency>
        <groupId>org.aspectjgroupId>
        <artifactId>aspectjweaverartifactId>
        <version>1.8.10version>
    dependency>

    
    <dependency>
        <groupId>com.google.guavagroupId>
        <artifactId>guavaartifactId>
        <version>20.0version>
    dependency>

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>1.2.38version>
    dependency>

  dependencies>
project>

三、配置Web.xml

在上述操作完毕之后,我们的网站所所依赖的包就完毕了。现在我们讲一下Web.xml的配置。当我们去启动一个WEB项目时,容器包括(JBoss、Tomcat等)首先会读取项目web.xml配置文件里的配置,当这一步骤没有出错并且完成之后,项目才能正常地被启动起来。而一些Spring框架的监控都是在这里配置的(注意:配置条目的顺序要一样,因为它是按照顺序扫描加载的。顺序错了可能会导致出错)。我们右键项目中的WEB-INF文件夹,然后新建一个web.xml(有的时候创建项目可以勾选自动创建web.xml,这里我们手动建一个)。具体配置和说明如下:


<web-app 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    metadata-complete="true" version="3.1">

    <display-name>Web Template created by D.F.display-name>

    
    <welcome-file-list>
        <welcome-file>/welcome-file>
    welcome-file-list>

    
    <session-config>
        <session-timeout>1800session-timeout>
    session-config>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <listener>
        <listener-class>org.springframework.security.web.session.HttpSessionEventPublisherlistener-class>
    listener>

    
    <filter>
        <filter-name>encodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <filter>
        <filter-name>springSecurityFilterChainfilter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
    filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChainfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/spring*.xml
                    /WEB-INF/applicationContext*.xmlparam-value>
    context-param>

    
    <servlet>
        <servlet-name>applicationContextservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>applicationContextservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.cssurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.jsurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.icourl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.gifurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.jpgurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.pngurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.bmpurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.jpegurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.swfurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.flvurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.xmlurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.txturl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.htmurl-pattern>
    servlet-mapping>
    <servlet-mapping>
        <servlet-name>defaultservlet-name>
        <url-pattern>*.htmlurl-pattern>
    servlet-mapping>
web-app>

四、添加其他的配置文件
在web.xml的配置中,我们还加了一个其他配置文件。这里我们就在WEB-INF下面再加入三个配置文件,分别是applicationContext-database.xmlapplicationContext-servlet.xmlspring-security.xml。我们将分别说明。

4.1、applicationContext-database.xml

这是阿里巴巴Druid数据连接池的配置。网站需要访问数据库,需要数据库连接池来管理数据库连接。我们使用的是druid工具。里面配置了用户名、密码、连接数、等待时间等等。不是本篇重点。我们只列出来,不说具体了。


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

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">    

        <property name="url"><value>jdbc:mysql://127.0.0.1:3306/Enterprisevalue>property> 
        <property name="username"><value>rootvalue>property> 
        <property name="password"><value>11111111value>property>

        
        <property name="initialSize" value="1" />
        <property name="minIdle" value="1" /> 
        <property name="maxActive" value="20" />

        
        <property name="maxWait" value="60000" />

        
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        
        <property name="filters" value="stat" />

    bean>

beans>
4.2、applicationContext-servlet.xml

这里主要配置SpringMVC的一些信息,包括对自动标注的支持,设置需要扫描的拦截器目录等。具体如下:


<beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:mvc="http://www.springframework.org/schema/mvc" 
             xmlns:security="http://www.springframework.org/schema/security" 
             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/mvc  
                     http://www.springframework.org/schema/mvc/spring-mvc-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/security
                     http://www.springframework.org/schema/security/spring-security-4.0.xsd" default-autowire="byName">

    <mvc:annotation-driven>
        
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8value>
                        <value>application/json;charset=UTF-8value>
                    list>
                property>
            bean>
        mvc:message-converters>
    mvc:annotation-driven>
    

    
    <mvc:default-servlet-handler />

    <context:annotation-config />

    
    <context:component-scan base-package="org.test" />

    
    <security:global-method-security jsr250-annotations="enabled" secured-annotations="enabled" pre-post-annotations="enabled"/>

    
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    bean>

beans>
4.3、spring-security.xml文件配置

这个就是配置spring-security权限控制的文件了。具体如下:


<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:beans="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    
    <http pattern="/resources/**" security="none" />
    <http pattern="/sitemap.xml" security="none" />
    <http pattern="/favicon.ico" security="none" />

    
    <http auto-config="true" use-expressions="true">

        <intercept-url pattern="/"  access="permitAll" />
        <intercept-url pattern="/index*" access="permitAll" />
        <intercept-url pattern="/signin*" access="permitAll" />
        <intercept-url pattern="/login*" access="permitAll" />
        <intercept-url pattern="/register*" access="permitAll" />
        <intercept-url pattern="/invalidsession*" access="permitAll" />
        <intercept-url pattern="/404*" access="none" />

        
        <form-login login-page="/signin" authentication-failure-url="/signin?login_error" default-target-url="/query"/>
        <logout logout-success-url="/query" delete-cookies="JSESSIONID" />

        
        <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
        <intercept-url pattern="/**" access="hasAnyRole('ROLE_ADMIN','ROLE_USER')" />

        <csrf disabled="true" />
        <access-denied-handler error-page="/403" />

        <remember-me data-source-ref="dataSource" token-validity-seconds="1209600" remember-me-parameter="remember-me" />

        <session-management invalid-session-url="/"> 
            <concurrency-control max-sessions="1"/> 
        session-management>

    http>

    <authentication-manager erase-credentials="false">
        <authentication-provider>
            <password-encoder ref="bcryptEncoder" />
            <jdbc-user-service data-source-ref="dataSource" />
        authentication-provider>
    authentication-manager>

    <beans:bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <beans:property name="basenames">
            <beans:list>
                <beans:value>classpath:myMessagesbeans:value>
            beans:list>
        beans:property>
    beans:bean>

    
    <beans:bean name="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />

beans:beans>

在上述配置文件都创建好了之后,我们的目录应该如下所示(这里把第5步骤的创建的首页也放进来了。)


使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第3张图片

五、创建首页

好了。在所有的配置文件都写好之后,我们开始创建一个首页。首先,我们在WEB-INF文件夹下创建一个views文件夹。这个之前说过了,我们在配置文件中写了。我们创建一个简单的jsp页面,如下:

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


<html lang="zh">
<head>
  <title>首页title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="cache-control" content="max-age=3600" />
  <meta http-equiv="expires" content="0" />
  <meta http-equiv="keywords" content="">
  <meta http-equiv="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

head>
<body>

    <h1>你好h1>

body>
html>

然后,我们需要创建一个Contoller来控制这个首页访问。在Java Resource下src上右键单击创建一个包,然后创建一个Java类,如下:


使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第4张图片

package org.test.controller;

import javax.servlet.http.HttpServletRequest;

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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ViewRedirectController {

  @RequestMapping("/")
  public ModelAndView index() {
    ModelAndView mav = new ModelAndView();
    mav.setViewName("/index");
    return mav;
  }

}

这里我们在类名上加上@Controller表明这是一个控制类,Spring监听器会把这个里面的方法加入到监听。然后我们创建了一个方法,声明@RequestMapping("/")表明这个方法是用来处理/请求的,就是我们常见的默认的首页。然后返回index这个页面。是使用setViewName("/index")方法。注意,这个类所在的包一定要和 applicationContext-servlet.xml 中配置的扫描的包要一致,至少要在那个包下面,负责会扫描不到这个控制类,就无法控制了。

好了,下面右键单击这个项目,点击Run As - Run on server之后,我们就可以启动这个系统(如果没有配置tomcat请先配置一下)。然后看到首页了。


使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第5张图片 使用SpringMVC创建Web工程并使用SpringSecurity进行权限控制的详细配置方法_第6张图片

本项目已经上传到GitHub中,请查看https://github.com/df19900725/WebTempalte

你可能感兴趣的:(网站系统)