├── .gitignore ├── README.md ├── src ├── main │ ├── resources │ │ ├── mail.properties │ │ ├── student.sql │ │ ├── mapper.xml │ │ ├── application.properties │ │ └── logback-spring.xml │ └── java │ │ └── com │ │ └── wuwei │ │ ├── dao │ │ ├── Dao.java │ │ └── JDBCDao.java │ │ ├── service │ │ ├── BaseService.java │ │ └── ServiceImpl.java │ │ ├── Application.java │ │ ├── entity │ │ ├── Result.java │ │ └── Student.java │ │ ├── controller │ │ └── Controller.java │ │ └── util │ │ ├── JDBCUtils.java │ │ ├── MailSender.java │ │ └── HttpClient.java └── test │ └── java │ └── com │ └── wuwei │ └── test │ └── DatabaseConnectionTest.java ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # springboot-jdbc-sqlserver 2 | Spring Boot MVC Demo with JDBC and SqlServer 3 | -------------------------------------------------------------------------------- /src/main/resources/mail.properties: -------------------------------------------------------------------------------- 1 | from=XXX@126.com 2 | to=xxx@qq.com 3 | username=XXX 4 | password=XXXXXX 5 | host=smtp.126.com -------------------------------------------------------------------------------- /src/main/resources/student.sql: -------------------------------------------------------------------------------- 1 | exec sys.sp_readerrorlog 0, 1, 'listening'; 2 | create database student; 3 | use student; 4 | 5 | create table student( 6 | id bigint primary key identity(1,1), 7 | name NVARCHAR(30) not null, 8 | course NVARCHAR(30) not null, 9 | addtime datetime not null default current_timestamp); 10 | 11 | insert into student(name,course)values('Jack','Chinese'); 12 | insert into student(name,course)values('Tom','Computer'); -------------------------------------------------------------------------------- /src/main/java/com/wuwei/dao/Dao.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.dao; 2 | 3 | import com.wuwei.entity.Student; 4 | import java.util.List; 5 | 6 | /** 7 | * Data Access Layer 8 | * 9 | * @author Wu Wei 10 | * @date 2017-8-5 21:03:48 11 | */ 12 | public interface Dao { 13 | 14 | public int addStudent(Student student); 15 | 16 | public List findAllStudent(); 17 | 18 | public int updateStudent(Student student); 19 | 20 | public int delStudentById(long id); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/service/BaseService.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.service; 2 | 3 | import com.wuwei.entity.Result; 4 | import com.wuwei.entity.Student; 5 | 6 | /** 7 | * BaseService Layer 8 | * 9 | * @author Wu Wei 10 | * @date 2017-8-6 20:31:29 11 | */ 12 | public interface BaseService { 13 | 14 | public Result addStudent(Student student); 15 | 16 | public Result findAllStudent(); 17 | 18 | public Result updateStudent(Student student); 19 | 20 | public Result delStudentById(String id); 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/Application.java: -------------------------------------------------------------------------------- 1 | package com.wuwei; 2 | 3 | import org.mybatis.spring.annotation.MapperScan; 4 | import org.springframework.boot.SpringApplication; 5 | import org.springframework.boot.autoconfigure.SpringBootApplication; 6 | 7 | /** 8 | * SpringBoot入口程序 9 | * 10 | * @author Wu Wei 11 | * @date 2017-8-5 14:04:37 12 | */ 13 | @SpringBootApplication 14 | @MapperScan(basePackages = "com.wuwei.dao") 15 | public class Application { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(Application.class, args); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/entity/Result.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.entity; 2 | 3 | import java.io.Serializable; 4 | 5 | public class Result implements Serializable { 6 | 7 | private static final long serialVersionUID = 7086445730263059369L; 8 | 9 | private int status; 10 | private Object data; 11 | 12 | public int getStatus() { 13 | return status; 14 | } 15 | 16 | public void setStatus(int status) { 17 | this.status = status; 18 | } 19 | 20 | public Object getData() { 21 | return data; 22 | } 23 | 24 | public void setData(Object data) { 25 | this.data = data; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/resources/mapper.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | insert into student(name,course)values(#{name},#{course}) 8 | 9 | 10 | 13 | 14 | 15 | update student set name=#{name},course=#{course} where id=#{id} 16 | 17 | 18 | 19 | delete from student where id=#{id} 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # MySql Connection 2 | #spring.datasource.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8 3 | #spring.datasource.username=root 4 | #spring.datasource.password= 5 | #spring.datasource.driver-class-name=com.mysql.jdbc.Driver 6 | 7 | # SqlServer Connection 8 | spring.datasource.url=jdbc:sqlserver://localhost:1434;databaseName=student 9 | spring.datasource.username=sa 10 | spring.datasource.password=123456 11 | spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver 12 | 13 | # Connection Pool 14 | spring.datasource.max-idle=10 15 | spring.datasource.max-wait=10000 16 | spring.datasource.min-idle=5 17 | spring.datasource.initial-size=5 18 | spring.datasource.validation-query=SELECT 1 19 | spring.datasource.test-on-borrow=false 20 | spring.datasource.test-while-idle=true 21 | spring.datasource.time-between-eviction-runs-millis=18800 22 | spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0) 23 | 24 | # Embeded Tomcat 25 | server.port=8181 26 | server.contextPath=/test 27 | 28 | # Mybatis ORM 29 | mybatis.mapper-locations: classpath:mapper.xml 30 | 31 | # logging 32 | logging.level.org.springframework.web=INFO 33 | logging.file=D:\\logs\\log.log -------------------------------------------------------------------------------- /src/main/java/com/wuwei/entity/Student.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.entity; 2 | 3 | import java.io.Serializable; 4 | import java.sql.Timestamp; 5 | 6 | /** 7 | * 8 | * @author 吴维 9 | * @date 2017-8-13 13:59:32 10 | */ 11 | public class Student implements Serializable { 12 | 13 | private static final long serialVersionUID = 6973576143316146251L; 14 | 15 | private long id; 16 | private String name; 17 | private String course; 18 | private Timestamp addtime; 19 | 20 | public long getId() { 21 | return id; 22 | } 23 | 24 | public void setId(long id) { 25 | this.id = id; 26 | } 27 | 28 | public String getName() { 29 | return name; 30 | } 31 | 32 | public void setName(String name) { 33 | this.name = name; 34 | } 35 | 36 | public String getCourse() { 37 | return course; 38 | } 39 | 40 | public void setCourse(String course) { 41 | this.course = course; 42 | } 43 | 44 | public Timestamp getAddtime() { 45 | return addtime; 46 | } 47 | 48 | public void setAddtime(Timestamp addtime) { 49 | this.addtime = addtime; 50 | } 51 | 52 | @Override 53 | public String toString() { 54 | return "Student{" + "id=" + id + ", name=" + name + ", course=" + course + ", addtime=" + addtime + '}'; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/wuwei/test/DatabaseConnectionTest.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.test; 2 | 3 | import com.wuwei.entity.Student; 4 | import com.wuwei.util.JDBCUtils; 5 | import java.sql.*; 6 | import java.util.List; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | 10 | /** 11 | * 数据库连接测试 12 | * 13 | * @author Wu Wei 14 | * @date 2017-8-9 11:07:46 15 | */ 16 | public class DatabaseConnectionTest { 17 | 18 | public static void main(String[] args) { 19 | queryTest(); 20 | } 21 | 22 | public static void queryTest() { 23 | try { 24 | Connection conn = JDBCUtils.getConnection(); 25 | String sql = "select * from student where id = ?"; 26 | PreparedStatement pre = conn.prepareStatement(sql); 27 | pre.setInt(1, 1); 28 | ResultSet rs = pre.executeQuery(); 29 | //结果集转换成实体对象 30 | List list = JDBCUtils.TranverseToList(rs, Student.class); 31 | //循环遍历结果 32 | for (int i = 0; i < list.size(); i++) { 33 | Student student = (Student) list.get(i); 34 | System.out.println(student); 35 | } 36 | } catch (SQLException | InstantiationException | IllegalAccessException ex) { 37 | Logger.getLogger(DatabaseConnectionTest.class.getName()).log(Level.SEVERE, null, ex); 38 | } finally { 39 | JDBCUtils.close(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/resources/logback-spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | logback 4 | 5 | 6 | 7 | 8 | INFO 9 | 10 | 11 | %d{yyyy-MM-dd HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n 12 | 13 | 14 | 15 | 16 | ${log.path} 17 | 18 | 19 | ${log.path}-%d{yyyy-MM-dd}.%i.txt 20 | 21 | 10MB 22 | 365 23 | 10GB 24 | 25 | 26 | %date %level [%thread] %logger{36} [%file : %line] %msg%n 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/controller/Controller.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.controller; 2 | 3 | import com.wuwei.entity.Result; 4 | import com.wuwei.entity.Student; 5 | import javax.annotation.Resource; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | import com.wuwei.service.BaseService; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestParam; 12 | 13 | /** 14 | * 控制器Controller 15 | * 16 | * @author Wu Wei 17 | * @date 2017-8-8 17:53:21 18 | */ 19 | @RestController 20 | @RequestMapping("/student") 21 | public class Controller { 22 | 23 | @Resource 24 | private BaseService service; 25 | 26 | /** 27 | * 新增 28 | * 29 | * @param student 30 | * @return 31 | */ 32 | @PostMapping("/addStudent") 33 | public Result addStudent(@RequestBody Student student) { 34 | return service.addStudent(student); 35 | } 36 | 37 | /** 38 | * 查询 39 | * 40 | * @return 41 | */ 42 | @PostMapping("/findAllStudent") 43 | public Result findAllStudent() { 44 | return service.findAllStudent(); 45 | } 46 | 47 | /** 48 | * 更新 49 | * 50 | * @param student 51 | * @return 52 | */ 53 | @PostMapping("/updateStudent") 54 | public Result updateStudent(@RequestBody Student student) { 55 | return service.updateStudent(student); 56 | } 57 | 58 | /** 59 | * 删除 60 | * 61 | * @param id 62 | * @return 63 | */ 64 | @PostMapping("/delStudentById") 65 | public Result delStudentById(@RequestParam("id") String id) { 66 | return service.delStudentById(id); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/service/ServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.service; 2 | 3 | import com.wuwei.dao.Dao; 4 | import com.wuwei.entity.Result; 5 | import com.wuwei.entity.Student; 6 | import java.util.List; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | import javax.annotation.Resource; 10 | import org.springframework.stereotype.Service; 11 | 12 | /** 13 | * 14 | * @author Wu Wei 15 | * @date 2017-8-8 18:06:30 16 | */ 17 | @Service 18 | public class ServiceImpl implements BaseService { 19 | 20 | @Resource(name = "JdbcDao") 21 | private Dao dao; 22 | private static final Logger logger = Logger.getLogger(ServiceImpl.class.getName()); 23 | 24 | @Override 25 | public Result addStudent(Student student) { 26 | Result result = new Result(); 27 | try { 28 | int res = dao.addStudent(student); 29 | result.setStatus(res); 30 | } catch (Exception e) { 31 | logger.log(Level.SEVERE, null, e); 32 | } 33 | return result; 34 | } 35 | 36 | @Override 37 | public Result findAllStudent() { 38 | Result result = new Result(); 39 | try { 40 | List students = dao.findAllStudent(); 41 | result.setStatus(1); 42 | result.setData(students); 43 | } catch (Exception e) { 44 | logger.log(Level.SEVERE, null, e); 45 | } 46 | return result; 47 | } 48 | 49 | @Override 50 | public Result updateStudent(Student student) { 51 | Result result = new Result(); 52 | try { 53 | int res = dao.updateStudent(student); 54 | result.setStatus(res); 55 | } catch (Exception e) { 56 | logger.log(Level.SEVERE, null, e); 57 | } 58 | return result; 59 | } 60 | 61 | @Override 62 | public Result delStudentById(String id) { 63 | Result result = new Result(); 64 | try { 65 | int res = dao.delStudentById(Long.parseLong(id)); 66 | result.setStatus(res); 67 | } catch (Exception e) { 68 | logger.log(Level.SEVERE, null, e); 69 | } 70 | return result; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/dao/JDBCDao.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.dao; 2 | 3 | import com.wuwei.entity.Student; 4 | import com.wuwei.util.JDBCUtils; 5 | import java.sql.Connection; 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.util.List; 9 | import java.util.logging.Level; 10 | import java.util.logging.Logger; 11 | import org.springframework.stereotype.Repository; 12 | 13 | /** 14 | * 15 | * @author Wu Wei 16 | * @date 2017-8-9 17:07:18 17 | */ 18 | @Repository("JdbcDao") 19 | public class JDBCDao implements Dao { 20 | 21 | private static final Logger logger = Logger.getLogger(JDBCDao.class.getName()); 22 | private static final Connection conn = JDBCUtils.getConnection(); 23 | 24 | @Override 25 | public int addStudent(Student student) { 26 | int res = 0; 27 | String sql = "INSERT INTO student(name,course)VALUES(?,?)"; 28 | try { 29 | PreparedStatement pre = conn.prepareStatement(sql); 30 | pre.setString(1, student.getName()); 31 | pre.setString(2, student.getCourse()); 32 | res = pre.executeUpdate(); 33 | } catch (Exception ex) { 34 | logger.log(Level.SEVERE, null, ex); 35 | } 36 | return res; 37 | } 38 | 39 | @Override 40 | public List findAllStudent() { 41 | List students = null; 42 | String sql = "SELECT * FROM student"; 43 | try { 44 | PreparedStatement pre = conn.prepareStatement(sql); 45 | ResultSet rs = pre.executeQuery(); 46 | students = JDBCUtils.TranverseToList(rs, Student.class); 47 | } catch (Exception ex) { 48 | logger.log(Level.SEVERE, null, ex); 49 | } 50 | return students; 51 | } 52 | 53 | @Override 54 | public int updateStudent(Student student) { 55 | int res = 0; 56 | String sql = "UPDATE student SET name = ?,course = ? WHERE id = ?"; 57 | try { 58 | PreparedStatement pre = conn.prepareStatement(sql); 59 | pre.setString(1, student.getName()); 60 | pre.setString(2, student.getCourse()); 61 | pre.setLong(3, student.getId()); 62 | res = pre.executeUpdate(); 63 | } catch (Exception ex) { 64 | logger.log(Level.SEVERE, null, ex); 65 | } 66 | return res; 67 | } 68 | 69 | @Override 70 | public int delStudentById(long id) { 71 | int res = 0; 72 | String sql = "DELETE FROM student WHERE id = ?"; 73 | try { 74 | PreparedStatement pre = conn.prepareStatement(sql); 75 | pre.setLong(1, id); 76 | res = pre.executeUpdate(); 77 | } catch (Exception ex) { 78 | logger.log(Level.SEVERE, null, ex); 79 | } 80 | return res; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | com.wuwei 5 | SpringBoot-MVC-JDBC-SqlServer 6 | 1.0-SNAPSHOT 7 | jar 8 | 9 | org.springframework.boot 10 | spring-boot-starter-parent 11 | 1.5.6.RELEASE 12 | 13 | 14 | 15 | UTF-8 16 | 1.8 17 | 1.8 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-test 27 | test 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-web 32 | 33 | 34 | org.springframework 35 | spring-jdbc 36 | 4.3.10.RELEASE 37 | jar 38 | 39 | 40 | mysql 41 | mysql-connector-java 42 | 43 | 44 | com.microsoft.sqlserver 45 | mssql-jdbc 46 | 6.1.0.jre8 47 | 48 | 49 | org.mybatis.spring.boot 50 | mybatis-spring-boot-starter 51 | 1.3.0 52 | 53 | 54 | 55 | 56 | 57 | org.springframework.boot 58 | spring-boot-maven-plugin 59 | 60 | true 61 | 62 | 63 | 64 | 65 | SpringBoot-MVC-JDBC-SqlServer 66 | 67 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/util/JDBCUtils.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.util; 2 | 3 | import java.sql.*; 4 | import java.lang.reflect.Field; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | 10 | /** 11 | * JDBC工具类 12 | * 13 | * @author Wu Wei 14 | * @date 2017-8-9 18:33:13 15 | */ 16 | public class JDBCUtils { 17 | 18 | private static final Logger logger = Logger.getLogger(JDBCUtils.class.getName()); 19 | public static Connection connection = null; 20 | public static PreparedStatement preparedStatement = null; 21 | public static ResultSet resultSet = null; 22 | 23 | private JDBCUtils() { 24 | } 25 | 26 | /** 27 | * 获取JDBC连接 28 | * 29 | * @return 30 | */ 31 | public static Connection getConnection() { 32 | String url = "jdbc:sqlserver://localhost:1434;databaseName=student"; 33 | String username = "sa"; 34 | String password = "123456"; 35 | if (connection != null) { 36 | return connection; 37 | } 38 | try { 39 | Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance(); 40 | connection = DriverManager.getConnection(url, username, password); 41 | } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) { 42 | logger.log(Level.SEVERE, null, ex); 43 | } 44 | return connection; 45 | } 46 | 47 | /** 48 | * 关闭资源 49 | */ 50 | public static void close() { 51 | try { 52 | if (connection != null) { 53 | connection.close(); 54 | connection = null; 55 | } 56 | if (preparedStatement != null) { 57 | preparedStatement.close(); 58 | preparedStatement = null; 59 | } 60 | if (resultSet != null) { 61 | resultSet.close(); 62 | resultSet = null; 63 | } 64 | } catch (SQLException e) { 65 | logger.log(Level.SEVERE, null, e); 66 | } 67 | } 68 | 69 | /** 70 | * 将结果集转换成实体对象集合 71 | * 72 | * @param rs 73 | * @param clazz 74 | * @throws SQLException 75 | * @throws IllegalAccessException 76 | * @throws InstantiationException 77 | * @return 78 | */ 79 | public static List TranverseToList(ResultSet rs, Class clazz) throws SQLException, InstantiationException, IllegalAccessException { 80 | //结果集中列的名称和类型的信息 81 | ResultSetMetaData rsm = rs.getMetaData(); 82 | int colNumber = rsm.getColumnCount(); 83 | List list = new ArrayList<>(); 84 | Field[] fields = clazz.getDeclaredFields(); 85 | //遍历每条记录 86 | while (rs.next()) { 87 | //实例化对象 88 | Object obj = clazz.newInstance(); 89 | //取出每一个字段进行赋值 90 | for (int i = 1; i <= colNumber; i++) { 91 | Object value = rs.getObject(i); 92 | //匹配实体类中对应的属性 93 | for (Field f : fields) { 94 | if (f.getName().equals(rsm.getColumnName(i))) { 95 | boolean flag = f.isAccessible(); 96 | f.setAccessible(true); 97 | f.set(obj, value); 98 | f.setAccessible(flag); 99 | break; 100 | } 101 | } 102 | } 103 | list.add(obj); 104 | } 105 | return list; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/util/MailSender.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.util; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.IOException; 5 | import java.util.Date; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | import java.util.Properties; 9 | import java.util.logging.Logger; 10 | import javax.activation.DataHandler; 11 | import javax.activation.DataSource; 12 | import javax.activation.FileDataSource; 13 | import javax.mail.BodyPart; 14 | import javax.mail.Message; 15 | import javax.mail.MessagingException; 16 | import javax.mail.Multipart; 17 | import javax.mail.PasswordAuthentication; 18 | import javax.mail.Session; 19 | import javax.mail.Transport; 20 | import javax.mail.internet.InternetAddress; 21 | import javax.mail.internet.MimeBodyPart; 22 | import javax.mail.internet.MimeMessage; 23 | import javax.mail.internet.MimeMultipart; 24 | 25 | /** 26 | * 发送可以带附件的邮件 27 | * 28 | * @author Wu Wei 29 | * @date 2017-8-7 16:32:15 30 | */ 31 | public class MailSender { 32 | 33 | private static final String CLASSPATH = MailSender.class.getResource("/").getPath(); 34 | private static final Logger logger = Logger.getLogger(MailSender.class.getName()); 35 | 36 | public static void main(String[] args) { 37 | sendAttachmentMail("D:\\XXX.txt"); 38 | } 39 | 40 | public static void sendAttachmentMail(String filename) { 41 | Map params = readMailConfig(); 42 | if (params == null || params.isEmpty()) { 43 | return; 44 | } 45 | String from = params.get("from"); 46 | String to = params.get("to"); 47 | final String username = params.get("username"); 48 | final String password = params.get("password"); 49 | String host = params.get("host"); 50 | Properties props = new Properties(); 51 | props.put("mail.smtp.auth", "true"); 52 | props.put("mail.smtp.starttls.enable", "true"); 53 | props.put("mail.smtp.host", host); 54 | props.put("mail.smtp.port", "25"); 55 | Session session = Session.getInstance(props, new javax.mail.Authenticator() { 56 | @Override 57 | protected PasswordAuthentication getPasswordAuthentication() { 58 | return new PasswordAuthentication(username, password); 59 | } 60 | }); 61 | try { 62 | // Create a default MimeMessage object. 63 | Message message = new MimeMessage(session); 64 | // Set From: header field of the header. 65 | message.setFrom(new InternetAddress(from)); 66 | // Set To: header field of the header. 67 | message.setRecipients(Message.RecipientType.TO, 68 | InternetAddress.parse(to)); 69 | // Set Subject: header field 70 | message.setSubject("Testing Subject"); 71 | // Create the message part 72 | BodyPart messageBodyPart = new MimeBodyPart(); 73 | // Now set the actual message 74 | messageBodyPart.setText("This is message body"); 75 | // Create a multipar message 76 | Multipart multipart = new MimeMultipart(); 77 | // Set text message part 78 | multipart.addBodyPart(messageBodyPart); 79 | // Part two is attachment 80 | messageBodyPart = new MimeBodyPart(); 81 | DataSource source = new FileDataSource(filename); 82 | messageBodyPart.setDataHandler(new DataHandler(source)); 83 | messageBodyPart.setFileName(filename); 84 | multipart.addBodyPart(messageBodyPart); 85 | // Send the complete message parts 86 | message.setContent(multipart); 87 | // Set message send time 88 | message.setSentDate(new Date()); 89 | // Send message 90 | Transport.send(message); 91 | System.out.println("Send mail successfully!"); 92 | } catch (MessagingException e) { 93 | logger.info(e.getMessage()); 94 | } 95 | } 96 | 97 | /** 98 | * 读取邮件配置参数 99 | * 100 | * @return 101 | */ 102 | private static Map readMailConfig() { 103 | StringBuilder fileName = new StringBuilder(CLASSPATH); 104 | fileName.append("mail.properties"); 105 | Properties prop = new Properties(); 106 | try { 107 | prop.load(new FileInputStream(fileName.toString())); 108 | Map params = new HashMap<>(); 109 | prop.entrySet().stream().forEach(entry -> { 110 | params.put((String) entry.getKey(), (String) entry.getValue()); 111 | }); 112 | return params; 113 | } catch (IOException e) { 114 | logger.info(e.getMessage()); 115 | } 116 | return null; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/wuwei/util/HttpClient.java: -------------------------------------------------------------------------------- 1 | package com.wuwei.util; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.logging.Level; 8 | import java.util.logging.Logger; 9 | import org.apache.http.Header; 10 | import org.apache.http.HttpEntity; 11 | import org.apache.http.NameValuePair; 12 | import org.apache.http.ParseException; 13 | import org.apache.http.client.config.RequestConfig; 14 | import org.apache.http.client.entity.UrlEncodedFormEntity; 15 | import org.apache.http.client.methods.CloseableHttpResponse; 16 | import org.apache.http.client.methods.HttpGet; 17 | import org.apache.http.client.methods.HttpPost; 18 | import org.apache.http.entity.StringEntity; 19 | import org.apache.http.impl.client.CloseableHttpClient; 20 | import org.apache.http.impl.client.HttpClients; 21 | import org.apache.http.message.BasicNameValuePair; 22 | import org.apache.http.util.EntityUtils; 23 | 24 | /** 25 | * 1. 通过HttpClient实现Get方法响应 26 | * 2. 通过HttpClient实现Post方法带参数传入的响应 27 | */ 28 | public class HttpClient { 29 | 30 | private static final Logger logger = Logger.getLogger(HttpClient.class.getName()); 31 | private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build(); 32 | 33 | //定义一个HttpClient 34 | private static final CloseableHttpClient httpClient = HttpClients.createDefault(); 35 | 36 | /** 37 | * 向服务器发送get请求 38 | * 39 | * @param url 40 | * @return 41 | */ 42 | public static String sendGet(String url) { 43 | if (url == null || url.isEmpty()) { 44 | return ""; 45 | } 46 | String result = ""; 47 | //实例化一个HttpGet对象 48 | HttpGet httpGet = new HttpGet(url); 49 | //设置请求响应配置 50 | httpGet.setConfig(requestConfig); 51 | CloseableHttpResponse response = null; 52 | try { 53 | response = httpClient.execute(httpGet); //获取到response对象 54 | System.out.println("输出当前的URI地址: " + httpGet.getURI()); 55 | //如果返回值为200,则请求成功,可以通过TestNG做判断 HttpStatus.SC_OK 56 | int status = response.getStatusLine().getStatusCode(); 57 | System.out.println("当前请求URL状态: " + status); 58 | //获取Http Headers信息 59 | Header[] headers = response.getAllHeaders(); 60 | int headerLength = headers.length; 61 | for (int i = 0; i < headerLength; i++) { 62 | System.out.println("Header内容为: " + headers[i]); 63 | } 64 | //获取到请求的内容 65 | HttpEntity entity = response.getEntity(); 66 | result = EntityUtils.toString(entity, "UTF-8"); 67 | System.out.println("获取请求响应的内容为: " + result); 68 | } catch (IOException | ParseException e) { 69 | logger.log(Level.INFO, e.getMessage()); 70 | } finally { 71 | try { 72 | httpGet.releaseConnection(); //关闭响应 73 | if(response != null){ 74 | response.close(); 75 | } 76 | //httpClient.close(); 77 | } catch (IOException e) { 78 | logger.log(Level.INFO, e.getMessage()); 79 | } 80 | } 81 | return result; 82 | } 83 | 84 | /** 85 | * 向服务器发送post请求 86 | * 87 | * @param url 88 | * @param params 89 | * @return 90 | */ 91 | public static String sendPost(String url, Map params) { 92 | if (url == null || url.isEmpty() || params == null || params.isEmpty()) { 93 | return ""; 94 | } 95 | String result = ""; 96 | HttpPost httpPost = new HttpPost(url); 97 | httpPost.setConfig(requestConfig); 98 | List list = new ArrayList<>(); 99 | for (Map.Entry entry : params.entrySet()) { 100 | list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 101 | } 102 | CloseableHttpResponse response = null; 103 | try { 104 | httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8")); 105 | response = httpClient.execute(httpPost); 106 | HttpEntity entity = response.getEntity(); 107 | result = EntityUtils.toString(entity, "UTF-8"); 108 | } catch (IOException | ParseException e) { 109 | logger.log(Level.INFO, e.getMessage()); 110 | } finally { 111 | try { 112 | httpPost.releaseConnection(); 113 | if (response != null) { 114 | response.close(); 115 | } 116 | //httpClient.close(); 117 | } catch (IOException e) { 118 | logger.log(Level.INFO, e.getMessage()); 119 | } 120 | } 121 | return result; 122 | } 123 | 124 | /** 125 | * 向服务器发送post请求 126 | * 127 | * @param url 128 | * @param jsonParams 129 | * @return 130 | */ 131 | public static String sendPost(String url, String jsonParams) { 132 | if (url == null || url.isEmpty() || jsonParams == null || jsonParams.isEmpty()) { 133 | return ""; 134 | } 135 | String result = ""; 136 | HttpPost httpPost = new HttpPost(url); 137 | httpPost.setConfig(requestConfig); 138 | httpPost.setHeader("Content-Type", "application/json"); 139 | CloseableHttpResponse response = null; 140 | try { 141 | httpPost.setEntity(new StringEntity(jsonParams, "UTF-8")); 142 | response = httpClient.execute(httpPost); 143 | HttpEntity httpEntity = response.getEntity(); 144 | result = EntityUtils.toString(httpEntity, "UTF-8"); 145 | } catch (IOException | ParseException e) { 146 | logger.log(Level.INFO, e.getMessage()); 147 | } finally { 148 | try { 149 | httpPost.releaseConnection(); 150 | if (response != null) { 151 | response.close(); 152 | } 153 | //httpClient.close(); 154 | } catch (IOException e) { 155 | logger.log(Level.INFO, e.getMessage()); 156 | } 157 | } 158 | return result; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------