springboot
@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() { } } }
girl.name=whe
girl.age=20
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 + '}'; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
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
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; } }
4 repository interface
package com.example.demo.controller; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
8 redis usage
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> </dependency>
# 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
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; } }
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; } } }
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; } }
public interface UserRepository extends JpaRepository<User, Long> { }
@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); // ... }
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);
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); }
@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);
public interface HotelSummary { City getCity(); String getName(); Double getAverageRating(); default Integer getAverageRatingRounded() { return getAverageRating() == null ? null : (int) Math.round(getAverageRating()); } }
@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);
Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name")); for(HotelSummary summay:hotels){ System.out.println("Name" +summay.getName()); }
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency>
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
@SpringBootApplication @MapperScan("com.neo.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
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); }
@RestController public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("hello") public String hello() { System.out.println(userMapper.getUserById(2L)); return "ss"; } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency>
@SpringBootApplication @EnableScheduling public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@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())); } }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
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 //以谁来发送邮件
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); } }
@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); }
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(); } }
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); }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<!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>
@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"; }
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 # 最大支持请求大小
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
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
public class FastDFSFile { private String name; private byte[] content; private String ext; private String md5; private String author; //省略getter、setter
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; }
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"; }
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
@RunWith(SpringRunner.class)
@SpringBootTest
@RunWith(SpringRunner.class) @SpringBootTest public class TestHello { @Test public void testHello() { System.out.println("hllo"); } }
<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>
- 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>
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.
4 Login authentication and authorization implementation
5 write the controller class
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
spring.devtools.restart.additional-paths=src/main/java