嗯,工具用的是intellij idea 朋友也推荐使用,用过android studio。确实好用。
首先创建一个 Spring Boot项目
。两种方式
1.可以利用这个网站创建 http://start.spring.io/
然后下载下来导入即可,可以自定义,很方便。而且是maven依赖~
导入intellij idea的方法是
“File”->“new”->“Module from Existing Sources...”
然后要选中 pom.xml文件
导入后要下载很多依赖文件,等一小会。
就会这样
2.还有一种是自带的 直接创建 输入url还是这个url~
因为pom.xml是maven的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
编写Controller
package com.example.test.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Administrator on 2017/6/12.
*/
@Controller
public class IndexController {
@RequestMapping(path = {"/","/index"})
@ResponseBody
public String index(){
return "hello Spring Boot";
}
}
访问8080
@RequestMapping(value = {"/profile/{groupId}/{userId}"})
//和Flask一样~{里面是参数}
@ResponseBody
public String profile(@PathVariable("groupId") String groupId,
//可以使用@PathVariable来获取url中的参数是/这种的 后面定义类型,参数名
@PathVariable("userId") int userId,
@RequestParam(value = "type",defaultValue = "1") int type,
//可以RequestParam来获取request请求的参数值,可以设置默认值 同样是后面设置 参数类型
都可以在方法中操作。
@RequestParam(value = "key",defaultValue = "Recar")String key
){
return String.format("GID{%s},UID{%d},TYPE{%d},KET{%s}",groupId,userId,type,key);
}
使用默认的
传参
然后使用 velocity模板
pom.xml中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-velocity</artifactId>
<version>1.4.1.RELEASE</version>
</dependency>
然后。。。写了模板,语法与Python的Flask差不多。。!!!!!重要的是SpringBoot只有1.4以下才支持。。然后怪不得我改了那么就还是不行。。。
操作request和response
@RequestMapping("/request")
@ResponseBody
public String request(HttpServletRequest request, HttpServletResponse response, HttpSession session){
String strHeader;
strHeader = request.getHeader("Cookie");
return strHeader;
}
@RequestMapping("/response")
@ResponseBody
public String response(@CookieValue(value = "cookieTest",defaultValue = "1") String cookie,
@RequestParam(value = "key",defaultValue = "key")String key,
@RequestParam(value = "value",defaultValue = "value") String value,
HttpServletResponse response){
//通过传入的参数设置cookie
response.addCookie(new Cookie(key,value));
response.addHeader(key,value);
return cookie;
}
跳转 302与301
301是永久跳转,也就是下次请求直接访问的是跳转后的
302是暂时跳转,下次还是会访问请求的url
@RequestMapping("/redirect/{code}")
public RedirectView redirectView(@RequestParam(value = "code",defaultValue = "302") int code){
RedirectView redirectView = new RedirectView("/");
if(code==302){
redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
return redirectView;
}else {
return redirectView;
}
}
异常 spring boot帮我们直接跳转到指定的页面。自己写个
//自己写异常
@RequestMapping("/admin")
@ResponseBody
public String amdin(@RequestParam(value = "key",defaultValue = "no") String key){
if("admin".equals(key)){
return "hello admin";
}
else {
//抛出异常
throw new IllegalArgumentException("key 错误");
}
}
//如果有异常就用下面的
@ExceptionHandler
@ResponseBody
public String error(Exception e){
return e.getMessage();
}
使用IOC
所有的逻辑写在service中,然后利用容器的IOC来实现
Controller
@Autowired
private IndexService indexService;
@RequestMapping("/indexService")
@ResponseBody
public String indexService(){
return indexService.index();
}
Service
@Service
public class IndexService {
public String index(){
return "hello service";
}
}
log,利用aop实现
java是用aop实现的,python使用装饰器实现
先使用log
@Controller
public class IndexController {
//创建log
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@RequestMapping(path = {"/","/index"})
@ResponseBody
public String index(HttpSession session){
logger.info("Visit Index");
//log记录
return "hello Spring Boot"+session.getAttribute("user");
}
package com.example.test.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2017/6/12.
*/
@Aspect
@Component
public class LogAspect {
private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
@Before("execution(* com.example.test.controller.IndexController.*(..))")
public void beforMethod(JoinPoint joinPoint){
logger.info("before method: ");
}
@After("execution(* com.example.test.controller.IndexController.*(..))")
public void afterMethod(JoinPoint joinPoint){
logger.info("after method");
}
}
使用切入点(JoinPoint joinPoint )
@Before("execution(* com.example.test.controller.IndexController.*(..))")
public void beforMethod(JoinPoint joinPoint){
StringBuilder sb = new StringBuilder();
for(Object arg:joinPoint.getArgs()){
sb.append("arg:"+arg.toString()+"|");
}
logger.info("before method: "+sb.toString());
}
这样就可以获取所有的参数了
遇到的问题
Error:java: 无效的源发行版: 1.8
上网查了,默认的是1.8 更改为1.7,还是不行,看到 pom.xml文件中的标签 java.version版本没有改,改成本地的1.7成功运行
学习过Spring 在看Spring Boot还是比较容易。。。毕竟就是为了简化。好用的很~