使用springBoot实现 web后端(二)
2017-03-20 14:16
337 查看
基于springBoot的Web后端 (二)
三、代码编写
项目源码(github)webdemo for wiki
项目结构图:
1.编写配置文件(application.yml)
IDE自动生成的工程配置文件为application.properties 可通过重命名为application.yml。 两者相差不大,凭个人喜好选择。 代码如下
server: port: 8888 #配置服务占用端口号 context-path: /webdemo #配置环境路径名 logging: config: classpath:logback-spring.xml #日志配置文件路径 debug: false #debug级日志是否输出 spring: output: ansi: enabled: always #控制台彩色 thymeleaf: suffix: .html #网页后缀名 mode: HTML5 #网页类型 prefix: classpath:/templates/ #网页所在路径 encoding: UTF-8 #网页编码格式 content-type: text/html #web容器类型 service: url: 127.0.0.1:8887/servicedemo #后台地址
注意空格位置不得有误
2编写日志配置文件(logback-spring.xml)
此处不再进行关于logback日志的讲解有兴趣可以参考以下博文
logback 配置详解(一)
logback 配置详解(二)
logback 配置详解(三)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xml> <configuration scan="true" scanPeriod="1 seconds" debug="false"> <contextName>myweblogback=></contextName> <!-- <include resource="org/springframework/boot/logging/logback/base.xml"/> --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoder 默认配置为PatternLayoutEncoder --> <encoder> <pattern>%contextName %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n </pattern> </encoder> </appender> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <appender name="ERRFILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>ERRlogFile.%d{yyyy-MM-dd}.log</fileNamePattern> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern> </encoder> </appender> <logger name="com.wp.webdemo.controller" level="INFO" additivity="true"> <appender-ref ref="FILE" /> <appender-ref ref="ERRFILE" /> </logger> <root level="INFO"> <appender-ref ref="STDOUT" /> </root> </configuration>
主要功能是 将控制层的接口通信日志和错误日志分级按日打印
3、视图层编写(login.html)
首先将接下来要用到的资源文件 (bootstrap.css,bootstarp.js,jquery.js)放在static文件夹下。相应jar包可以在相应官网下载。 html页面代码如下,放在templates文件夹下
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta content="test/html" charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Title</title> <script src="jquery.js"></script> <link rel="stylesheet" href="bootstrap.css"/> <script src="bootstrap.js" ></script> </head> <body > <div align="center"> <div style="width: 50% ; margin-top: 200px" align="center"> <h3><span th:text="${msg}"></span></h3> <form method="post" class="form-horizontal" action="login"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="email" name="email" class="form-control" id="inputEmail3" placeholder="Email"/> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" name="password" class="form-control" id="inputPassword3" placeholder="Password"/> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox"/> Remember me </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Sign in</button> </div> </div> </form> </div> </div> </body> </html>
4、控制层编写(UserController)
用到的接口信息后台源码地址(github)
servicedemo for wiki
url:http://127.0.0.1:8887/servicedemo/login
入参:
参数名 | 参数类型 | 参数说明 |
---|---|---|
String | 邮箱地址 | |
password | String | 密码 |
参数名 | 参数类型 | 参数说明 |
---|---|---|
resultCode | String | 响应码 |
resultMessage | String | 响应信息 |
入参 { "email":"771910012@qq.com", "password":"123" } 出参 { "resultCode": "1", "resultMessage": "成功" }
package com.wp.webdemo.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.wp.webdemo.web.domain.req.LoginReq; import com.wp.webdemo.web.domain.resp.ResultResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.net.URL; import java.util.HashMap; /** * Created by wp on 2017/3/16. * 用户控制层 */ @Controller public class UserController { /* logger 初始化 */ private static Logger log= LoggerFactory.getLogger(UserController.class); /* 变量注入 : application.yml 中的service.url 变量 */ @Value("${service.url}") private String serviceUrl; /** * 首页跳转 * @return */ @RequestMapping(value = "index" , method = RequestMethod.GET , produces = MediaType.ALL_VALUE) public String index(){ return "login"; } /** * 登录action * @param loginReq * @return */ @RequestMapping(value = "login" , method = RequestMethod.POST , produces = MediaType.ALL_VALUE) public ModelAndView login(LoginReq loginReq) { log.info("/login: 入参 "+loginReq.toString()); String msg; HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectMapper objectMapper=new ObjectMapper(); try { URL url =new URL("http://"+serviceUrl+"/login"); HttpEntity<String> entity = new HttpEntity<String>(objectMapper.writeValueAsString(loginReq), headers); RestTemplate template=new RestTemplate(); String result=template.postForObject(url.toString(),entity,String.class, new HashMap<String, Object>()); ResultResponse response= objectMapper.readValue(result,ResultResponse.class); if (!response.getResultCode().equals("1")) { msg=response.getResultMessage(); } else msg = "登录成功"; log.info("/login:出参"+response.toString()); } catch (IOException e1) { log.error(e1.getMessage()); msg = "未知错误"; } return new ModelAndView("login","msg",msg); } }
5、实体类编写
此处用到的类有 LoginReq和ResultResponse 用来封装rest 请求和json数据。
package com.wp.webdemo.web.domain.req; import lombok.Data; import lombok.ToString; import java.io.Serializable; /** * Created by 95 on 2017/3/16. */ @Data @ToString public class LoginReq implements Serializable{ private String email; private String password; }
package com.wp.webdemo.web.domain.resp; import lombok.Data; import lombok.ToString; /** * Created by 95 on 2017/3/17. */ @Data @ToString public class ResultResponse { private String resultCode; private String resultMessage; public ResultResponse(String resultCode, String resultMessage) { this.resultCode = resultCode; this.resultMessage = resultMessage; } public ResultResponse() { } }
至此代码编写完成,实例只实现了登录功能,可根据自己需求进行拓展,举一反三
三、测试
在WebdemoApplication上右键->RUN 看到Started WebdemoApplication in 4.939 seconds (JVM running for 5.622) 且无异常抛出,项目则成功运行 打开浏览器 输入url:http://127.0.0.1:8888/webdemo/index 效果如下图:
输入Email 771910012@qq.com Password: 123456(已在后台写死)效果如下图:
相关文章推荐
- 使用springBoot实现 web后端(一)
- Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(json web token) 用户发送按照约定,向服务端发送 Header、Payload 和 Signature,
- 使用SpringBoot整合Jersey 实现Restful webservice.可以同时使用springmvc。
- 使用 Spring Boot 2.0 + WebFlux 实现 RESTful API功能
- 用Spring Boot & Cloud,Angular2快速搭建微服务web应用 - 实现RESTful CRUD
- 使用spring-loaded开源项目,实现java程序和web应用的热部署
- 使用spring-loaded开源项目,实现java程序和web应用的热部署
- JAVA_WEB项目之Spring中使用AOP编程运用到Lucene中实现解耦
- Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问
- Spring Boot(十一)使用AOP,@Aspect统一处理Web请求日志
- Web项目中使用Spring 3.x + Quartz 2.x实现作业调度详解
- spring boot + webSocket 实现简单会话与在线人数统计的demo
- 使用spring boot和thymeleaf提供web内容
- 46. Spring Boot中使用AOP统一处理Web请求日志【从零开始学Spring Boot】
- 使用spring-loaded开源项目,实现java程序和web应用的热部署
- Spring Boot(十)使用@Async实现异步调用
- 基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置
- 使用CXF与Spring集成实现RESTFul WebService
- 使用spring实现事务管理(@transactional)的遇到的两个异常:java.lang.noclassdeffounderror:org/objectweb.asm
- 2.1、Spring Web MVC是什么 Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职