4.0.0
com.bobo
SpringBootDemo01
1.0-SNAPSHOT
spring-boot-starter-parent
org.springframework.boot
2.3.8.RELEASE
org.springframework.boot
spring-boot-starter-web
package com.bobo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBoot项目的启动类
*/
@SpringBootApplication
public class AppStart {
/**
* 程序启动的入口
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(AppStart.class,args);
}
}
package com.bobo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/*@Controller
@ResponseBody*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("hello ...);
return "Hello ...";
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
// 以上四个是JAVA中提供的元注解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
package com.bobo;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
/**
* @SpringBootApplication 组合注解
* @ComponentScan 可以直接扫描路径
* 如果没有指定要扫描的特定的路径,
* 那么默认的是会把当前注解所在的类的包及其子包作为扫描路径
*/
@SpringBootApplication
public class SpringBootDemo03Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SpringBootDemo03Application.class);
app.setBannerMode(Banner.Mode.OFF); // 关闭掉Banner
app.run(args);
}
}
server.port=8082
server.servlet.context-path=/springboot
# 默认属性修改
server.port=8082
server.servlet.context-path=/springboot
# 自定义属性
user.userName=admin
user.realName=波波
user.address=湖南长沙
package com.bobo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/*@Controller
@ResponseBody*/
@RestController
public class HelloController {
@Value(value = "${user.userName}")
private String userName;
@Value(value = "${user.realName}")
private String realName;
@Value(value = "${user.address}")
private String address;
@RequestMapping("/hello")
public String hello(){
System.out.println("hello ..."+ userName + " " + realName + " " + address);
return "Hello ...";
}
}
user.hello.username=a
user.hello.password=123
user.hello.address=cs
user.hello.age=1
user:
hello:
username:a
password:123
address:cs
age:1
# 日志配置
#logging.file.path=d:/tools/log
logging.file.name=d:/tools/log/log.log
logging.level.org.springframework.web=DEBUG
${LOG_HOME}/%d{yyyyMMdd}/${APP_NAME}.log
15
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
utf8
100MB
user.host=192.168.100.120
user.host=192.168.111.123
## 设置自定义的路径
spring.mvc.static-path-pattern=/**
## 覆盖掉默认的配置录
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,class path:/sfile/
package com.bobo.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name="firstServlet",urlPatterns = "/first")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("--firstServlet -- doGet 方法");
PrintWriter writer = resp.getWriter();
writer.write("success");
writer.flush();
writer.close();
}
}
@SpringBootApplication
// 在SpringBoot项目启动的时候会扫描 @WebServlet注解
@ServletComponentScan
public class SpringbootDemo06Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo06Application.class, args);
}
}
package com.bobo.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SecondServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("--secondServlet -- doGet 方法");
PrintWriter writer = resp.getWriter();
writer.write("success");
writer.flush();
writer.close();
}
}
@SpringBootApplication
// 在SpringBoot项目启动的时候会扫描 @WebServlet注解
@ServletComponentScan
public class SpringbootDemo06Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo06Application.class, args);
}
@Bean
public ServletRegistrationBean servletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new SecondServlet());
bean.addUrlMappings("/second");
return bean;
}
}
@WebFilter(urlPatterns = "/first")
public class FirstFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("FirstFilter before");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("FirstFilter end");
}
}
package com.bobo.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
public class SecondFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("SecondFilter before");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("SecondFilter end");
}
}
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFilter());
bean.addUrlPatterns("/second");
return bean;
}
package com.bobo.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FirstListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("FirstListener ... 初始化");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("FirstListener ... 销毁");
}
}
package com.bobo.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
public class SecondListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("SecondListener ... 初始化");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("SecondListener ... 销毁");
}
}
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
return new ServletListenerRegistrationBean(new SecondListener());
}
用户管理
文件上传案例:
package com.bobo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
@RequestMapping("/user")
public class UserContoller {
@RequestMapping("/upload")
public String fileUpload(String username, MultipartFile upload) throws IOException {
System.out.println(username + " " + upload.getOriginalFilename());
upload.transferTo(new File("d:/tools/",upload.getOriginalFilename()));
return "success";
}
}
server.port=8082
spring.servlet.multipart.enabled=true
# 设置单个文件上传的大小
spring.servlet.multipart.max-file-size=20MB
# 设置一次请求上传文件的总的大小
spring.servlet.multipart.max-request-size=200MB
org.springframework.boot
spring-boot-starter-freemarker
spring.freemarker.suffix=.ftl
Freemaker
Hello Freemark ...
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/query")
public String query(){
System.out.println("query ....");
return "user";
}
}
/**
* 基本数据类型
* 自定义数据类型
* 数据容器
* @param model
* @return
*/
@RequestMapping("/query")
public String query(Model model){
System.out.println("query ....");
model.addAttribute("userName","波波老师");
model.addAttribute("age",18);
model.addAttribute("address","湖南长沙");
model.addAttribute("flag",true);
model.addAttribute("birth",new Date());
return "user";
}
Freemaker
Hello Freemark ...
${userName}
${age}
Freemaker
Hello Freemark ...
${userName}
${age}
${address}
${flag?string("真","假")}
Freemaker
Hello Freemark ...
${userName}
${age}
${address}
${flag?string("真","假")}
${birth}
Freemaker
Hello Freemark ...
${userName}
${age}
${address}
${flag?string("真","假")}
${birth?string("yyyy-MM-dd")}
Freemaker
Hello Freemark ...
${userName}
${age}
${address}
${flag?string("真","假")}
${birth?string("yyyy-MM-dd")}
<#-- 注释符 -->
<#assign x=3.1415>
<#assign y=6>
x=${x}
y=${y}
#{x;M2}
#{x;m2}
#{y;M2}
#{y;m2}
<#assign hello="hello freemarker" >
<#-- 字符串拼接 -->
HELLO-${hello}
<#-- EL表达式中的常量表示 -->
${'HELLO|'+hello}
<#-- 常量中使用数据 -->
${'HELLO*${hello}'}
${userName}----${hello}
${userName+'-->' + hello}
${hello}
${hello[1]}
${hello[4]}
${hello[1..6]}
${hello[3..]}
@RequestMapping("/query1")
public String query1(Model model){
User user = new User(666,"admin","123456");
model.addAttribute("user",user);
return "user1";
}
Freemaker
<#-- 自定义对象 -->
${user.id}
--> <#--${user[id]}
-->
${user.userName}
-->${user['userName']}
${user.password}
@RequestMapping("/query1")
public String query1(Model model){
User user = new User(666,"admin","123456");
model.addAttribute("user",user);
Map map = new HashMap<>();
map.put("user",user);
List list = Arrays.asList("张三","李四","王五");
List list1 = Arrays.asList("1111","2222","3333");
model.addAttribute("list",list);
model.addAttribute("list1",list1);
model.addAttribute("map",map);
return "user1";
}
加法: +
减法: -
乘法: *
除法: /
求模 (求余): %
Freemaker
算术运算符:
${99+100*30}
${99/7}
${(99/7)?int}
${55%3}
逻辑 或: ||
逻辑 与: &&
逻辑 非: !
Freemaker
算术运算符:
${99+100*30}
${99/7}
${(99/7)?int}
${55%3}
内建函数:
<#assign hello="Hello FreeMarker">
<#assign page="HELLO">
${hello}
${page}
${page?html}
${hello?upper_case}
${hello?lower_case}
${now?date}
${now?datetime}
${now?time}
Freemaker
算术运算符:
${99+100*30}
${99/7}
${(99/7)?int}
${55%3}
内建函数:
<#assign hello="Hello FreeMarker">
<#assign page="HELLO">
${hello}
${page}
${page?html}
${hello?upper_case}
${hello?lower_case}
${now?date}
${now?datetime}
${now?time}
<#assign age = 18 >
<#if age == 18>
等于18
<#elseif age gt 18 >
大于18
<#else >
小于18
#if>
null的判断:
<#assign mypage="a">
<#-- ?? 检测值是否存在 -->
<#if mypage??>
mypage存在
<#else >
mypage不存在
#if>
<#assign i=3>
<#switch i>
<#case 1>
ok
<#break >
<#case 2>
ok2
<#break >
<#case 3>
ok3
<#break >
<#default >
ok4
#switch>
<#list list as obj>
<#if obj=='李四'>
<#break >
#if>
${obj}
#list>
<#assign aaa=555>
<#-- !的使用-->
${aaa!"666"}
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.9.RELEASE
com.bobo
springboot-demo09
0.0.1-SNAPSHOT
springboot-demo09
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-freemarker
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
com.alibaba
druid
1.0.14
org.springframework.boot
spring-boot-maven-plugin
server.port=8082
# 配置JDBC的相关信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?
characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 配置连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 配置MyBatis的package 设置别名
mybatis.type-aliases-package=com.bobo.pojo
package com.bobo.pojo;
public class User {
private String user_id ;
private String user_name ;
private String real_name ;
private String password ;
private String email ;
private String phone ;
private String u1 ;
private String u2 ;
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getReal_name() {
return real_name;
}
public void setReal_name(String real_name) {
this.real_name = real_name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getU1() {
return u1;
}
public void setU1(String u1) {
this.u1 = u1;
}
public String getU2() {
return u2;
}
public void setU2(String u2) {
this.u2 = u2;
}
}
package com.bobo.mapper;
import com.bobo.pojo.User;
import java.util.List;
public interface UserMapper {
List query();
}
package com.bobo.service;
import com.bobo.pojo.User;
import java.util.List;
public interface IUserService {
List query();
}
package com.bobo.service.impl;
import com.bobo.mapper.UserMapper;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper mapper;
@Override
public List query() {
return mapper.query();
}
}
package com.bobo.controller;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService service;
@RequestMapping("/query")
public String query(Model model){
List list = service.query();
model.addAttribute("list",list);
return "/user";
}
}
用户管理
用户管理
编号
账号
姓名
邮箱
电话
操作
<#list list as user>
${user.user_id}
${user.user_name}
${user.real_name!""}
${user.email!""}
${user.phone!""}
...
#list>
用户管理
用户管理
用户管理
用户管理
用户管理
用户管理
添加用户
编号
账号
姓名
邮箱
电话
操作
<#list list as user>
${user.user_id}
${user.user_name}
${user.real_name!""}
${user.email!""}
${user.phone!""}
更新
删除
#list>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.9.RELEASE
com.bobo
springboot-demo10
0.0.1-SNAPSHOT
springboot-demo10
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
Thymeleaf介绍
Hello Thymeleaf
@Controller
public class UserController {
@RequestMapping("/hello")
public String hello(){
System.out.println("hello ....");
return "/user";
}
}
@RequestMapping("/hello")
public String hello(Model model){
System.out.println("hello ....");
model.addAttribute("hello","Hello Thymeleaf");
model.addAttribute("msg","hahaha");
model.addAttribute("now",new Date());
model.addAttribute("flag",true);
model.addAttribute("age",18);
return "/user";
}
Thymeleaf介绍
Hello Thymeleaf
th:value的使用
Thymeleaf介绍
string类型介绍
hello:
hello是否为空:
hello字符串是否包含"th":
hello字符串是否包含"Th":
hello以H开头:
hello以a开头:
hello以H结尾:
hello以a结尾:
hello的长度:
hello都大写:
hello都小写:
日期时间处理
时间:
时间:
时间:
时间:
时间:
年份:
月份:
日期:
本周的第几天:
小时:
Thymeleaf介绍
条件判断
if语句
男
女
or的使用11
or的使用12
and的使用21
and的使用22
not的使用11
not的使用22
17岁
18岁
19岁
其他...
Thymeleaf介绍
循环判断
@RequestMapping("/hello4")
public String hello4(HttpServletRequest request){
request.setAttribute("req","request msg ...");
request.getSession().setAttribute("sess","session msg ....");
request.getServletContext().setAttribute("app","application msg ....");
return "/user4";
}
Thymeleaf介绍
域对象使用
request:
session:
servletContext:
Thymeleaf介绍
URL使用
百度
百度
相对路径
相对于服务器的根
相对路径--参数传递
RestFul支持
Title
用户管理
添加用户
编号
账号
姓名
邮箱
电话
操作
更新
删除
Title
org.springframework.boot
spring-boot-devtools
Title
系统出错,请联系管理员....
package com.bobo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UserController {
@RequestMapping("/show1")
public String showInfo1(){
String name = null;
// 模拟 空指针异常
name.length();
return "index";
}
@RequestMapping("/show2")
public String showInfo2(){
int a = 1/0; // 默认算术异常
return "index";
}
@ExceptionHandler(value = {NullPointerException.class})
public ModelAndView nullPointerExceptionHandler(Exception e){
ModelAndView mm = new ModelAndView();
mm.addObject("error",e.toString());
mm.setViewName("error1");
return mm;
}
@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView arithmeticException(Exception e){
ModelAndView mm = new ModelAndView();
mm.addObject("error",e.toString());
mm.setViewName("error2");
return mm;
}
}
Title
系统出错,请联系管理员....nullPointerExceptionHandler
Title
系统出错,请联系管理员....arithmeticException
package com.bobo.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
// @ControllerAdvice
public class GlobalException {
//@ExceptionHandler(value = {NullPointerException.class})
public ModelAndView nullPointerExceptionHandler(Exception e){
ModelAndView mm = new ModelAndView();
mm.addObject("error",e.toString());
mm.setViewName("error1");
return mm;
}
//@ExceptionHandler(value = {ArithmeticException.class})
public ModelAndView arithmeticException(Exception e){
ModelAndView mm = new ModelAndView();
mm.addObject("error",e.toString());
mm.setViewName("error2");
return mm;
}
}
package com.bobo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UserController {
@RequestMapping("/show1")
public String showInfo1(){
String name = null;
// 模拟 空指针异常
name.length();
return "index";
}
@RequestMapping("/show2")
public String showInfo2(){
int a = 1/0; // 默认算术异常
return "index";
}
}
package com.bobo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import java.util.Properties;
@SpringBootApplication
public class SpringbootDemo11Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemo11Application.class, args);
}
/**
* 通过SimpleMappingExceptionResolver 设置 特定异常和 处理器的映射关系
* @return
*/
// @Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.put("java.lang.NullPointerException","error1");
properties.put("java.lang.ArithmeticException","error2");
resolver.setExceptionMappings(properties);
return resolver;
}
}
package com.bobo.exception;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MyHandleExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mm = new ModelAndView();
if(e instanceof NullPointerException){
mm.setViewName("error1");
}else if(e instanceof ArithmeticException){
mm.setViewName("error2");
}else{
mm.setViewName("error");
}
return mm;
}
}
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
package com.bobo.service.impl;
import com.bobo.service.IUserService;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Override
public List query() {
return Arrays.asList("张三","李四","王五");
}
}
package com.bobo;
import com.bobo.service.IUserService;
import net.bytebuddy.asm.Advice;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootDemo12ApplicationTests {
@Autowired
private IUserService service;
@Test
void contextLoads() {
System.out.println("---->" + service.query());
}
@BeforeEach
void before(){
System.out.println("before ...");
}
@AfterEach
void after(){
System.out.println("after ...");
}
}
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
mysql
mysql-connector-java
com.alibaba
druid
1.1.8
org.springframework.boot
spring-boot-devtools
server.port=8082
# 配置JDBC的相关信息
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/logistics?
characterEncoding=utf-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
# 配置连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 配置MyBatis的package 设置别名
mybatis.type-aliases-package=com.bobo.pojo
# 指定映射文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
package com.bobo.service;
import com.bobo.pojo.User;
import java.util.List;
public interface IUserService {
public User login(String userName);
public List query(User user);
}
package com.bobo.service.impl;
import com.bobo.mapper.UserMapper;
import com.bobo.pojo.User;
import com.bobo.pojo.UserExample;
import com.bobo.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private UserMapper mapper;
@Override
public User login(String userName) {
User user = new User();
user.setUserName(userName);
List list = this.query(user);
if(list != null && list.size() == 1){
return list.get(0);
}
return null;
}
@Override
public List query(User user) {
UserExample example = new UserExample();
UserExample.Criteria criteria = example.createCriteria();
if(user != null){
if(!"".equals(user.getUserName()) && user.getUserName() != null){
criteria.andUserNameEqualTo(user.getUserName());
}
}
return mapper.selectByExample(example);
}
}
org.apache.shiro
shiro-spring
1.3.2
package com.bobo.realm;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class MyRealm extends AuthorizingRealm {
@Autowired
private IUserService service;
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
package com.bobo.config;
import com.bobo.realm.MyRealm;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class ShiroConfig {
/**
* 配置凭证匹配器
* @return
*/
@Bean
public HashedCredentialsMatcher hashedCredentialsMatcher(){
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
matcher.setHashAlgorithmName("md5");
matcher.setHashIterations(1024);
return matcher;
}
/**
* 注册自定义的Realm
* @param hashedCredentialsMatcher
* @return
*/
@Bean
public MyRealm myRealm(CredentialsMatcher hashedCredentialsMatcher){
MyRealm realm = new MyRealm();
realm.setCredentialsMatcher(hashedCredentialsMatcher);
return realm;
}
/**
* 注册SecurityManager对象
* @return
*/
@Bean
public SecurityManager securityManager(Realm myRealm){
DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
manager.setRealm(myRealm);
return manager;
}
/**
* 注册ShiroFilterFactoryBean
* @return
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager manager){
ShiroFilterFactoryBean filter = new ShiroFilterFactoryBean();
filter.setSecurityManager(manager);
filter.setLoginUrl("/login.do");
filter.setSuccessUrl("/success.html");
filter.setUnauthorizedUrl("/refuse.html");
// 设置过滤器
Map map = new HashMap<>();
map.put("/css/**","anon");
map.put("/img/**","anon");
map.put("/js/**","anon");
map.put("/login","anon");
map.put("/login.do","authc");
map.put("/**","authc");
filter.setFilterChainDefinitionMap(map);
return filter;
}
}
package com.bobo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
@RequestMapping("/login")
public String goLoginPage(){
return "login";
}
}
package com.bobo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/query")
public String query(){
System.out.println("----user query----");
return "user";
}
}
package com.bobo.realm;
import com.bobo.pojo.User;
import com.bobo.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;
public class MyRealm extends AuthorizingRealm {
@Autowired
private IUserService service;
/**
* 认证
* @param authenticationToken
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName = token.getUsername();
User user = new User();
user.setUserName(userName);
// 账号验证
user = service.login(userName);
if(user == null){
return null;
}
return new SimpleAuthenticationInfo(user,user.getPassword(),new SimpleByteSource(user.getU1()) ,"myRealm");
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
package com.bobo.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
public class LoginController {
@RequestMapping("/login")
public String goLoginPage(){
return "login";
}
@RequestMapping("/login.do")
public String login(HttpServletRequest request){
Object obj = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
System.out.println("认证错误的信息:" + obj);
return "/login";
}
@RequestMapping("/logout")
public String logout(){
SecurityUtils.getSubject().logout();
return "/login";
}
}
Title
登录页面
/**
* 开启对Shiro授权注解的支持
* @return
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
/**
* 授权
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
User user = (User) principalCollection.getPrimaryPrincipal();
System.out.println("获取授权的账号:" + user.getUserName());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRole("role1");
return info;
}
org.springframework
spring-aspects