20181010-SpringBoot HelloWord

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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@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);
	}
}

⑦通过http://localhost:8080/createUser/zhangsan 访问

猜你喜欢

转载自blog.csdn.net/qiaoqiyu6416/article/details/83003038