前言

整合spring,mybatis,springMVC

初始化项目

引入spring依赖

  1. <properties>
  2. <!--设置编译版本-->
  3. <maven.compiler.source>1.8</maven.compiler.source>
  4. <maven.compiler.target>1.8</maven.compiler.target>
  5. <!--设置版本号-->
  6. <spring.version>5.0.2.RELEASE</spring.version>
  7. <slf4j.version>1.6.6</slf4j.version>
  8. <log4j.version>1.2.12</log4j.version>
  9. <mybatis.version>3.4.5</mybatis.version>
  10. <spring.security.version>5.0.1.RELEASE</spring.security.version>
  11. </properties>
  12. <dependencies>
  13. <!-- spring -->
  14. <dependency>
  15. <groupId>org.aspectj</groupId>
  16. <artifactId>aspectjweaver</artifactId>
  17. <version>1.6.8</version>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework</groupId>
  21. <artifactId>spring-context-support</artifactId>
  22. <version>${spring.version}</version>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-orm</artifactId>
  27. <version>${spring.version}</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-test</artifactId>
  32. <version>${spring.version}</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.springframework</groupId>
  36. <artifactId>spring-webmvc</artifactId>
  37. <version>${spring.version}</version>
  38. </dependency>
  39. <dependency>
  40. <groupId>org.springframework</groupId>
  41. <artifactId>spring-tx</artifactId>
  42. <version>${spring.version}</version>
  43. </dependency>
  44. <dependency>
  45. <groupId>junit</groupId>
  46. <artifactId>junit</artifactId>
  47. <version>4.12</version>
  48. <scope>test</scope>
  49. </dependency>
  50. <dependency>
  51. <groupId>javax.servlet</groupId>
  52. <artifactId>javax.servlet-api</artifactId>
  53. <version>3.1.0</version>
  54. <scope>provided</scope>
  55. </dependency>
  56. <dependency>
  57. <groupId>javax.servlet.jsp</groupId>
  58. <artifactId>jsp-api</artifactId>
  59. <version>2.0</version>
  60. <scope>provided</scope>
  61. </dependency>
  62. <dependency>
  63. <groupId>jstl</groupId>
  64. <artifactId>jstl</artifactId>
  65. <version>1.2</version>
  66. </dependency>
  67. <!-- log start -->
  68. <dependency>
  69. <groupId>log4j</groupId>
  70. <artifactId>log4j</artifactId>
  71. <version>${log4j.version}</version>
  72. </dependency>
  73. <dependency>
  74. <groupId>org.slf4j</groupId>
  75. <artifactId>slf4j-api</artifactId>
  76. <version>${slf4j.version}</version>
  77. </dependency>
  78. <dependency>
  79. <groupId>org.slf4j</groupId>
  80. <artifactId>slf4j-log4j12</artifactId>
  81. <version>${slf4j.version}</version>
  82. </dependency>
  83. <!-- log end -->
  84. <!--json-->
  85. <dependency>
  86. <groupId>com.alibaba</groupId>
  87. <artifactId>fastjson</artifactId>
  88. <version>1.2.28</version>
  89. </dependency>
  90. </dependencies>
  91. <build>
  92. <pluginManagement>
  93. <plugins>
  94. <plugin>
  95. <groupId>org.apache.maven.plugins</groupId>
  96. <artifactId>maven-compiler-plugin</artifactId>
  97. <version>3.2</version>
  98. <configuration>
  99. <source>1.8</source>
  100. <target>1.8</target>
  101. <encoding>UTF-8</encoding>
  102. <showWarnings>true</showWarnings>
  103. </configuration>
  104. </plugin>
  105. </plugins>
  106. </pluginManagement>
  107. <plugins>
  108. <plugin>
  109. <groupId>org.apache.tomcat.maven</groupId>
  110. <artifactId>tomcat7-maven-plugin</artifactId>
  111. <version>2.2</version>
  112. </plugin>
  113. </plugins>
  114. </build>
  115. </project>

