spring mvc 4.1.1集成spring-security3.2.10 demo

 

1、针对eclipse(jdk1.8 tomcat8.0),创建SpringMVC工程,File->New->Dynamic Web Project

project name 随意,->finish

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

2、WebContent下WEB-INF下lib添加项目所需jar包,附jar包贴图

构建路径:右击项目->Build Path ->Configure Build Path ->Libraries ->Add JRES (选择项目、lib下jar包)依次选择 ok

3、WEB-INF下创建web.xml初始化配置信息,具体看注释

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
 id="WebApp_ID" version="3.1">
  <display-name>SpringMVC</display-name>
  
  <!-- contextConfigLocation配置就是扫描我们的spring mvc和spring security配置文件。 -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <!-- 启用上下文配置文件 -->
      <param-value>/WEB-INF/SpringMVC-servlet.xml,/WEB-INF/applicationContext-security.xml</param-value>
  </context-param>
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!-- spring安全启动   -->
  <!-- spring security的安全机制是保护在web最外层的安全框架,所以你的任何访问都要经过spring security 投票机制授权才可以访问的,否则不允许访问。只有登陆用户才可以访问。 -->
  <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>
   
  <!-- springmvc拦截器 -->
 <servlet>
     <servlet-name>SpringMVC</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
 </servlet>
 <!-- url-pattern配置为/,不带文件后缀,会造成其它静态文件(js,css等)不能访问。如配为*.do,则不影响静态文件的访问 -->
 <servlet-mapping>
     <servlet-name>SpringMVC</servlet-name>
     <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

3、创建SpringMVC-servlet.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-4.1.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-4.1.xsd
  http://www.springframework.org/schema/mvc
  http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
  
    <!-- 实现注解 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
    <context:component-scan base-package="com.demo.controller" />
    <!-- 如果当前路径是/ 则重定向到login -->
     <mvc:view-controller path="/" view-name="login" />
     <!-- Spring MVC使用ViewResolver来根据controller中返回的view名关联到具体的View对象。使用View对象来渲染返回值以生成最终的视图, -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

4、创建applicationContext-security.xml配置文件

<?xml version="1.0" encoding="UTF-8"?> 
<b:beans xmlns="http://www.springframework.org/schema/security" 
    xmlns:b="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-3.2.xsd 
                        http://www.springframework.org/schema/security 
                        http://www.springframework.org/schema/security/spring-security-3.2.xsd">
                        
    <b:bean id="csrfSecurityRequestMatcher" class="com.demo.security.CsrfSecurityRequestMatcher"></b:bean>
    
    <!-- 静态资源,不用权限,配置如下 -->
    <!-- <http pattern="/resources/**" security="none"/>-->
    
    <!-- 开启默认拦截器 -->
    <http auto-config='true' use-expressions="true"><!-- use-expressions="true" -->
        <!-- <headers>
            <frame-options disabled="true" />
        </headers> -->
        
        <csrf request-matcher-ref="csrfSecurityRequestMatcher" />
        <intercept-url pattern="/login.jsp*" access="permitAll" />
        <intercept-url pattern="/user/common/**" access="hasRole('ROLE_USER')" /><!-- hasRole('ROLE_USER')-->
        <intercept-url pattern="/**" access="permitAll" />
        
        <!-- 允许访问的url(security默认登录页面) -->
        <!-- <intercept-url pattern="/login.jsp*" access="ROLE_USER" /> --><!-- access="hasRole(ROLE_USER)"  -->
        
        <!-- 自定义登陆页面 -->
        <form-login login-page="/login.jsp" default-target-url="/login.jsp" authentication-failure-url="/login.jsp?error=true"/>
        <logout logout-success-url="/login.jsp" />
        <!-- <session-management invalid-session-url="/view/sessionOutTime.jsp"> -->
      <!-- 单点登陆,这个会导致前一个登陆失效 error-if-maximum-exceeded 阻止第二次登陆 -->
              <!-- <concurrency-control max-sessions="1" error-if-maximum-exceeded="true"></concurrency-control>
        <session-management> -->
    </http>
    <b:bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <!-- <property name="basename" value="message" /> -->
  </b:bean>
  <global-method-security
    jsr250-annotations="enabled" secured-annotations="enabled">
  </global-method-security>
    <!-- 权限管理者 -->
    <authentication-manager>
        <!-- 可提供登录访问的用户 -->
        <authentication-provider> 
            <user-service>
                <user name="cesi" password="ceshi" authorities="ROLE_USER, ROLE_ADMIN" /> 
                <user name="security" password="security" authorities="ROLE_USER" /> 
            </user-service>
        </authentication-provider> 
    </authentication-manager>
    
</b:beans>

5、创建登录controller

package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {
    
    @RequestMapping("/login")
    public ModelAndView login(String username, String password){
        if(username.equals("username") && password.equals("password")){
            System.out.println(username+"登陆成功!");
            return new ModelAndView("view/loginSuccess","username",username);
        }else{
            return new ModelAndView("view/loginError","username",username);
        }
    }
    
    @RequestMapping("/list")
    public ModelAndView list(String username){
        if(username!=null && !"".equals(username)){
            return new ModelAndView("view/list","username",username);
        }else{
            return new ModelAndView("view/loginSuccess","username",username);
        }
        
    }
    
    @RequestMapping("/logout")
    public ModelAndView logout(){
        
        return null;
        
    }
    
}
 

 

6、创建CsrfSecurityRequestMatcher.java、此时HttpServletRequest会报编译错误(HttpServletRequest cannot be resolved to a type)、右击项目->Build Path ->Configure Build Path ->Libraries ->Add Library ->Server Runtime ->next (选择tomcat8.0)->finish

