20181010-SpringBoot HelloWord
阿新 • • 發佈:2018-11-06
1.建立maven工程,選擇為jar型別
2.引入依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.joe</groupId> <artifactId>boot01</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- 引入父類工程 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <dependencies> <!-- spring-web 元件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> </project>
3.編寫Controller類
package cn.joe.controller; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 只需直接編寫Controller無需配置其他便可執行 * url : http://localhost:8080/getList * @author joe * */ @RestController // RestController = ResponseBody+Controller public class TestController1 { @RequestMapping("/text01") public String test01() { return "success"; } @RequestMapping("getList") public List<String> getList(){ List<String> list = new ArrayList<String>(); list.add("zhangsan"); return list; } }
4.編寫啟動類
package cn.joe.main; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; /** * 啟動類 * apringboot內建Tomcat無需配置到Tomcat上 * @author joe * */ @ComponentScan("cn.joe.controller")//配置包掃描 @EnableAutoConfiguration public class AppStart { public static void main(String[] args) { SpringApplication.run(AppStart.class, args); } }
(可選:異常處理類)
package cn.joe.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 異常處理類
* @author joe
*
*/
@ControllerAdvice
public class GrobelExceptionHandler {
@ExceptionHandler(RuntimeException.class) //處理執行時異常
@ResponseBody
public Map<String,String> errorResult(){
Map<String,String> result = new HashMap<String, String>();
result.put("error", "error");
return result;
}
}
5.執行成功
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.3.RELEASE)
2018-10-10 20:53:58.347 INFO 6068 --- [ main] cn.joe.controller.TestController1 : Starting TestController1 on DESKTOP-JSID8GI with PID 6068 (H:\bslProject\boot01\target\classes started by joe in H:\bslProject\boot01)
2018-10-10 20:53:58.351 INFO 6068 --- [ main] cn.joe.controller.TestController1 : No active profile set, falling back to default profiles: default
2018-10-10 20:53:58.422 INFO 6068 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]71ebd825: startup date [Wed Oct 10 20:53:58 CST 2018]; root of context hierarchy
2018-10-10 20:53:59.371 INFO 6068 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2018-10-10 20:54:00.776 INFO 6068 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-10-10 20:54:00.797 INFO 6068 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2018-10-10 20:54:00.799 INFO 6068 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.32
2018-10-10 20:54:00.937 INFO 6068 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-10-10 20:54:00.937 INFO 6068 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2519 ms
2018-10-10 20:54:01.537 INFO 6068 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2018-10-10 20:54:01.548 INFO 6068 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-10-10 20:54:01.549 INFO 6068 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-10-10 20:54:01.549 INFO 6068 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-10-10 20:54:01.549 INFO 6068 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-10-10 20:54:01.787 INFO 6068 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]71ebd825: startup date [Wed Oct 10 20:53:58 CST 2018]; root of context hierarchy
2018-10-10 20:54:01.871 INFO 6068 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[]}" onto public java.util.List<java.lang.String> cn.joe.controller.TestController1.getList()
2018-10-10 20:54:01.872 INFO 6068 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/text01]}" onto public java.lang.String cn.joe.controller.TestController1.test01()
2018-10-10 20:54:01.876 INFO 6068 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-10-10 20:54:01.876 INFO 6068 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-10-10 20:54:01.924 INFO 6068 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-10 20:54:01.924 INFO 6068 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-10 20:54:01.994 INFO 6068 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-10-10 20:54:02.148 INFO 6068 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-10-10 20:54:02.241 INFO 6068 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-10-10 20:54:02.247 INFO 6068 --- [ main] cn.joe.controller.TestController1 : Started TestController1 in 4.535 seconds (JVM running for 5.056)
2018-10-10 20:54:19.924 INFO 6068 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-10-10 20:54:19.925 INFO 6068 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-10-10 20:54:19.973 INFO 6068 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 48 ms
6.訪問靜態資源
在"src/main/resources"下新建"static"包,將靜態資源放到此處即可。
通過localhost:8080/xx.jpg 訪問
7.渲染web介面
--使用Freemarker模組引擎渲染Web檢視
匯入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
①在"src/main/resources"下新建"templates"包,建立index.ftl檔案。
Hello Word!
${name}
②建立控制器
package cn.joe.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PageController {
@RequestMapping("page/{page}")
public String pages(@PathVariable("page") String page,HttpServletRequest request){
request.setAttribute("name", "zhangsan");
return page;
}
}
③通過http://localhost:8080/page/index訪問
8.通過jsp渲染web頁面,建立war工程 (少用,springBoot建議使用模組引擎渲染Web介面)
①匯入依賴
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.joe</groupId>
<artifactId>boot01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 引入父類工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
<!-- spring-web 元件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
</project>
②建立application.properties配置檔案
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
③webapp/WEB-INF/jsp/index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
Hello World!
</body>
</html>
④建立控制器
package cn.joe.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class PageController {
@RequestMapping("page/{page}")
public String toPage(@PathVariable("page") String page){
return page;
}
}
⑤建立啟動類
package cn.joe.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("cn.joe.controller")
@EnableAutoConfiguration
public class AppStart {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
}
⑥通過http://localhost:8080/page/index訪問
9.使用jdbc
①引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
②配置 application.properties
spring.datasource.url=jdbc:mysql://192.168.48.4:3306/taotao
spring.datasource.username=root
spring.datasource.password=234568
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
③dao
package cn.joe.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate template; //springBoot自帶此類
public int insertUser(String username){
int update = template.update("insert into user (user_name) values(?)", username);
return update;
}
}
④service
package cn.joe.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.joe.dao.UserDao;
@Service
public class UserService {
@Autowired
private UserDao dao;
public int saveUser(String username){
int result = dao.insertUser(username);
return result;
}
}
⑤controller
package cn.joe.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.joe.service.UserService;
@RestController
public class UserController {
@Autowired
private UserService service;
@RequestMapping("/createUser/{username}")
public String createUser(@PathVariable("username") String username){
int result = service.saveUser(username);
return String.valueOf(result);
}
}
⑥啟動類
package cn.joe.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
/**
* 啟動類
* apringboot內建Tomcat無需配置到Tomcat上
* @author joe
*
*/
@ComponentScan("cn.joe.*")//配置包掃描
@EnableAutoConfiguration
public class AppStart {
public static void main(String[] args) {
SpringApplication.run(AppStart.class, args);
}
}