配置springMVC

applicationContext.xml

可以分为dao层和service层

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  7. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
  9. http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
  10. http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
  11. <!--service包扫描-->
  12. <context:component-scan base-package="com.alvin.service"></context:component-scan>
  13. </beans>

springMvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context"
  4. xmlns:mvc="http://www.springframework.org/schema/mvc"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
  8. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
  9. <!--web扫描-->
  10. <context:component-scan base-package="com.alvin.controller"></context:component-scan>
  11. <!--视图解析器-->
  12. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  13. <property name="prefix" value="/WEB-INF/jsp/"></property>
  14. <property name="suffix" value=".jsp"></property>
  15. </bean>
  16. <!--注解驱动 ali日期格式化-->
  17. <mvc:annotation-driven>
  18. <mvc:message-converters register-defaults="true">
  19. <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  20. <property name="supportedMediaTypes" value="application/json"/>
  21. <property name="features">
  22. <array>
  23. <value>WriteMapNullValue</value>
  24. <value>WriteDateUseDateFormat</value>
  25. </array>
  26. </property>
  27. </bean>
  28. </mvc:message-converters>
  29. </mvc:annotation-driven>
  30. <!--静态资源的放行-->
  31. <mvc:default-servlet-handler/>
  32. </beans>

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://java.sun.com/xml/ns/javaee"
  4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  5. id="WebApp_ID" version="3.0">
  6. <!--springMvc的核心控制器-->
  7. <servlet>
  8. <servlet-name>dispatcherServlet</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <init-param>
  11. <param-name>contextConfigLocation</param-name>
  12. <param-value>classpath:springMvc.xml</param-value>
  13. </init-param>
  14. <load-on-startup>1</load-on-startup>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>dispatcherServlet</servlet-name>
  18. <url-pattern>/</url-pattern>
  19. </servlet-mapping>
  20. <!--spring的监听器-->
  21. <listener>
  22. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  23. </listener>
  24. <context-param>
  25. <param-name>contextConfigLocation</param-name>
  26. <param-value>classpath:applicationContext.xml</param-value>
  27. </context-param>
  28. <!--字符编码的过滤器-->
  29. <filter>
  30. <filter-name>characterFilter</filter-name>
  31. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  32. <init-param>
  33. <param-name>encoding</param-name>
  34. <param-value>utf-8</param-value>
  35. </init-param>
  36. </filter>
  37. <filter-mapping>
  38. <filter-name>characterFilter</filter-name>
  39. <url-pattern>/*</url-pattern>
  40. </filter-mapping>
  41. </web-app>

数据库

引入依赖

pom.xml

  1. <!--mysql 和mybaits 驱动-->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <version>5.1.26</version>
  6. <scope>compile</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.mybatis</groupId>
  10. <artifactId>mybatis</artifactId>
  11. <version>${mybatis.version}</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.mybatis</groupId>
  15. <artifactId>mybatis-spring</artifactId>
  16. <version>1.3.0</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.alibaba</groupId>
  20. <artifactId>druid</artifactId>
  21. <version>1.0.9</version>
  22. </dependency>

dao层数据库配置

db.properties

  1. jdbc.driver = com.mysql.jdbc.Driver
  2. jdbc.url = jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
  3. jdbc.username = root
  4. jdbc.password = root

sqlMapConfig.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--开启延迟加载-->
  7. <settings>
  8. <setting name="lazyLoadingEnabled" value="true"/>
  9. <setting name="aggressiveLazyLoading" value="false"/>
  10. </settings>
  11. </configuration>

applicationContext-dao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载jdbc.properties配置文件-->
  7. <context:property-placeholder location="classpath:db.properties"/>
  8. <!--数据源-->
  9. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  10. <property name="driverClassName" value="${jdbc.driver}"></property>
  11. <property name="url" value="${jdbc.url}"></property>
  12. <property name="username" value="${jdbc.username}"></property>
  13. <property name="password" value="${jdbc.password}"></property>
  14. </bean>
  15. <!--session工厂-->
  16. <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  17. <property name="dataSource" ref="dataSource"></property>
  18. <property name="typeAliasesPackage" value="com.alvin.domain"></property>
  19. <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
  20. </bean>
  21. <!--用于扫描dao接口路径生成代理实现类-->
  22. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  23. <property name="basePackage" value="com.alvin.dao"></property>
  24. </bean>
  25. </beans>

有可能需要service.xml里面导入dao.xml

  1. <!--引入dao的配置文件-->
  2. <import resource="classpath:applicationContext-dao.xml"></import>

缓存:

一级缓存默认开启,作用范围sqlsession,相当于一个方法。

二级缓存作用范围sqlmapper,相当于一个类,一般不用。

sqlmapconfig.xml

  1. <!--全局打开二级缓存-->
  2. <setting name="cacheEnabled" value="true"/>

普通mapper.xml

  1. <!--局部打开二级缓存-->
  2. <cache/>
  3. <!--useCache="true"打开某个select缓存-->
  4. <select id="queryUserById" parameterType="int" resultType="user" useCache="true">
  5. select * from user where id=#{id}
  6. </select>

AOP

已经引入maven

注解方式

springmvc.xml里面开启

  1. <aop:aspectj-autoproxy/>

注解aop方法即可

  1. @Component
  2. @Aspect
  3. public class AopMethod {
  4. @Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
  5. private void log(){}
  6. @Before("log()")
  7. public void before() {
  8. System.out.println("前置通知");
  9. }
  10. }

xml方式

编写AOP方法

  1. import org.aspectj.lang.ProceedingJoinPoint;
  2. public class AopMethod {
  3. public void before() {
  4. System.out.println("前置通知");
  5. }
  6. public void afterReturning() {
  7. System.out.println("后置通知");
  8. }
  9. public void afterThrowing() {
  10. System.out.println("异常通知");
  11. }
  12. /**
  13. * 环绕通知需要环绕通知的前置通知执行完成后,让原有的方法执行,再执行环绕通知的后置通知
  14. */
  15. public void around(ProceedingJoinPoint joinPoint) throws Throwable {
  16. System.out.println("环绕通知-前置");
  17. //执行原来的方法
  18. joinPoint.proceed();
  19. System.out.println("环绕通知-后置");
  20. }
  21. public void after() {
  22. System.out.println("最终通知");
  23. }
  24. }

