springboot

1 the advantages of spring boot
    simple fast and convenient  quickly set up microservice 
 
2 springboot  infrastructure directory
    src/main/java  program development and main entrance
    src/main/resources  cnfiguration file
    src/test/java   test program
 
3 web module
    spring-boot-starter-web    function  suport web development
    spring-boot-starter            function   core module, autoconfiguration support  logging  yaml
    spring-boot-starter-test    function   test module junit 
  
4 web development 
    json output   filters  property   log   
    @RestController   support  json output
 
5 custom filter 
   1  implement filter interface 
   2 add @Configuration annotations, add it to filter chain
@Configuration
public class WebConfiguration {

    @Bean
    RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }
    @Bean
    public FilterRegistrationBean testFilterRegisteration() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.addUrlPatterns("/*");
        registrationBean.addInitParameter("paramName", "paramValue");
        registrationBean.setName("MyFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }
    public class MyFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {

        }

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            System.out.println("url" + request.getRequestURI());
            filterChain.doFilter(servletRequest, servletResponse);
        }

        @Override
        public void destroy() {

        }
    }
}
View Code
 
6 custom property
   1 application.properties
girl.name=whe
girl.age=20
View Code
   2 Bean
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Girl {
    @Value("${girl.name}")
    private String name;

    @Value("${girl.age}")
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {

        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Girl{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code
 
7 jpa
   1 add jar package in maven
      <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
View Code
   2 add configuration in application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
View Code
   3 bean
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Component;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;

@Entity
public class User implements Serializable{
    private static final long SeriaVersionID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false, unique = false)
    private String name;

    @Column(nullable = false, unique = false)
    private String password;

    @Column(nullable = false)
    private Integer age;

    public User() {
    }

    public User(String name, String password, Integer age) {

        this.name = name;
        this.password = password;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }

    public static long getSeriaVersionID() {
        return SeriaVersionID;
    }
}
View Code

  4 repository interface

package com.example.demo.controller;


import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User, Long> {

}
View Code

8   redis  usage

   install redis
   1  yum install gcc-c++
   2 tar -zxvf redis-3.0.7.tar.gz -C app/
   3 cd redis-3.0.7/
   4 make   compile
   5  make PREFIX=/root/redis install     install redis
   6 cd app/redis-3.0.7/
   7 cp redis.conf /root/redis/bin/
   8  cd /root/redis/bin
   9 chmod 777 redis.conf
   10 vi redis.conf    daemonize yes
   11 ./redis-server redis.conf
   12 ps -aux | grep redis   6379
 
   1 add jar package in maven
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-redis</artifactId>  
</dependency> 
View Code
   2 add configuration in application.properties
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=  
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8  
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1  
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8  
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0  
# 连接超时时间(毫秒)
spring.redis.timeout=0  
View Code
   3 add the cache configuration class
package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisDataSource {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.pool.max-active}")
    private int maxactive;

    @Value("${spring.redis.pool.max-idle}")
    private int maxidle;

    private JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxidle);
        jedisPoolConfig.setMaxTotal(maxactive);
        return jedisPoolConfig;
    }

    private JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(jedisPoolConfig());
        factory.setHostName(host);
        factory.setPort(port);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public StringRedisSerializer stringRedisSerializer() {
        return new StringRedisSerializer();
    }

    @Bean(name = "redisTemplate")
    public <K, V> RedisTemplate<K, V> redisTemplate() {
        RedisTemplate<K, V> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(stringRedisSerializer());
        template.setValueSerializer(stringRedisSerializer());
        template.setHashKeySerializer(stringRedisSerializer());
        template.setHashValueSerializer(stringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

}
View Code
   4 create  Redis Utils Class
package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Set;

public abstract class AbstractRedisDao {

    private static final Logger log = LoggerFactory.getLogger(AbstractRedisDao.class);

    abstract RedisTemplate<String, String> getRedisTemplate();

    private ValueOperations<String, String> valOps() {
        return getRedisTemplate().opsForValue();
    }

    public void storeValue(String key, String str) {
        try {
            valOps().set(key, str);
        } catch (Exception e) {
            log.error("error when store values to redis for key: " + key, e);
        }
    }

    public Set<String> getKeys(String pattern) {
        try {
            return getRedisTemplate().keys(pattern);
        } catch (Exception e) {
            log.error("error when store zset to redis for pattern: " + pattern, e);
            return null;
        }
    }
}
View Code
package com.example.demo.controller;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
@SuppressWarnings("SpringJavaAutowiringInspection")
@Repository
public class RedisClient extends AbstractRedisDao {


    @Resource(name = "redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }
}
View Code
 
9 jpa
   jpa is Sun's offical java persistence  specification,
   Basic query  is also divided into two kinds, 
         denerate methods in advance
              1 inherites jpaRepository
public interface UserRepository extends JpaRepository<User, Long> {
}
View Code
              2 use the default method
@Test
public void testBaseQuery() throws Exception {
    User user=new User();
    userRepository.findAll();
    userRepository.findOne(1l);
    userRepository.save(user);
    userRepository.delete(user);
    userRepository.count();
    userRepository.exists(1l);
    // ...
}
View Code
         Customiize simple queries
               automatically generated according to the method name    find  read   count  get
User findByUserName(String userName);
Long deleteById(Long id);
Long countByUserName(String userName)
List<User> findByEmailLike(String email);

User findByUserNameIgnoreCase(String userName);
    
List<User> findByUserNameOrderByEmailDesc(String email);
View Code
Complex queries
      when we use pageing, union 
    pageing query    in the query method, you need to pass paraments pageable, and get the return Page
Page<User> findALL(Pageable pageable);
    
Page<User> findByUserName(String userName,Pageable pageable);
@Test
public void testPageQuery() throws Exception {
    int page=1,size=10;
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = new PageRequest(page, size, sort);
    userRepository.findALL(pageable);
    userRepository.findByUserName("testName", pageable);
}
View Code
    Custom Sql Query   use @query,  when add or delete or modify  ues @modifying      
@Modifying
@Query("update User u set u.userName = ?1 where u.id = ?2")
int modifyByIdAndUserId(String  userName, Long id);
    
@Transactional
@Modifying
@Query("delete from User where id = ?1")
void deleteByUserId(Long id);
  
@Transactional(timeout = 10)
@Query("select u from User u where u.emailAddress = ?1")
    User findByEmailAddress(String emailAddress);
View Code
     Multi-table query
    1 define a result set interface class
public interface HotelSummary {

    City getCity();

    String getName();

    Double getAverageRating();

    default Integer getAverageRatingRounded() {
        return getAverageRating() == null ? null : (int) Math.round(getAverageRating());
    }

}
View Code
    2 query method return type is set to newly created interface
@Query("select h.city as city, h.name as name, avg(r.rating) as averageRating "
        - "from Hotel h left outer join h.reviews r where h.city = ?1 group by h")
Page<HotelSummary> findByCity(City city, Pageable pageable);

@Query("select h.name as name, avg(r.rating) as averageRating "
        - "from Hotel h left outer join h.reviews r  group by h")
Page<HotelSummary> findByCity(Pageable pageable);
View Code
    3 use
Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));
for(HotelSummary summay:hotels){
        System.out.println("Name" +summay.getName());
    }
