第一次创建springboot框架项目
- 1.1_创建步骤
- 2.1_启动时遇到的问题
- 2.2_启动响应网页测试
- 2.3_连接数据库尝试
1.1_创建步骤
(1)创建spring项目
(2)
(3)
加入引擎
下一步即可
2.1_启动时遇到的问题
(1)刚开始没有启动图标,等一会就好了
(2)后来启动失败并报错ERROR 3704 — [ main] o.s.b.d.LoggingFailureAnalysisReporter :
因为默认端口是8080,若已被占用需要更改默认端口号
修改方法:修改application.properties文件,在文件中添加:
server.port=8081
server.context-path=/demo
启动成功:
(3)接下来访问http://localhost:8081/ 成功,但是后来过了一天又不行了发现是目录的问题
应该访问http://localhost:8081/demo
2.2_启动响应网页测试
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//响应服务器,与@RequestMapping配合使用(“@RestController配合@RequestMapping”与“@Controller配合@ResponseBody再配合@RequestMapping”效果一样)
@SpringBootApplication//声明该类是一个springboot引导类,
public class DemoApplication {public static void main(String[] args) {//run方法表示运行springboot的引导类SpringApplication.run(DemoApplication.class, args);}@RequestMappingpublic String hello() {return "hello spring boot!";}
}
在浏览器搜索:“http://localhost:8081/”
2.3_连接数据库尝试
package com.example.demo;
import java.sql.*;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController//响应服务器,与@RequestMapping配合使用(“@RestController配合@RequestMapping”与“@Controller配合@ResponseBody再配合@RequestMapping”效果一样)
@SpringBootApplication
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}@RequestMappingpublic String hello()throws Exception {SqlOperation.main();ResultSet resultSet = SqlOperation.statement.executeQuery("select * from Score");String s;resultSet.next();s = resultSet.getString("name");return s;}
}
class SqlOperation {public static Connection connection = null;//定义连接数据库的对象(桥梁)public static String url = "jdbc:sqlserver://localhost:1433;DatabaseName=Studentinfo";public static Statement statement = null;//定义静态操作对象public static PreparedStatement preparedStatement = null;//定义动态操作对象public static void main() {try{//第一步加载驱动Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");System.out.println("加载驱动成功!");//第二步建立连接connection = DriverManager.getConnection(url,"sa","shejiashuai");System.out.println("连接数据库成功!");//第三步建立操作对象statement = connection.createStatement();}catch (Exception e){e.printStackTrace();System.out.println("连接数据库失败!");}}public static void close(){//关闭连接try{statement.close();connection.close();}catch (Exception e){e.printStackTrace();}}
}