Srpingboot记录
一、HelloWorld
依赖
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <!—SpringBoot web 组件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
|
spring-boot-starter-parent作用 在pom.xml中引入spring-boot-start-parent,spring官方的解释叫什么stater poms,它可以提供dependency management,也就是说依赖管理,引入以后在申明其它dependency的时候就不需要version了,后面可以看到。 spring-boot-starter-web作用 springweb 核心组件 |
创建HelloController类,内容如下
@RestController @EnableAutoConfiguration publicclass HelloController { @RequestMapping("/hello") public String index() { return"Hello World"; } publicstaticvoid main(String[] args) { SpringApplication.run(HelloController.class, args); } } |
2.4、@RestController
在上加上RestController 表示修饰该Controller所有的方法返回JSON格式,直接可以编写
Restful接口
2.5、@EnableAutoConfiguration
注解:作用在于让 Spring Boot 根据应用所声明的依赖来对 Spring 框架进行自动配置
这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于spring-boot-starter-web添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。
2.6 SpringApplication.run(HelloController.class, args);
标识为启动类
2.7、SpringBoot启动方式1
Springboot默认端口号为8080
@RestController @EnableAutoConfiguration publicclass HelloController { @RequestMapping("/hello") public String index() { return"Hello World"; } publicstaticvoid main(String[] args) { SpringApplication.run(HelloController.class, args); } } |
启动主程序,打开浏览器访问http://localhost:8080/index,可以看到页面输出Hello World
2.8、SpringBoot启动方式2
@ComponentScan(basePackages = "com.itmayiedu.controller")---控制器扫包范围
@ComponentScan(basePackages = "com.itmayiedu.controller") @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } |
说明:@RestController登陆Controller+Responsebody,用原生的SpringMVC也是可以的!
二、静态资源访问
在src/main/resources/目录下创建如下规定的目录:
/static
/public
/resources
/META-INF/resources
这是springboot已经配置好了的静态资源映射。注意:路径是不带static或者public的,已经映射好了。
三、自定义异常拦截器
1.拦截器代码(跟SpringMVC相同)
package com.loger.interceptor;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter;
/** * Create by Loger * SpringMVC拦截器 */ public class ExceptionInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; }
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { JSONObject msg = new JSONObject(); if (ex != null) { msg.put("result", "fail"); msg.put("code", "system.error"); msg.put("msg", "系统错误"); String json = JSON.toJSONString(msg); response.setContentType("application/json;charset=UTF-8"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); PrintWriter out = response.getWriter(); out.print(json); out.flush(); out.close(); } }
} |
2.拦截器配置
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new ExceptionInterceptor()); super.addInterceptors(registry); } } |
3.main方法扫包
@ComponentScan(basePackages = {"com.loger.controller","com.loger.common"}) @EnableAutoConfiguration//标识为启动类 public class Main { public static void main(String [] args){ SpringApplication.run(Main.class,args); } } |
说明:扫描到config所在的包
四、springboot中使用原生Servlet的东西
1.过滤器
@WebFilter(filterName = "test",urlPatterns = "/*") public class TestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("过滤器被初始化了"); }
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; StringBuffer requestURL = request.getRequestURL(); System.out.println("请求的url:"+requestURL); filterChain.doFilter(servletRequest,servletResponse); }
@Override public void destroy() { System.out.println("过滤器被销毁了"); } } |
2.监听器
@WebListener public class TestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent servletRequestEvent) { System.out.println("请求销毁了了:"+servletRequestEvent.getServletRequest().getRemoteAddr()); }
@Override public void requestInitialized(ServletRequestEvent servletRequestEvent) { System.out.println("请求进来了:"+servletRequestEvent.getServletRequest().getRemoteAddr()); } } |
3.servlet
@WebServlet(value = "/testServlet") public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("请求了TestServlet"); resp.setCharacterEncoding("utf-8"); PrintWriter out = resp.getWriter(); out.print("响应给你"); } } |
4.扫包
@ServletComponentScan(basePackages = {"com.loger.filter","com.loger.listener","com.loger.servlet"}) @ComponentScan(basePackages = {"com.loger.controller","com.loger.common"}) @EnableAutoConfiguration//标识为启动类 public class Main { public static void main(String [] args){ SpringApplication.run(Main.class,args); } } |
五、项目路径问题
@RequestMapping(value = "/path") public Object path(HttpServletRequest request){ //这种写法springboot不支持 // String path = this.getClass().getClassLoader().getResource("/").getPath(); // System.out.println(path); return request.getServletContext().getRealPath("/"); } |
不支持this这种写法
六、页面(freeMark)
推荐使用freeMark,不推荐使用jsp。如果使用jsp,那就需要建立webapps、web-inf目录,这跟web工程就没什么区别了。
1.依赖
<!-- 引入freeMarker的依赖包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> |
2.配置文件
新建application.properties文件,在resources目录下
#freeMark配置 spring.freemarker.allow-request-override=false spring.freemarker.cache=true spring.freemarker.check-template-location=true spring.freemarker.charset=UTF-8 spring.freemarker.content-type=text/html spring.freemarker.expose-request-attributes=false spring.freemarker.expose-session-attributes=false spring.freemarker.expose-spring-macro-helpers=false spring.freemarker.suffix=.ftl spring.freemarker.template-loader-path=classpath:/templates/ |
3.代码
@RequestMapping public String index(HttpServletRequest request){ request.setAttribute("name","Loger"); return "index"; } |
4.页面
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"/> <title>ftl页面</title> </head> <body> ${name} </body> </html> |
七、文件上传
1.单文件上传
/** * 单文件上传 * @param file2 * @return */ @RequestMapping(value = "/upload",method = RequestMethod.POST) public Object upload(MultipartFile file2){ //说明:使用MultipartFIle不需要进行配置,使用CommonsMultipartFile是需要配置的 //参数名可以与文件name属性对应,也可以使用@RequestParam指定 File save = new File("D:\\"+file2.getOriginalFilename()); try { System.out.println(file2.getName()+" "+file2.getOriginalFilename()); file2.transferTo(save); } catch (IOException e) { e.printStackTrace(); return "fail"; } return "success"; } |
2.多文件上传
/** * 多文件上传 * @return */ @RequestMapping(value = "/upload2",method = RequestMethod.POST) public Object upload2(HttpServletRequest request){ List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");//这个file对应表单名 for(MultipartFile file:files){ File save = new File("d:\\"+file.getOriginalFilename()); try { file.transferTo(save); } catch (IOException e) { e.printStackTrace(); } } return "success"; } |
3.页面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 你能访问到我吗??? <form action="/upload2" method="post" enctype="multipart/form-data" > <input name="file" type="file"><br> <input name="file" type="file"><br> <input name="file" type="file"><br> <input type="submit" value="上传"> </form> </body> </html> |
4.上传文件大小限制配置
在application.properties文件中添加如下配置
#文件上传设置 spring.http.multipart.maxFileSize=100Mb spring.http.multipart.maxRequestSize=1000Mb |
八、整合jdbc-template
依赖
<!-- jdbc-template --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> |
application.properties配置
#JDBCTemplate spring.datasource.url=jdbc:mysql://localhost:3306/db_test spring.datasource.username=root spring.datasource.password=apple spring.datasource.driver-class-name=com.mysql.jdbc.Driver |
增删改
都是使用jdbcTemplate.unpdate();方法
public void delete(int id){ jdbcTemplate.update("DELETE FROM `user` WHERE id=?;",id); } |
查
首先需要一个Mapper映射:
然后使用query方法:
事务管理
在Service方法上加@Transactional注解即可。
springboot整合Mybatis
依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> |
数据源
跟jdbctemplate的数据源一样的
#Mybatis spring.datasource.url=jdbc:mysql://localhost:3306/db_test spring.datasource.username=root spring.datasource.password=apple spring.datasource.driver-class-name=com.mysql.jdbc.Driver |
mapper接口
这里使用注解的形式
public interface UserMapper { @Select("select id,name,age from user where id=#{id}") User select(Integer id); } |
启动类扫包
扫描mapper接口所在的包
@MapperScan(value = "com.loger.mapper") |
打包发布
在pom文件中添加:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <maimClass>com.loger.main.Main</maimClass> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions>
</plugin> </plugins> </build>
|