java面试题网

普通会员

162

帖子

12

回复

171

积分

楼主
发表于 2018-03-29 18:21:14 | 查看: 5404| 回复: 0

SpringBoot教程_SpringBoot快速入门教程

SpringBoot教程_SpringBoot快速入门教程


第一章:带你入门SpringBoot第一个程序


1、maven新建一个普通工程,pom.xml配置如下

<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>com.jubotech</groupId>

<artifactId>spring-boot</artifactId>

<version>0.0.1-SNAPSHOT</version>

<parent>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-parent</artifactId>

   <version>1.5.8.RELEASE</version>

</parent>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

<java.version>1.8</java.version>

</properties>

<dependencies>

<!-- 整合 javaweb  -->

 <dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-web</artifactId>

   </dependency>

</dependencies>

</project>

2、编写启动入口

package cn.wuliaokankan.web;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

/**

* Spring Boot项目的核心注解,主要目的是开启自动配置,加了这个注解,后springboot会扫描本包及子包的所有javabean;

*/

@SpringBootApplication

public class SpringBootMain {

public static void main(String[] args) {

    //SpringBoot项目入口

SpringApplication.run(SpringBootMain.class, args);

}

}

3、编写controller 和 对象bean

package cn.wuliaokankan.web.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

/**

* @RestController支持restfull的controller

*/

@RestController

public class UserController {

/**

* 返回字符串

* @return

*/

@ResponseBody

@RequestMapping("/hello")

public  String hello(){

return "无聊看看https:www.wuliaokankan.cn,闲的无聊就看看";

}

/**

* 返回json对象

* @return

*/

@ResponseBody

@RequestMapping("/user")

public  User user(){

return new User(100, "无聊看看");

}

/**

* 返回json数组

* @return

*/

@ResponseBody

@RequestMapping("/userList")

public  List<User> userList(){

List<User> list = new ArrayList<>();

for(int i=1;i<-10;i++){

list.add(new User(100+i, "无聊看看"+i));

}

return list;

}

}

编写User对象

package cn.wuliaokankan.web.entity;

import java.io.Serializable;

public class User implements Serializable {

private static final long serialVersionUID = 1L;

private Integer id;

private String name;

public User() {

super();

}

public User(Integer id, String name) {

super();

this.id = id;

this.name = name;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

4、main方法启动SpringBootMain.java,浏览器依次访问

http://127.0.0.1:8080/hello

http://127.0.0.1:8080/user

http://127.0.0.1:8080/userList

页面就会返回对应字符串和json数组,其他对象照葫芦画瓢即可

说明:springboot默认使用了tomcat容器作为web服务器,默认端口8080


第二章:SpringBoot 框架web容器、配置文件及jsp的使用


1、修改springboot默认容器的端口

在maven工程的src/main/resources下新建一个application.properties配置文件(springboot默认的主配置文件就叫此名,springboot也支持application.yml配置文件,看着不爽,我个人不太喜欢)

加入一行:

server.port = 9090

重启运行即可修改默认容器端口

2、springboot配置jsp环境

springboot默认是不支持jsp的,需要引入依赖才可支持,pom.xml加入

<dependency>

<groupId>org.apache.tomcat.embed</groupId>

<artifactId>tomcat-embed-jasper</artifactId>

</dependency>

application.properties配置视图解析器

spring.mvc.view.prefix=/WEB-INF/pages/

spring.mvc.view.suffix=.jsp

3、在项目src/main目录下新建webapp目录,在webapp目录下新建WEB-INF,在WEB-INF下新建pages目录,再在pages下新建一个index.jsp(注意目录结构,不然将找不到jsp页面)

jsp页面取值:你好 ${user}

4、编写Controller方法

package cn.wuliaokankan.web.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

/**

* 注意这里要用@Controller注解

*/

@Controller

public class JspController {

/**

* 传值并返回到jsp页面

*/

@RequestMapping("/jsp")

public  ModelAndView index(){

Map<String, String> model =new HashMap<>();

model.put("user", "无聊看看");

return new ModelAndView("index",model);

}

}

5、启动springboot工程,浏览器访问http://127.0.0.1:9090/jsp即可携值跳转到index.jsp页面


第三章   springboot整合和freemarker


1、pom.xml中移除jsp的依赖

<!-- <dependency> -->

<!-- <groupId>org.apache.tomcat.embed</groupId> -->

<!-- <artifactId>tomcat-embed-jasper</artifactId> -->

<!-- </dependency> -->

2、application.properties配置文件中移除

#spring.mvc.view.prefix=/WEB-INF/pages/

#spring.mvc.view.suffix=.jsp

3、pom.xml中引入freemarker的依赖

<!-- 整合 freemarker 注意要把jsp的去掉 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-freemarker</artifactId>

</dependency>

4、在工程 src/main/resources(工程classpath,与application.properties同级)下新建templates文件夹,新建index.ftl,页面取值 你好${user}

5、编写Controller方法

package cn.wuliaokankan.web.controller;

import java.util.HashMap;

import java.util.Map;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

/**

* 注意这里要用@Controller注解

* 默认的freemarker的模板文件在classpath:/templates/,默认的文件扩展名为:.ftl

*/

@Controller

public class FreeMarkerController {

/**

* 传值并返回到freemarker页面

*/

@RequestMapping("/ftl")

public  ModelAndView index(){

Map<String, String> model =new HashMap<>();

model.put("user", "无聊看看");

return new ModelAndView("index",model);

}

}

6、启动springboot工程,浏览器访问http://127.0.0.1:9090/ftl即可携值跳转到index.ftl页面

7、补充:可以通过在application.properties文件中配置

spring.freemarker.templateLoaderPath=classpath:/ftl/

进行路径的修改


第四章  springboot使用jetty替换tomcat容器与静态资源的访问


1、排出tomcat依赖

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

<!-- 替换tomcat容器为 jetty-->

<exclusions>

   <exclusion>

      <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-starter-tomcat</artifactId>

   </exclusion>

</exclusions>

</dependency>

2、加入jetty依赖,即可完成容器的替换

<!-- 加入jetty依赖-->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jetty</artifactId>

</dependency>

3、springboot静态资源访问

springboot默认可以把静态资源放在

"classpath:/META-INF/resources/", "classpath:/resources/","classpath:/static/", "classpath:/public/"

所以只需要将静态资源放入这些目录,就可以直接访问了


第五章  关于springboot使用如何快速使用servlet的api


1、启动入口类加入@ServletComponentScan注解即可使用servlet3.0api

@ServletComponentScan

@SpringBootApplication

public class SpringBootMain {

public static void main(String[] args) {

    //SpringBoot项目入口

SpringApplication.run(SpringBootMain.class, args);

}

}

2、servlet3.0 注解 servlet、filter、listener

@WebServlet("/myservlet.do")

public class MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

this.doPost(req, resp);

}

@Override

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

System.out.println("欢迎你,无聊看看");

}

}

