- 前言
- 初始化项目
- 数据库
- AOP
- 事务
- 支持JSON
- 分页
- 处理异常
- 权限控制
- 方式一
- 方式二
- Set root category priority to INFO and its only appender to CONSOLE.
- log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
- Set the enterprise logger category to FATAL and its only appender to CONSOLE.
- CONSOLE is set to be a ConsoleAppender using a PatternLayout.
- LOGFILE is set to be a File appender using a PatternLayout.
前言
整合spring,mybatis,springMVC
初始化项目
引入spring依赖
<properties>
<!--设置编译版本-->
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--设置版本号-->
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mybatis.version>3.4.5</mybatis.version>
<spring.security.version>5.0.1.RELEASE</spring.security.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</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-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<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>
<showWarnings>true</showWarnings>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
配置springMVC
applicationContext.xml
可以分为dao层和service层
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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:xsi="http://www.w3.org/2001/XMLSchema-instance"
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-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<!--service包扫描-->
<context:component-scan base-package="com.alvin.service"></context:component-scan>
</beans>
springMvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/context"
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-4.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
<!--web扫描-->
<context:component-scan base-package="com.alvin.controller"></context:component-scan>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--注解驱动 ali日期格式化-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json"/>
<property name="features">
<array>
<value>WriteMapNullValue</value>
<value>WriteDateUseDateFormat</value>
</array>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--静态资源的放行-->
<mvc:default-servlet-handler/>
</beans>
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--springMvc的核心控制器-->
<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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--spring的监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--字符编码的过滤器-->
<filter>
<filter-name>characterFilter</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>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
数据库
引入依赖
pom.xml
<!--mysql 和mybaits 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
dao层数据库配置
db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8
jdbc.username = root
jdbc.password = root
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>
<!--开启延迟加载-->
<settings>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
applicationContext-dao.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:context="http://www.springframework.org/schema/context"
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">
<!--加载jdbc.properties配置文件-->
<context:property-placeholder location="classpath:db.properties"/>
<!--数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--session工厂-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.alvin.domain"></property>
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!--用于扫描dao接口路径生成代理实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.alvin.dao"></property>
</bean>
</beans>
有可能需要service.xml里面导入dao.xml
<!--引入dao的配置文件-->
<import resource="classpath:applicationContext-dao.xml"></import>
缓存:
一级缓存默认开启,作用范围sqlsession,相当于一个方法。
二级缓存作用范围sqlmapper,相当于一个类,一般不用。
sqlmapconfig.xml
<!--全局打开二级缓存-->
<setting name="cacheEnabled" value="true"/>
普通mapper.xml
<!--局部打开二级缓存-->
<cache/>
<!--useCache="true"打开某个select缓存-->
<select id="queryUserById" parameterType="int" resultType="user" useCache="true">
select * from user where id=#{id}
</select>
AOP
已经引入maven
注解方式
springmvc.xml里面开启
<aop:aspectj-autoproxy/>
注解aop方法即可
@Component
@Aspect
public class AopMethod {
@Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
private void log(){}
@Before("log()")
public void before() {
System.out.println("前置通知");
}
}
xml方式
编写AOP方法
import org.aspectj.lang.ProceedingJoinPoint;
public class AopMethod {
public void before() {
System.out.println("前置通知");
}
public void afterReturning() {
System.out.println("后置通知");
}
public void afterThrowing() {
System.out.println("异常通知");
}
/**
* 环绕通知需要环绕通知的前置通知执行完成后,让原有的方法执行,再执行环绕通知的后置通知
*/
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知-前置");
//执行原来的方法
joinPoint.proceed();
System.out.println("环绕通知-后置");
}
public void after() {
System.out.println("最终通知");
}
}
applicationContext.xml里面配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="aopmethod" class="com.itheima.aop.AopMethod"/>
<aop:config>
<aop:aspect ref="aopmethod">
<aop:pointcut id="pointCut" expression="execution(* com.itheima.service.*.*(..))">
<aop:before method="before" pointcut-ref="pointCut"/>
<aop:after-returning method="afterReturning" pointcut="execution(* com.itheima.service.*.m*(..))"/>
<aop:around method="around" pointcut="execution(* com.itheima.service.*.m*(..))"/>
<aop:after method="after" pointcut="execution(* com.itheima.service.*.m*(..))"/>
</aop:aspect>
</aop:config>
</beans>
事务
注解方式
开启注解:application-service.xml
<tx:annotation-config/>
使用注解
@Transactional(propagation = Propagation.REQUIRED)
public void transMoney(String in, String out, Float money) {
//查询
Account accountIn = accountMapper.queryAccountByUsername(in);
Account accountOut = accountMapper.queryAccountByUsername(out);
//转钱
accountIn.setMoney(accountIn.getMoney() + money);
accountOut.setMoney(accountOut.getMoney() - money);
//修改
accountMapper.updateAccount(accountIn);
int a = 1 / 0;
accountMapper.updateAccount(accountOut);
}
xml配置
<!--事务管理器的配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务的通知-->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--事务切面的配置-->
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.itheima.service.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"></aop:advisor>
</aop:config>
支持JSON
请求必须是json格式:JSON.stringify(rowData)
引入
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
使用
返回json
public @ResponseBody Person test(@RequestBody() Person person) {
return person;
}
自定义状态枚举
enums/ResultEnum.java
public enum ResultEnum {
SUCCESS(0, "成功"),
UNKOWN_ERROR(-1, "未知错误"),
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
自定义返回json格式
domain/Result.java
import java.io.Serializable;
/**
* 用于封装后端返回前端数据对象
* @author Mark
*/
public class Result implements Serializable {
private int code;
private Object data;
private String msg;
public Result() {
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
自定义返回json工具类
ResultUtil.java
public class ResultUtil {
public static Result success(int code,Object object) {
Result resultInfo = new Result();
resultInfo.setCode(code);
resultInfo.setData(object);
resultInfo.setMsg(null);
return resultInfo;
}
public static Result error(int code,String msg) {
Result resultInfo = new Result();
resultInfo.setCode(code);
resultInfo.setData(null);
resultInfo.setMsg(msg);
return resultInfo;
}
}
分页
引入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
在sessionFactory的bean配置里面添加属性
<!--分页插件的拦截器-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<prop key="helperDialect">oracle</prop>
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
service层使用
public PageInfo<Orders> findAllOrder(Integer pageNum, Integer pageSize) {
//开启分页插件的静态方法
PageHelper.startPage(pageNum,pageSize);
//返回都是拦截器处理成的继承list的page对象
List<Orders> oList = dao.findAllOrder();
PageInfo<Orders> pageInfo = new PageInfo<Orders>(oList);
return pageInfo;
}
自带PageInfo属性
//当前页
private int pageNum;
//每页的数量
private int pageSize;
//当前页的数量
private int size;
//由于startRow和endRow不常用,这里说个具体的用法
//可以在页面中"显示startRow到endRow 共size条数据"
//当前页面第一个元素在数据库中的行号
private int startRow;
//当前页面最后一个元素在数据库中的行号
private int endRow;
//总记录数
private long total;
//总页数
private int pages;
//结果集
private List<T> list;
//前一页
private int prePage;
//下一页
private int nextPage;
//是否为第一页
private boolean isFirstPage = false;
//是否为最后一页
private boolean isLastPage = false;
//是否有前一页
private boolean hasPreviousPage = false;
//是否有下一页
private boolean hasNextPage = false;
//导航页码数
private int navigatePages;
//所有导航页号
private int[] navigatepageNums;
//导航条上的第一页
private int navigateFirstPage;
//导航条上的最后一页
private int navigateLastPage;
处理异常
先自定义异常
public class MyException extends Exception {
private int code;
public MyException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
自定义全局异常返回Json
public class MyHandleExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mv = new ModelAndView();
/* 使用response返回 */
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache, must-revalidate");
Result result = null;
MyException myException = null;
if (ex instanceof MyException) {
myException = (MyException) ex;
result = ResultUtil.error(myException.getCode(), myException.getMessage());
} else {
result = ResultUtil.error(-1, ex.getMessage());
}
try {
response.getWriter().write(new ObjectMapper().writeValueAsString(result));
} catch (IOException e) {
}
return mv;
}
}
配置后,就会拦截(springmvc.xml)
<!--全局异常处理-->
<bean class="com.itheima.ex.MyHandleExceptionResolver"/>
权限控制
- 先引入依赖
<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-core</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${spring.security.version}</version>
</dependency>
- 数据库和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) )
- domain类
public class SysUser {
private Long id;
private String username;
private String email;
private String password;
private String phoneNum;
private int status;
private List
3. 准备好静态页面
403.jsp<br />
login.jsp<br />
error.jsp
4. 配置文件
> springSecurity.xml
<?xml version=”1.0” encoding=”UTF-8”?>
<!--放行未登录访问的页面-->
<security:http pattern="/login.jsp" security="none"></security:http>
<security:http pattern="/error.jsp" security="none"></security:http>
<security:http pattern="/css/**" security="none"></security:http>
<security:http pattern="/img/**" security="none"></security:http>
<security:http pattern="/pages/**" security="none"></security:http>
<security:http pattern="/plugins/**" security="none"></security:http>
<!--配置拦截器的路径规则
auto-config="true" 表示使用权限框架默认的配置
use-expressions="false" 关闭权限框架的表达式 spel
intercept-url 拦截请求资源的路径
access="ROLE_USER" 允许访问的条件 当前用户必须拥有ROLE_USER的角色才可以访问
-->
<security:http auto-config="true" use-expressions="true">
<!--权限框架支持多种角色的登录 角色之间的关系为or 或者的关系-->
<security:intercept-url pattern="/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN')"></security:intercept-url>
<!--自定义页面的配置节点-->
<security:form-login login-page="/login.jsp"
login-processing-url="/login"
default-target-url="/index.jsp"
authentication-failure-url="/error.jsp"></security:form-login>
<!--登录成功权限不足的处理-->
<security:access-denied-handler error-page="/403.jsp"></security:access-denied-handler>
<!--csrf关闭跨域请求的攻击-->
<security:csrf disabled="true"></security:csrf>
<!--
logout 退出请求的url路径 实际是页面点击按钮请求的地址
logout-success-url 成功注销后 跳转的页面
invalidate-session 设置session失效
-->
<security:logout logout-url="/logOut" logout-success-url="/login.jsp" invalidate-session="true"></security:logout>
</security:http>
<!--配置拦截后验证的节点-->
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<!--自定义的加密工具类-->
<security:password-encoder ref="pwdEncoder"></security:password-encoder>
</security:authentication-provider>
</security:authentication-manager>
<!--配置自定义的加密工具类,这里使用自带的-->
<bean id="pwdEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></bean>
<!--开启注解支持-->
<security:global-method-security secured-annotations="enabled"/>
> web.xml 引入filter
> web.xml 将配置文件添加到监听器中
5. 在service层中添加校验方法
> 继承指定接口
public interface SysUserService extends UserDetailsService { @Override UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; }
> 实现接口
@Service(“userService”) public class SysUserServiceImpl implements SysUserService {
@Autowired
private SysUserDao userDao;
@Autowired
BCryptPasswordEncoder pwdEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//得到数据库的用户
SysUser sysUser = userDao.findUserByName(username);
//框架的User对象用于验证返回 用户名 密码 用户的权限集合
//查询得到用户真正的角色集合返回
List<Role> roles =sysUser.getRoles();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
///如果当前用户确实拥有角色 循环添加到集合中
if(roles!=null&&roles.size()>0){
for (Role role : roles) {
authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
}
}
//这里可以使用User的另外一个构造函数,参数多了四个boolean类型进行精确控制。
User user = new User(sysUser.getUsername(),sysUser.getPassword(),authorities);
return user;
}
}
6. 用户名获取
> 前台获取
方式一
${ sessionScope.SPRING_SECURITY_CONTEXT.authentication.principal.username }
方式二
> 后台获取
// 先获取到SecurityContext对象 SecurityContext context = SecurityContextHolder.getContext(); // 获取到认证的对象 Authentication authentication = context.getAuthentication(); // 获取到登录的用户信息 User user = (User) authentication.getPrincipal(); System.out.println(user.getUsername());
7. 权限控制
> jsp控制
> 后台控制
先开启
再使用
@Secured(“ROLE_ADMIN”) public class RoleController
<a name="4f80b6c7"></a>
# 上传和下载
先引入依赖
springmvc中配置文件解析器
上传到本地服务器
public String upload(MultipartFile uploadFile, String fileName) throws IOException { uploadFile.transferTo(new File(“D:/itheima/1.jpg”)); //返回成功页面 return “success”; }
上传到其他服务器
修改要上传服务器tomcat的web.xml
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());
<a name="456d29ef"></a>
# 日志
加入配置文件即可
> 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
<a name="b4babdcc"></a>
# 支持restful
> 增post 删delete 查get 改put
web.xml配置
前端post请求必须包含_method:put,后端代码:
@RequestMapping(value = “person/{id}”, method = RequestMethod.PUT) @ResponseBody //返回的是普通数据 public String update(@PathVariable(“id”) int id) { System.out.println(id); return “success”; }
<a name="f7ae864d"></a>
# 拦截器
> interceptor只能springmvc使用,filter属于servlet; interceptor只能拦截方法,filter可以拦截所有。
先自定义拦截器
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println(“preHandle”); return true; }
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("posthandle");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("after");
}
}
注册即可使用
> springmvc.xml
<a name="bf52b411"></a>
# 其他问题
<a name="524136f2"></a>
## 识别前台文本日期
在domain类中添加注解
@DateTimeFormat(pattern=”yyyy‐MM‐dd HH:mm”) private Date departureTime;
<a name="8a0e3dd0"></a>
## 获取项目根路径
参数添加:HttpServletRequest request 内部获取:request.getServletContext().getRealPath(“/“) ```