View Code

 

10 spring boot mybats
     1 add jar package in maven
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
View Code
     2 add configuration in application.properties
mybatis.type-aliases-package=com.neo.entity

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = root
View Code
     3 create mapper  and add @mapperscan in setup class  or add @mapper in mapper class
@SpringBootApplication
@MapperScan("com.neo.mapper")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
View Code
public interface UserMapper {
    
    @Select("SELECT * FROM users")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    List<UserEntity> getAll();
    
    @Select("SELECT * FROM users WHERE id = #{id}")
    @Results({
        @Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
        @Result(property = "nickName", column = "nick_name")
    })
    UserEntity getOne(Long id);

    @Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
    void insert(UserEntity user);

    @Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
    void update(UserEntity user);

    @Delete("DELETE FROM users WHERE id =#{id}")
    void delete(Long id);

}
View Code
     4 use mapper
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("hello")
    public String hello() {
        System.out.println(userMapper.getUserById(2L));
        return "ss";
    }
}
View Code

 

11 shedule task
    1 add jar package in maven
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
View Code
    2 enable timing at setup class
@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
View Code
    3 create a task 
@Component
public class Scheduler2Task {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }

}
View Code

 

12 mail service
     we need mail service when we encounter some problems like registration verification, forget the password or send marketing messages to the user,
      1 add jar package in maven
<dependency> 
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency> 
View Code
      2 add configuration in application.properties
spring.mail.host=smtp.qiye.163.com //邮箱服务器地址
spring.mail.username=xxx@oo.com //用户名
spring.mail.password=xxyyooo    //密码
spring.mail.default-encoding=UTF-8

mail.fromMail.addr=xxx@oo.com  //以谁来发送邮件
View Code
      3 write mailService 
public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){
    MimeMessage message = mailSender.createMimeMessage();

    try {
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        FileSystemResource res = new FileSystemResource(new File(rscPath));
        helper.addInline(rscId, res);

        mailSender.send(message);
        logger.info("嵌入静态资源的邮件已经发送。");
    } catch (MessagingException e) {
        logger.error("发送嵌入静态资源的邮件时发生异常!", e);
    }
}
View Code
      4  test