applicationContext.xml里面配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <bean id="aopmethod" class="com.itheima.aop.AopMethod"/>
  10. <aop:config>
  11. <aop:aspect ref="aopmethod">
  12. <aop:pointcut id="pointCut" expression="execution(* com.itheima.service.*.*(..))">
  13. <aop:before method="before" pointcut-ref="pointCut"/>
  14. <aop:after-returning method="afterReturning" pointcut="execution(* com.itheima.service.*.m*(..))"/>
  15. <aop:around method="around" pointcut="execution(* com.itheima.service.*.m*(..))"/>
  16. <aop:after method="after" pointcut="execution(* com.itheima.service.*.m*(..))"/>
  17. </aop:aspect>
  18. </aop:config>
  19. </beans>

事务

注解方式

开启注解:application-service.xml

  1. <tx:annotation-config/>

使用注解

  1. @Transactional(propagation = Propagation.REQUIRED)
  2. public void transMoney(String in, String out, Float money) {
  3. //查询
  4. Account accountIn = accountMapper.queryAccountByUsername(in);
  5. Account accountOut = accountMapper.queryAccountByUsername(out);
  6. //转钱
  7. accountIn.setMoney(accountIn.getMoney() + money);
  8. accountOut.setMoney(accountOut.getMoney() - money);
  9. //修改
  10. accountMapper.updateAccount(accountIn);
  11. int a = 1 / 0;
  12. accountMapper.updateAccount(accountOut);
  13. }