@WebFilter("/myservlet.do")

public class MyFilter implements Filter {

@Override

public void init(FilterConfig filterConfig) throws ServletException {

}

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

System.out.println("拦截你,无聊看看");

chain.doFilter(request, response);

}

@Override

public void destroy() {

}

}

@WebListener

public class MyListenner implements ServletContextListener {

@Override

public void contextInitialized(ServletContextEvent sce) {

System.out.println("监听器");

}

@Override

public void contextDestroyed(ServletContextEvent sce) {

}

}

3、Controller方法注入HttpServletRequest、HttpServletResponse


第六章  springboot中拦截器的使用


1、编写MyHandlerInterceptor.java实现HandlerInterceptor接口

public class MyHandlerInterceptor implements  HandlerInterceptor{

@Override

public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)

throws Exception {

System.out.println("----afterCompletion在页面渲染之后被调用--好像没啥鸟用--");

}

@Override

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)

throws Exception {

System.out.println("----postHandle在controller执行之后切页面渲染之前被调用----");

}

@Override

public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {

System.out.println("-----preHandle在controller执行之前被调用------");

return true;

}

}

2、编写WebConfiguration.java 继承WebMvcConfigurerAdapter加入 @SpringBootConfiguration注解,重写addInterceptors方法,将自定义的拦截器加入即可

@SpringBootConfiguration

public class WebConfiguration extends WebMvcConfigurerAdapter {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new MyHandlerInterceptor());

}

}


第七章  springboot中对异常的处理


1、编写MyException.java 实现ErrorPageRegistrar,加上@Component注解由spring容器管理

@Component

public class MyException implements  ErrorPageRegistrar{

@Override

public void registerErrorPages(ErrorPageRegistry registry) {

ErrorPage ep404 = new ErrorPage(HttpStatus.NOT_FOUND , "/404.html");

ErrorPage ep500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

registry.addErrorPages(ep404,ep500);

}

}

2、在classpath资源目录(src/main/resources)下新建public目录,新建自定义的404html,500.html


第八章  springboot  事务、AOP的运用


1、springboot中事务的应用

引入依赖:

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-jdbc</artifactId>

</dependency>

启动入口注解开启事务

@EnableTransactionManagement

@SpringBootApplication

public class SpringBootMain {

public static void main(String[] args) {

    //SpringBoot项目入口

SpringApplication.run(SpringBootMain.class, args);

}

}

在service层类上加入@Transactional

2、Springboot中AOP的的应用

引入依赖

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-aop</artifactId>

</dependency>

编写切面

@Aspect//加@Aspect注解

@Component//纳入spring容器

public class LogAspect {

//@Before("execution(* com.wl.kankan.*.*.*Controller.*(..))")

@Around("execution(* com.wl.kankan.*.*.*Controller.*(..))")

public void log(){

System.out.println("aop-log-无聊看看");

}

@After("execution(* com.wl.kankan.*.*.*Controller.*(..))")

public void logAfter(JoinPoint point){

System.out.println(point.getTarget().getClass());

}

}

springboot默认开启了aop,不需要任何配置

--------------------------------------------------无聊看看网原创------------------------------------



文章来自www.wityx.com,转载请注明出处!原文地址http://www.wityx.com/post/247_1_1.html


java面试题交流群:327440556

您需要登录后才可以回帖 登录 | 立即注册

java面试题网www.wuliaokankan.cnjava建站系统提供技术支持V2.1 网站地图 © 2016-2018