@Test
public void sendInlineResourceMail() {
    String rscId = "neo006";
    String content="<html><body>这是有图片的邮件:<img src=\'cid:" + rscId + "\' ></body></html>";
    String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png";

    mailService.sendInlineResourceMail("ityouknow@126.com", "主题:这是有图片的邮件", content, imgPath, rscId);
}
View Code

 

13 mail history
     mail agreement   transmisssion of one person's information to another person, so how to transfer information, we need discuss the standard
     SMTP  protcol
            simple mail tranfer protocal, it is mainly responsible for the underling mail system how to send mail from one machine to another machine
      Pop3 protocol
             post office protocol 3,  specifies how to connect a personal computer to the internet's mail servier and to download electronic protocols from e-mail.
      mail delivery process
   1 the sender edits the message on the user agent and writes the recipient's email address, 
   2 user agent generates mail base on the information edited by the sender.
   3 user agent sends mail to the sender's mail server, 
   4 sender's mail server use  smtp protocol to send this mail the recipient' s mail server
   5 when the recipient's mail server receives the mail, it place the recipient in the recipient's mail box,
   6 the recipient uses the user agent to collect the mail.
  java mail
public class SendEmail{
   public static void main(String [] args){   
      // 收件人电子邮箱
      String to = "ityouknow@gmail.com";
      // 发件人电子邮箱
      String from = "webMail@gmail.com";
      // 指定发送邮件的主机为 localhost
      String host = "localhost";
      // 获取系统属性
      Properties properties = System.getProperties();
      // 设置邮件服务器
      properties.setProperty("mail.smtp.host", host);
      // 获取默认session对象
      Session session = Session.getDefaultInstance(properties);
      try{
         // 创建默认的 MimeMessage 对象
         MimeMessage message = new MimeMessage(session);
         // Set From: 头部头字段
         message.setFrom(new InternetAddress(from));
         // Set To: 头部头字段
         message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
         // Set Subject: 头部头字段
         message.setSubject("This is the Subject Line!");
         // 设置消息体
         message.setText("This is actual message");
         // 发送消息
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
View Code
 spring mail
public void simpleSend() {
    // 构建简单邮件对象,见名知意
    SimpleMailMessage smm = new SimpleMailMessage();
    // 设定邮件参数
    smm.setFrom(mailSender.getUsername());
    smm.setTo("ityouknow@126.com");
    smm.setSubject("Hello world");
    smm.setText("Hello world via spring mail sender");
    // 发送邮件
    mailSender.send(smm);
}
View Code

 

14 upload file 
     Uploading files is one of the most commonly used scenarios on the Internet. The most typical case is uploading avatars, etc. Today there is a small case that brings you a Spring Boot upload file.
      1 add jar package in maven
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
View Code
      2 write the front page
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>
View Code
      3 write upload control class
@PostMapping("/upload") 
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {
    if (file.isEmpty()) {
        redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
        return "redirect:uploadStatus";
    }

    try {
        // Get the file and save it somewhere
        byte[] bytes = file.getBytes();
        Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
        Files.write(path, bytes);

        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded '" + file.getOriginalFilename() + "'");

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "redirect:/uploadStatus";
}
View Code

      multipartfile is spring wrapper class file, contains the file binary and file attributes and other information ,configuartion can also be configured on the properties, the basic configuration information is as follows.

spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小
View Code

 

15 fastdfs
     how to upload file to distributed file system. 
          1 add jar package in maven
<dependency>
    <groupId>org.csource</groupId>
    <artifactId>fastdfs-client-java</artifactId>
    <version>1.27-SNAPSHOT</version>
</dependency>
View Code
          2 add configuration  file in resource directory fdfs_client.conf
connect_timeout = 60
network_timeout = 60
charset = UTF-8
http.tracker_http_port = 8080
http.anti_steal_token = no
http.secret_key = 123456

tracker_server = 192.168.53.85:22122
tracker_server = 192.168.53.86:22122
View Code
          3 create fastdfsfile contains filename, content, file type, author
public class FastDFSFile {
    private String name;
    private byte[] content;
    private String ext;
    private String md5;
    private String author;
    //省略getter、setter
View Code
          4  create  fastdfs utils, upload, download, delete
static {
    try {
        String filePath = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();;
        ClientGlobal.init(filePath);
        trackerClient = new TrackerClient();
        trackerServer = trackerClient.getConnection();
        storageServer = trackerClient.getStoreStorage(trackerServer);
    } catch (Exception e) {
        logger.error("FastDFS Client Init Fail!",e);
    }
}
public static String[] upload(FastDFSFile file) {
    logger.info("File Name: " + file.getName() + "File Length:" + file.getContent().length);

    NameValuePair[] meta_list = new NameValuePair[1];
    meta_list[0] = new NameValuePair("author", file.getAuthor());

    long startTime = System.currentTimeMillis();
    String[] uploadResults = null;
    try {
        storageClient = new StorageClient(trackerServer, storageServer);
        uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
    } catch (IOException e) {
        logger.error("IO Exception when uploadind the file:" + file.getName(), e);
    } catch (Exception e) {
        logger.error("Non IO Exception when uploadind the file:" + file.getName(), e);
    }
    logger.info("upload_file time used:" + (System.currentTimeMillis() - startTime) + " ms");

    if (uploadResults == null) {
        logger.error("upload file fail, error code:" + storageClient.getErrorCode());
    }
    String groupName = uploadResults[0];
    String remoteFileName = uploadResults[1];

    logger.info("upload file successfully!!!" + "group_name:" + groupName + ", remoteFileName:" + " " + remoteFileName);
    return uploadResults;
}
View Code
          5 use
public String saveFile(MultipartFile multipartFile) throws IOException {
    String[] fileAbsolutePath={};
    String fileName=multipartFile.getOriginalFilename();
    String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
    byte[] file_buff = null;
    InputStream inputStream=multipartFile.getInputStream();
    if(inputStream!=null){
        int len1 = inputStream.available();
        file_buff = new byte[len1];
        inputStream.read(file_buff);
    }
    inputStream.close();
    FastDFSFile file = new FastDFSFile(fileName, file_buff, ext);
    try {
        fileAbsolutePath = FastDFSClient.upload(file);  //upload to fastdfs
    } catch (Exception e) {
        logger.error("upload file Exception!",e);
    }
    if (fileAbsolutePath==null) {
        logger.error("upload file failed,please upload again!");
    }
    String path=FastDFSClient.getTrackerUrl()+fileAbsolutePath[0]+ "/"+fileAbsolutePath[1];
    return path;
}
@PostMapping("/upload") //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file,
                               RedirectAttributes redirectAttributes) {
    if (file.isEmpty()) {
        redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
        return "redirect:uploadStatus";
    }
    try {
        // Get the file and save it somewhere
        String path=saveFile(file);
        redirectAttributes.addFlashAttribute("message",
                "You successfully uploaded '" + file.getOriginalFilename() + "'");
        redirectAttributes.addFlashAttribute("path",
                "file path url '" + path + "'");
    } catch (Exception e) {
        logger.error("upload file failed",e);
    }
    return "redirect:/uploadStatus";
}
View Code

 

16 test and package
      development stage
      unit test
      1   add jar package in maven
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
View Code
      2   create test class     add    @RunWith(SpringRunner.class)  @SpringBootTest
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestHello {

    @Test
    public void testHello() {
        System.out.println("hllo");
    }
}
View Code
      integration test automatic
      1   add jar package in maven
 <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <fork>true</fork>
            </configuration>
        </plugin>
</plugins>
</build>
View Code
      2  compiler project
 
17  shiro  authentication  and rights management
          At the conceptual level, the Shiro architecture contains three main ideas: Subject, SecurityManager, and Realm. The diagram below shows how these components interact with each other, which we will describe in turn below. 
  • Subject: The current user, Subject can be a person, but it can also be a third-party service, daemon account, clock daemon, or any other event that is currently interacting with the software.
  • SecurityManager: Manage all Subjects. The SecurityManager is at the core of the Shiro architecture and together with internal security components make up a safety umbrella.
  • Realms: used to verify the authority information, we realize. Realm is essentially a specific secure DAO: it encapsulates the details of the connection to the data source and gets the relevant data Shiro needs. When configuring Shiro, you must specify at least one Realm for authentication and / or authorization.
  • We need Realms Authentication and Authorization. Authentication is used to verify the user identity, Authorization is authorized access control for authorization of the operation of the user to prove that the user is allowed to carry out the current operation, such as access to a link, a resource file.

       how to use shiro

   1 add jar package in maven    write front page

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
View Code

   2 RBAC     RBAC is Role-Based Access Control, permissions are asscocited with roles, and users gain access to these roles by becoming members of the roles. this greatly simplifies the management of rights, this managerment are level intedependencies, permissions given to the role, and rloe given to the user.

  3 shiro configuration

    the shiro core is implemented vir filter, since it is generally used by filter, so we need to define a series of rules and access permissions on the URL.

Login authentication and  authorization implementation

5 write the controller class

 

18 hot deployment 
     1 add jar in maven
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
View Code
     2 add configuration
spring.devtools.restart.additional-paths=src/main/java
     3  set compline to auto compline
 
posted on 2018-02-06 15:29  wheleetcode  阅读(441)  评论(0编辑  收藏  举报