xml配置

  1. <!--事务管理器的配置-->
  2. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  3. <property name="dataSource" ref="dataSource"></property>
  4. </bean>
  5. <!--事务的通知-->
  6. <tx:advice id="txAdvice">
  7. <tx:attributes>
  8. <tx:method name="save*" propagation="REQUIRED"/>
  9. <tx:method name="update*" propagation="REQUIRED"/>
  10. <tx:method name="delete*" propagation="REQUIRED"/>
  11. <tx:method name="find*" read-only="true"/>
  12. </tx:attributes>
  13. </tx:advice>
  14. <!--事务切面的配置-->
  15. <aop:config>
  16. <aop:pointcut id="pointCut" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut>
  17. <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"></aop:advisor>
  18. </aop:config>

支持JSON

请求必须是json格式:JSON.stringify(rowData)

引入

  1. <!--json-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.28</version>
  6. </dependency>

使用

返回json

  1. public @ResponseBody Person test(@RequestBody() Person person) {
  2. return person;
  3. }

自定义状态枚举

enums/ResultEnum.java

  1. public enum ResultEnum {
  2. SUCCESS(0, "成功"),
  3. UNKOWN_ERROR(-1, "未知错误"),
  4. ;
  5. private Integer code;
  6. private String msg;
  7. ResultEnum(Integer code, String msg) {
  8. this.code = code;
  9. this.msg = msg;
  10. }
  11. public Integer getCode() {
  12. return code;
  13. }
  14. public String getMsg() {
  15. return msg;
  16. }
  17. }

自定义返回json格式

domain/Result.java

  1. import java.io.Serializable;
  2. /**
  3. * 用于封装后端返回前端数据对象
  4. * @author Mark
  5. */
  6. public class Result implements Serializable {
  7. private int code;
  8. private Object data;
  9. private String msg;
  10. public Result() {
  11. }
  12. public int getCode() {
  13. return code;
  14. }
  15. public void setCode(int code) {
  16. this.code = code;
  17. }
  18. public Object getData() {
  19. return data;
  20. }
  21. public void setData(Object data) {
  22. this.data = data;
  23. }
  24. public String getMsg() {
  25. return msg;
  26. }
  27. public void setMsg(String msg) {
  28. this.msg = msg;
  29. }
  30. }

自定义返回json工具类

ResultUtil.java

  1. public class ResultUtil {
  2. public static Result success(int code,Object object) {
  3. Result resultInfo = new Result();
  4. resultInfo.setCode(code);
  5. resultInfo.setData(object);
  6. resultInfo.setMsg(null);
  7. return resultInfo;
  8. }
  9. public static Result error(int code,String msg) {
  10. Result resultInfo = new Result();
  11. resultInfo.setCode(code);
  12. resultInfo.setData(null);
  13. resultInfo.setMsg(msg);
  14. return resultInfo;
  15. }
  16. }

分页

引入依赖

  1. <dependency>
  2. <groupId>com.github.pagehelper</groupId>
  3. <artifactId>pagehelper</artifactId>
  4. <version>5.1.2</version>
  5. </dependency>

在sessionFactory的bean配置里面添加属性

  1. <!--分页插件的拦截器-->
  2. <property name="plugins">
  3. <array>
  4. <bean class="com.github.pagehelper.PageInterceptor">
  5. <property name="properties">
  6. <props>
  7. <prop key="helperDialect">oracle</prop>
  8. <prop key="reasonable">true</prop>
  9. </props>
  10. </property>
  11. </bean>
  12. </array>
  13. </property>

service层使用

  1. public PageInfo<Orders> findAllOrder(Integer pageNum, Integer pageSize) {
  2. //开启分页插件的静态方法
  3. PageHelper.startPage(pageNum,pageSize);
  4. //返回都是拦截器处理成的继承list的page对象
  5. List<Orders> oList = dao.findAllOrder();
  6. PageInfo<Orders> pageInfo = new PageInfo<Orders>(oList);
  7. return pageInfo;
  8. }

