Springboot

SpringBoot(二) :web综合开发

2017-08-15  本文已影响127人  阿亮私语

上篇介绍了Spring的简单入门<>,方便大家快速入门,了解springboot的简单开发,下面进一步的展开说明。

1、web开发

springboot的开发非常简单,其中包括常用的json输出,filters,property,log等
只要在类上添加@RestController 这个注解,接口就会以json的方式返回,该注解是spring4.x之后推出的新注解,包括@GetMapping,@PostMapping,@DeleteMapping等一系列的注解,为了简化之前的注解操作。

这个让我尤其记忆深刻,因为一次面试中,一个面试官说这是springboot的注解,这个讨论了许久。springboot在我看来是个容器而已,可以将许多的东西包容进去,像spring相关,tomcat容器,mybatis,jpa等等。

启动时报错Unregistering JMX-exposed beans on shutdown
添加如下内置tomcat即可

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>

接下来controller的书写方式如下

@RestController
public class UserController {
    @GetMapping("/getUser")
    public User getUser(){

        return new User("admin", "123456", "aa@126.com", "aa123456","2017-06-07 11:12:23");
    }
}

如果我们需要使用页面开发,则应该用@Controller注解,下面结合模板说明。

2、自定义Filter

我们常常在项目中会使用filters用于录调用日志、排除有XSS威胁的字符、执行权限验证等等。Spring Boot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,并且我们可以自定义Filter。

操作步骤如下:

话不多少,直接上代码

@Configuration
public class WebConfiguration {
    @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean
    public FilterRegistrationBean testFilterRegistration() {

        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new MyFilter());
        registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
        registration.setName("MyFilter");
        registration.setOrder(1);
        return registration;
    }

    public class MyFilter implements Filter {
        @Override
        public void destroy() {
            // TODO Auto-generated method stub
        }

        @Override
        public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain filterChain)
                throws IOException, ServletException {
            // TODO Auto-generated method stub
            HttpServletRequest request = (HttpServletRequest) srequest;
            System.out.println("this is MyFilter,url :"+request.getRequestURI());
            filterChain.doFilter(srequest, sresponse);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
            // TODO Auto-generated method stub
        }
    }

3、自定义propertiey

配置在application.properties中的

server.port=8888
com.lessons.title= welcome to my lesson
com.lessons.description= best lessons

自定义配置类

@Component
public class LessinsProperty {
    @Value("${com.lessons.title}")
    private String title;
    @Value("${com.lessons.description}")
    private String description;
}


4、log配置

配置输出级别

logging.path=/user/local/log
logging.level.com.favorites=DEBUG
logging.level.org.springframework.web=INFO

path为本机的log地址,logging.level 后面可以根据包路径配置不同资源的log级别

5、数据库操作

这里主要讲mysql结合jpa的使用

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
 <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

其实这个hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构,有四个值:

6、添加实体和dao

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private String regTime;

    public User(String userName, String passWord) {
        this.userName = userName;
        this.passWord = passWord;
    }
    //省略getter settet方法、构造方法

}

dao只要继承JpaRepository类就可以,几乎可以不用写方法,还有一个特别有尿性的功能非常赞,就是可以根据方法名来自动的生产SQL,比如findByUserName 会自动生产一个以 userName 为参数的查询方法,比如 findAlll 自动会查询表里面的所有数据,比如自动分页等等。。

Entity中不映射成列的字段得加@Transient 注解,不加注解也会映射成列

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByUserName(String userName);
    User findByUserNameOrEmail(String username, String email);
}

7、测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UserRepositoryTest {
    @Autowired
    private UserRepository userRepository;
    @Test
    public void test() throws Exception {

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
        String formattedDate = dateFormat.format(date);

        userRepository.save(new User("aa1", "aa@126.com", "aa", "aa123456",formattedDate));
        userRepository.save(new User("bb2", "bb@126.com", "bb", "bb123456",formattedDate));
        userRepository.save(new User("cc3", "cc@126.com", "cc", "cc123456",formattedDate));

        Assert.assertEquals(9, userRepository.findAll().size());
        Assert.assertEquals("bb", userRepository.findByUserNameOrEmail("bb", "cc@126.com").getNickName());
        userRepository.delete(userRepository.findByUserName("aa1"));
    }
}

当让 spring data jpa 还有很多功能,比如封装好的分页,可以自己定义SQL,主从分离等等,这里就不详细讲了

8、thymeleaf模板

Spring boot 推荐使用来代替jsp,thymeleaf模板到底是什么来头呢,让spring大哥来推荐,下面我们来聊聊

Thymeleaf介绍

Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。

好了,你们说了我们已经习惯使用了什么 velocity,FreMaker,beetle之类的模版,那么到底好在哪里呢? 比一比吧 Thymeleaf是与众不同的,因为它使用了自然的模板技术。这意味着Thymeleaf的模板语法并不会破坏文档的结构,模板依旧是有效的XML文档。模板还可以用作工作原型,Thymeleaf会在运行期替换掉静态值。Velocity与FreeMarker则是连续的文本处理器。 下面的代码示例分别使用Velocity、FreeMarker与Thymeleaf打印出一条消息:

Velocity: <p>$message</p>
FreeMarker: <p>${message}</p>
Thymeleaf: <p th:text="${message}">Hello World!</p>
``
### 9、URL
URL在Web应用模板中占据着十分重要的地位,需要特别注意的是Thymeleaf对于URL的处理是通过语法@{…}来处理的。Thymeleaf支持绝对路径URL:
<a th:href="@{http://www.thymeleaf.org}">Thymeleaf</a>

条件求值

<a th:href="@{/login}" th:unless=${session.user != null}>Login</a>

for循环

<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

就列出这几个吧,下面结合代码说下thymeleaf的整合

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

配置文件尾部一定注意不要有空格,因为空格导致404的问题,导致花了很多时间,还有修改pom文件后确认jar包是否正确引入。
controller代码编写如下

@Controller
public class HelloWorldController {
    @Value("${com.lessons.title}")
    private String title;
    @Value("${com.lessons.description}")
    private String description;
    /**
     * 返回html模板
     * @return
     */
    @RequestMapping("/hello")
    public String hello(ModelMap map){
        map.put("title",title);
        map.put("description",description);
        return "hello";
    }
}

thymeleaf模板如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello World!</title>
    <meta charset="UTF-8"/>
</head>
<body>
<h1 th:inline="text">Hello.v.2</h1>
<p th:text="${title}"></p>
<p th:text="${description}"></p>
</body>
</html>

9、页面即原型

在Web开发过程中一个绕不开的话题就是前端工程师与后端工程师的写作,在传统Java Web开发过程中,前端工程师和后端工程师一样,也需要安装一套完整的开发环境,然后各类Java IDE中修改模板、静态资源文件,启动/重启/重新加载应用服务器,刷新页面查看最终效果。

但实际上前端工程师的职责更多应该关注于页面本身而非后端,使用JSP,Velocity等传统的Java模板引擎很难做到这一点,因为它们必须在应用服务器中渲染完成后才能在浏览器中看到结果,而Thymeleaf从根本上颠覆了这一过程,通过属性进行模板渲染不会引入任何新的浏览器不能识别的标签,例如JSP中的,不会在Tag内部写表达式。整个页面直接作为HTML文件用浏览器打开,几乎就可以看到最终的效果,这大大解放了前端工程师的生产力,它们的最终交付物就是纯的HTML/CSS/JavaScript文件。

最后代码也会给大家:
其中本章代码在lessons项目中的项目lessons

https://github.com/liangliang1259/daily-lessons.git

上一篇 下一篇

猜你喜欢

热点阅读