package com.demo.security;

import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

public class CsrfSecurityRequestMatcher implements RequestMatcher{

    /*自定义不需要拦截的请求方式*/
    private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
    /*有rest服务时用*/
    private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("^/rest/.*", null);
 
    @Override
    public boolean matches(HttpServletRequest request) {
        if(allowedMethods.matcher(request.getMethod()).matches()){
            return false;
        }
        return !unprotectedMatcher.matches(request);
    }
}
 

 

7、WebContent下创建login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Spring 4.1 MVC demo</title>
</head>
<body>
    <!-- <form action="login" method="post">
        username:<input type="text" name="username"><br /> 
        Password:<input type="password" name="password"><br /> 
        <input type="submit" value="登陆">
    </form> -->
    <form id="login_form" action="login" method="post">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <div class="login_frame" style="position: relative";>
            <div class="login_gl" style="margin-top: 35px;">
                <span class="login_wz">登录</span>
            </div>

            <div class="login_user">
                usermame:<input id="username" name="username" type="text"
                    placeholder="" value=""
                    style="width: 10%; height: 32px; border-style: 1xp; font-size: 16px; color: #959595;" />
            </div>

            <div class="login_user">
                password:<input id="password" name="password" type="password"
                    placeholder="" value=""
                    style="width: 10%; height: 32px; border-style: 1xp; font-size: 16px; color: #959595;" />
            </div>
            
            <!-- <div id="login_btn" class="login_log">
                <span style="font-size: 16px;">submit</span>
            </div> -->
            
            <input type="submit" value="submit">
            
        </div>
    </form>

</body>
</html>

8、WebContent下创建view文件夹、创建

1)loginSuccess.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%-- <font color="green">${username } </font> --%>
    <form action="list" method="post">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <div class="login_user">
                按用户名查询:<input id="username" name="username" />
        </div>
        <input type="submit" value="submit">
    </form>
</body>
</html>

2)loginError.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <font color="red">Sorry</font>,没有${username }这个用户!
    <br />
    <a href="login.jsp">请重新登录!</a>

</body>
</html>

3)list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<font color="green">${username}</font>
</body>
</html>

9、项目结构

 

登录google浏览器登录F12模式->Network看token值、

登录成功查看用户列表 token

附源码:

https://download.csdn.net/download/diaofeiyang/10796342

链接:https://pan.baidu.com/s/10YUmUSyaolILgAOGIuwfVA 
提取码:rk2o 

均可下载

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是 Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表的实战代码: 1. 添加依赖 在 `pom.xml` 文件中添加以下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingsphere</groupId> <artifactId>sharding-jdbc-core</artifactId> <version>4.1.1</version> </dependency> <!-- Mybatis-Plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> <!-- MySQL 驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> </dependencies> ``` 2. 配置数据源 在 `application.yml` 文件中配置数据源: ```yaml spring: datasource: # 主库 master: url: jdbc:mysql://localhost:3306/db_master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # 从库 slave: url: jdbc:mysql://localhost:3306/db_slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` 3. 配置 Sharding-JDBC 在 `application.yml` 文件中配置 Sharding-JDBC: ```yaml spring: shardingsphere: datasource: names: master, slave # 数据源名称 master: type: com.zaxxer.hikari.HikariDataSource slave: type: com.zaxxer.hikari.HikariDataSource config: sharding: tables: user: actualDataNodes: master.user_$->{0..1} # 分表规则,user_0 和 user_1 表 tableStrategy: inline: shardingColumn: id algorithmExpression: user_$->{id % 2} # 分表规则,根据 id 取模 databaseStrategy: inline: shardingColumn: id algorithmExpression: master # 分库规则,根据 id 取模 bindingTables: - user # 绑定表,即需要进行分库分表的表 ``` 4. 配置 Mybatis-Plus 在 `application.yml` 文件中配置 Mybatis-Plus: ```yaml mybatis-plus: configuration: map-underscore-to-camel-case: true # 下划线转驼峰 ``` 5. 编写实体类 创建 `User` 实体类,用于映射数据库中的 `user` 表: ```java @Data public class User { private Long id; private String name; private Integer age; } ``` 6. 编写 Mapper 接口 创建 `UserMapper` 接口,用于定义操作 `user` 表的方法: ```java @Mapper public interface UserMapper extends BaseMapper<User> { } ``` 7. 编写 Service 类 创建 `UserService` 类,用于调用 `UserMapper` 接口中的方法: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User getById(Long id) { return userMapper.selectById(id); } public boolean save(User user) { return userMapper.insert(user) > 0; } public boolean updateById(User user) { return userMapper.updateById(user) > 0; } public boolean removeById(Long id) { return userMapper.deleteById(id) > 0; } } ``` 8. 测试 在 `UserController` 类中进行测试: ```java @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/user") public User getUser(Long id) { return userService.getById(id); } @PostMapping("/user") public boolean addUser(@RequestBody User user) { return userService.save(user); } @PutMapping("/user") public boolean updateUser(@RequestBody User user) { return userService.updateById(user); } @DeleteMapping("/user") public boolean removeUser(Long id) { return userService.removeById(id); } } ``` 启动应用程序,访问 `http://localhost:8080/user?id=1` 可以得到 `id` 为 1 的用户信息。访问 `http://localhost:8080/user` 并传入用户信息,可以添加用户。访问 `http://localhost:8080/user` 并传入更新后的用户信息,可以更新用户信息。访问 `http://localhost:8080/user?id=1` 并使用 DELETE 方法,可以删除用户。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值