自带PageInfo属性

  1. //当前页
  2. private int pageNum;
  3. //每页的数量
  4. private int pageSize;
  5. //当前页的数量
  6. private int size;
  7. //由于startRow和endRow不常用,这里说个具体的用法
  8. //可以在页面中"显示startRow到endRow 共size条数据"
  9. //当前页面第一个元素在数据库中的行号
  10. private int startRow;
  11. //当前页面最后一个元素在数据库中的行号
  12. private int endRow;
  13. //总记录数
  14. private long total;
  15. //总页数
  16. private int pages;
  17. //结果集
  18. private List<T> list;
  19. //前一页
  20. private int prePage;
  21. //下一页
  22. private int nextPage;
  23. //是否为第一页
  24. private boolean isFirstPage = false;
  25. //是否为最后一页
  26. private boolean isLastPage = false;
  27. //是否有前一页
  28. private boolean hasPreviousPage = false;
  29. //是否有下一页
  30. private boolean hasNextPage = false;
  31. //导航页码数
  32. private int navigatePages;
  33. //所有导航页号
  34. private int[] navigatepageNums;
  35. //导航条上的第一页
  36. private int navigateFirstPage;
  37. //导航条上的最后一页
  38. private int navigateLastPage;

处理异常

先自定义异常

  1. public class MyException extends Exception {
  2. private int code;
  3. public MyException(ResultEnum resultEnum) {
  4. super(resultEnum.getMsg());
  5. this.code = resultEnum.getCode();
  6. }
  7. public int getCode() {
  8. return code;
  9. }
  10. public void setCode(int code) {
  11. this.code = code;
  12. }
  13. }

自定义全局异常返回Json

  1. public class MyHandleExceptionResolver implements HandlerExceptionResolver {
  2. @Override
  3. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
  4. ModelAndView mv = new ModelAndView();
  5. /* 使用response返回 */
  6. response.setStatus(HttpStatus.OK.value());
  7. response.setContentType(MediaType.APPLICATION_JSON_VALUE);
  8. response.setCharacterEncoding("UTF-8");
  9. response.setHeader("Cache-Control", "no-cache, must-revalidate");
  10. Result result = null;
  11. MyException myException = null;
  12. if (ex instanceof MyException) {
  13. myException = (MyException) ex;
  14. result = ResultUtil.error(myException.getCode(), myException.getMessage());
  15. } else {
  16. result = ResultUtil.error(-1, ex.getMessage());
  17. }
  18. try {
  19. response.getWriter().write(new ObjectMapper().writeValueAsString(result));
  20. } catch (IOException e) {
  21. }
  22. return mv;
  23. }
  24. }

配置后,就会拦截(springmvc.xml)

  1. <!--全局异常处理-->
  2. <bean class="com.itheima.ex.MyHandleExceptionResolver"/>

权限控制

  1. 先引入依赖
  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-web</artifactId>
  4. <version>${spring.security.version}</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework.security</groupId>
  8. <artifactId>spring-security-config</artifactId>
  9. <version>${spring.security.version}</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.security</groupId>
  13. <artifactId>spring-security-core</artifactId>
  14. <version>${spring.security.version}</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.security</groupId>
  18. <artifactId>spring-security-taglibs</artifactId>
  19. <version>${spring.security.version}</version>
  20. </dependency>
  1. 数据库和domain类
  • 数据库 ``` — 用户表 CREATE TABLE sys_user( id int auto_increment PRIMARY KEY , username VARCHAR(50), email VARCHAR(50) , PASSWORD VARCHAR(80), phoneNum VARCHAR(20), STATUS int(1) );

— 角色表 CREATE TABLE sys_role( id int auto_increment PRIMARY KEY, roleName VARCHAR(50) , roleDesc VARCHAR(50) ) — 用户和角色中间表 CREATE TABLE sys_user_role( userId int, roleId int, PRIMARY KEY(userId,roleId), FOREIGN KEY (userId) REFERENCES sys_USER(id), FOREIGN KEY (roleId) REFERENCES sys_role(id) )

  1. - domain

public class SysUser { private Long id; private String username; private String email; private String password; private String phoneNum; private int status; private List roles; } public class Role { private Long id; private String roleName; private String roleDesc; }

  1. 3. 准备好静态页面
  2. 403.jsp<br />
  3. login.jsp<br />
  4. error.jsp
  5. 4. 配置文件
  6. > springSecurity.xml

<?xml version=”1.0” encoding=”UTF-8”?>

  1. <!--放行未登录访问的页面-->
  2. <security:http pattern="/login.jsp" security="none"></security:http>
  3. <security:http pattern="/error.jsp" security="none"></security:http>
  4. <security:http pattern="/css/**" security="none"></security:http>
  5. <security:http pattern="/img/**" security="none"></security:http>
  6. <security:http pattern="/pages/**" security="none"></security:http>
  7. <security:http pattern="/plugins/**" security="none"></security:http>
  8. <!--配置拦截器的路径规则
  9. auto-config="true" 表示使用权限框架默认的配置
  10. use-expressions="false" 关闭权限框架的表达式 spel
  11. intercept-url 拦截请求资源的路径
  12. access="ROLE_USER" 允许访问的条件 当前用户必须拥有ROLE_USER的角色才可以访问
  13. -->
  14. <security:http auto-config="true" use-expressions="true">
  15. <!--权限框架支持多种角色的登录 角色之间的关系为or 或者的关系-->
  16. <security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"></security:intercept-url>
  17. <!--自定义页面的配置节点-->
  18. <security:form-login login-page="/login.jsp"
  19. login-processing-url="/login"
  20. default-target-url="/index.jsp"
  21. authentication-failure-url="/error.jsp"></security:form-login>
  22. <!--登录成功权限不足的处理-->
  23. <security:access-denied-handler error-page="/403.jsp"></security:access-denied-handler>
  24. <!--csrf关闭跨域请求的攻击-->
  25. <security:csrf disabled="true"></security:csrf>
  26. <!--
  27. logout 退出请求的url路径 实际是页面点击按钮请求的地址
  28. logout-success-url 成功注销后 跳转的页面
  29. invalidate-session 设置session失效
  30. -->
  31. <security:logout logout-url="/logOut" logout-success-url="/login.jsp" invalidate-session="true"></security:logout>
  32. </security:http>
  33. <!--配置拦截后验证的节点-->
  34. <security:authentication-manager>
  35. <security:authentication-provider user-service-ref="userService">
  36. <!--自定义的加密工具类-->
  37. <security:password-encoder ref="pwdEncoder"></security:password-encoder>
  38. </security:authentication-provider>
  39. </security:authentication-manager>
  40. <!--配置自定义的加密工具类,这里使用自带的-->
  41. <bean id="pwdEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>
  42. <!--开启注解支持-->
  43. <security:global-method-security secured-annotations="enabled"/>

  1. > web.xml 引入filter

springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy

springSecurityFilterChain /*

  1. > web.xml 将配置文件添加到监听器中

org.springframework.web.context.ContextLoaderListener

contextConfigLocation classpath:applicationContext.xml,classpath:springSecurity.xml

  1. 5. service层中添加校验方法
  2. > 继承指定接口

public interface SysUserService extends UserDetailsService { @Override UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }

  1. > 实现接口

@Service(“userService”) public class SysUserServiceImpl implements SysUserService {

  1. @Autowired
  2. private SysUserDao userDao;
  3. @Autowired
  4. BCryptPasswordEncoder pwdEncoder;
  5. @Override
  6. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  7. //得到数据库的用户
  8. SysUser sysUser = userDao.findUserByName(username);
  9. //框架的User对象用于验证返回 用户名 密码 用户的权限集合
  10. //查询得到用户真正的角色集合返回
  11. List<Role> roles =sysUser.getRoles();
  12. List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
  13. ///如果当前用户确实拥有角色 循环添加到集合中
  14. if(roles!=null&&roles.size()>0){
  15. for (Role role : roles) {
  16. authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
  17. }
  18. }
  19. //这里可以使用User的另外一个构造函数,参数多了四个boolean类型进行精确控制。
  20. User user = new User(sysUser.getUsername(),sysUser.getPassword(),authorities);
  21. return user;
  22. }

}

  1. 6. 用户名获取
  2. > 前台获取

方式一

${ sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username }

方式二

  1. > 后台获取

// 先获取到SecurityContext对象 SecurityContext context = SecurityContextHolder.getContext(); // 获取到认证的对象 Authentication authentication = context.getAuthentication(); // 获取到登录的用户信息 User user = (User) authentication.getPrincipal(); System.out.println(user.getUsername());

  1. 7. 权限控制
  2. > jsp控制

  • 产品管理
    1. > 后台控制
    2. 先开启

    1. 再使用

    @Secured(“ROLE_ADMIN”) public class RoleController

    1. <a name="4f80b6c7"></a>
    2. # 上传和下载
    3. 先引入依赖
    4. springmvc中配置文件解析器

    1. 上传到本地服务器

    public String upload(MultipartFile uploadFile, String fileName) throws IOException { uploadFile.transferTo(new File(“D:/itheima/1.jpg”)); //返回成功页面 return “success”; }

    1. 上传到其他服务器

    修改要上传服务器tomcat的web.xml

    readonly false

    String imageUrl = “http://127.0.0.1:9090/uploads/“ //使用jersey进行上传 Client client = Client.create(); //执行上传的路径 WebResource resource = client.resource(imageUrl + fileName); //执行上传 resource.put(String.class,uploadFile.getBytes());

    1. <a name="456d29ef"></a>
    2. # 日志
    3. 加入配置文件即可
    4. > log4j.properties

    Set root category priority to INFO and its only appender to CONSOLE.

    log4j.rootCategory=INFO, CONSOLE debug info warn error fatal

    log4j.rootCategory=debug, CONSOLE, LOGFILE

    Set the enterprise logger category to FATAL and its only appender to CONSOLE.

    log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

    CONSOLE is set to be a ConsoleAppender using a PatternLayout.

    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

    LOGFILE is set to be a File appender using a PatternLayout.

    log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

    1. <a name="b4babdcc"></a>
    2. # 支持restful
    3. > 增post 删delete 查get 改put
    4. web.xml配置

    methodFilter org.springframework.web.filter.HiddenHttpMethodFilter

    methodFilter /*

    1. 前端post请求必须包含_method:put,后端代码:

    @RequestMapping(value = “person/{id}”, method = RequestMethod.PUT) @ResponseBody //返回的是普通数据 public String update(@PathVariable(“id”) int id) { System.out.println(id); return “success”; }

    1. <a name="f7ae864d"></a>
    2. # 拦截器
    3. > interceptor只能springmvc使用,filter属于servlet; interceptor只能拦截方法,filter可以拦截所有。
    4. 先自定义拦截器

    public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(“preHandle”); return true; }

    1. @Override
    2. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    3. System.out.println("posthandle");
    4. }
    5. @Override
    6. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    7. System.out.println("after");
    8. }

    }

    1. 注册即可使用
    2. > springmvc.xml

    1. <a name="bf52b411"></a>
    2. # 其他问题
    3. <a name="524136f2"></a>
    4. ## 识别前台文本日期
    5. 在domain类中添加注解

    @DateTimeFormat(pattern=”yyyy‐MM‐dd HH:mm”) private Date departureTime;

    1. <a name="8a0e3dd0"></a>
    2. ## 获取项目根路径

    参数添加:HttpServletRequest request 内部获取:request.getServletContext().getRealPath(“/“) ```