package com.wen.config;
import com.wen.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfigure implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/","/login","/userLogin");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/user/login");
registry.addViewController("/login").setViewName("/user/login");
}
}
package com.wen.config;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
@Scheduled(cron = "5 0 0 * * ?")
public void scheduledTask1(){
System.out.println("定时任务1");
}
@Scheduled(initialDelay = 1000 * 10,fixedDelay = 1000 * 5)
public void scheduledTask2(){
System.out.println("任务2执行时间:"+System.currentTimeMillis());
System.out.println("定时任务2");
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务2结束时间:"+System.currentTimeMillis());
}
@Scheduled(initialDelay = 1000 * 10,fixedRate = 1000 * 5)
public void scheduledTask3(){
System.out.println("任务3执行时间:"+System.currentTimeMillis());
System.out.println("定时任务3");
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务3结束时间:"+System.currentTimeMillis());
}
}
package com.wen.config;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
@Scheduled(cron = "5 0 0 * * ?")
public void scheduledTask1(){
System.out.println("定时任务1");
}
@Scheduled(initialDelay = 1000 * 10,fixedDelay = 1000 * 5)
public void scheduledTask2(){
System.out.println("任务2执行时间:"+System.currentTimeMillis());
System.out.println("定时任务2");
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务2结束时间:"+System.currentTimeMillis());
}
@Scheduled(initialDelay = 1000 * 10,fixedRate = 1000 * 5)
public void scheduledTask3(){
System.out.println("任务3执行时间:"+System.currentTimeMillis());
System.out.println("定时任务3");
try {
Thread.sleep(2*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务3结束时间:"+System.currentTimeMillis());
}
}
package com.wen.config;
import io.swagger.models.Contact;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot Swagger2 构建 API")
.termsOfServiceUrl("http://despairyoke.github.io/")
.contact("wb")
.version("1.0")
.description("温彬")
.build();
}
}
package com.wen.controller;
import com.wen.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Api("用户登录")
@Controller
public class LoginController {
@Autowired
private StudentService studentService;
@ApiOperation(value = "登录",httpMethod = "POST")
@PostMapping(value = "/userLogin")
public String login(@RequestParam("username")String username,
@RequestParam("password")String password,
Map<String,Object> map,
HttpSession session){
if (studentService.findByNameAndPassword(username,password)){
session.setAttribute("loginUser",username);
return "redirect:/list";
}else {
map.put("loginMsg","账号密码输入错误请重新输入");
return "/user/login";
}
}
}
package com.wen.controller;
import com.wen.entity.Students;
import com.wen.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Api(value = "RUCD")
@Controller
public class StudentController {
@Autowired
private StudentService studentService;
@ApiOperation(value = "查询全部",httpMethod = "GET")
@RequestMapping("/list")
public String list(Model model){
List<Students> users=studentService.getUserList();
model.addAttribute("users",users);
return "user/list";
}
@RequestMapping("/listAll")
@ResponseBody
public List<Students> all(Model model){
List<Students> list=studentService.getUserList();
return list;
}
@ApiOperation(value = "add跳转",httpMethod = "POST")
@RequestMapping("/toAdd")
public String toAdd(){
return "user/userAdd";
}
@ApiOperation("添加")
@RequestMapping("/add")
public String add(Students students){
studentService.save(students);
return "redirect:/list";
}
@ApiOperation(value = "修改",httpMethod ="PUT")
@RequestMapping("/toEdit")
public String toEdit(Model model,Long id){
Students students=studentService.findUserById(id);
model.addAttribute("user",students);
return "user/userEdit";
}
@ApiOperation(value = "修改",httpMethod ="PUT")
@RequestMapping("/edit")
public String edit(Students students){
studentService.edit(students);
return "redirect:/list";
}
@ApiOperation(value = "删除",httpMethod = "DELETE")
@RequestMapping("/delete")
public String delete(Long id){
studentService.delete(id);
return "redirect:/list";
}
}
package com.wen.dao;
import com.wen.entity.Students;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentDao extends JpaRepository<Students,Long> {
Students findById(long id);
Students findByNameAndPassword(String name,String password);
void deleteById(Long id);
}
package com.wen.entity;
import javax.persistence.*;
@Entity
@Table(name = "t_students")
public class Students {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false,unique = true)
private String name;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private int age;
@Column(nullable = false)
private String address;
@Override
public String toString() {
return "Students{" +
"id=" + id +
", name=" + name +
", password=" + password +
", age=" + age +
", address='" + address + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.wen.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user!=null)
return true;
request.setAttribute("loginMsg","没权限请先登录");
request.getRequestDispatcher("/login").forward(request,response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:height="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>用户列表</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body class="container">
<br/>
<h1>用户列表</h1>
<br/><br/>
<div class="with:80%">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>用户名</th>
<th>密码</th>
<th>年龄</th>
<th>姓名</th>
<th>修改</th>
<th>删除</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<th scope="row" th:text="${user.id}">id</th>
<td th:text="${user.name}">name</td>
<td th:text="${user.password}">password</td>
<td th:text="${user.age}">age</td>
<td th:text="${user.address}">address</td>
<td><a th:href="@{/toEdit(id=${user.id})}">编辑</a></td>
<td><a th:href="@{/delete(id=${user.id})}">删除</a></td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="col-sm-2 control-label">
<a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">新增</a>
</div>
</div>
<br/>
<br/>
<br/>
<br/>
<div id="main" style="width: 100%;height:400px;"></div>
<div id="main2" style="width: 100%;height:400px;"></div>
<div id="main3" style="width: 100%;height:400px;"></div>
<script type="text/javascript">
$(document).ready(function(){
var myChart = echarts.init(document.getElementById('main'));
var myChart2 = echarts.init(document.getElementById('main2'));
var myChart3 = echarts.init(document.getElementById('main3'));
myChart.showLoading();
var names=[];
var values=[];
$.ajax({
type : "get",
async : true,
url : "/listAll",
data : {},
dataType : "json",
success : function(result) {
if (result) {
for(var i=0;i<result.length;i++){
names.push(result[i].name);
values.push(result[i].age);
}
myChart.hideLoading();
myChart.setOption({
tooltip: {},
legend: {
data:['年龄段详情']
},
xAxis: {
data: names
},
yAxis: {
type: 'value'
},
series: [{
name: '年龄',
type: 'bar',
data: values
}]
});
myChart2.setOption({
xAxis: {
type: 'category',
data: names
},
yAxis: {
type: 'value'
},
series: [{
data: values,
type: 'line'
}]
});
myChart3.setOption({
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 10,
data: names
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['50%', '70%'],
avoidLabelOverlap: false,
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '30',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: values
}
]
});
}
},
error : function(errorMsg) {
alert("图表请求数据失败!");
myChart.hideLoading();
}
});
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>管理登录</title>
<link href="../static/images/favicon.ico" th:href="@{/favicon.ico}" rel="icon" type="image/x-ico">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
<link rel="stylesheet" th:href="@{/css/sign.css}"/>
<link rel="stylesheet" href="../../static/css/me.css" th:href="@{/css/me.css}">
<style>
body{ text-align:center}
#divcss5{margin:0 auto;border:1px solid #000;width:300px;height:100px}
</style>
</head>
<body>
<br>
<br>
<br>
<div class="m-container-small m-padded-tb-massive" style="max-width: 30em !important;">
<div class="ur container" >
<div class="ui middle aligned center aligned grid">
<div class="column">
<h2 class="ui teal image header">
<div class="content">
管理后台登录
</div>
</h2>
<form class="ui large form" method="post" action="#" th:action="@{userLogin}">
<div class="ui segment">
<div class="field">
<div class="ui left icon input">
<i class="user icon"></i>
<input type="text" name="username" placeholder="用户名">
</div>
</div>
<div class="field">
<div class="ui left icon input">
<i class="lock icon"></i>
<input type="password" name="password" placeholder="密码">
</div>
</div>
<button class="ui fluid large teal submit button">登 录</button>
</div>
<div class="ui error mini message"></div>
<div class="ui mini negative message"><span style="color: red" th:text="${loginMsg}" th:if="${not #strings.isEmpty(loginMsg)}"></span></div>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.js"></script>
<script>
$('.ui.form').form({
fields : {
username : {
identifier: 'username',
rules: [{
type : 'empty',
prompt: '请输入用户名'
}]
},
password : {
identifier: 'password',
rules: [{
type : 'empty',
prompt: '请输入密码'
}]
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>新增</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body class="container">
<br/>
<h1>添加用户</h1>
<br/><br/>
<div class="with:80%">
<form class="form-horizontal" th:action="@{/add}" method="post">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" id="name" placeholder="name" required/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label" >密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" id="password" placeholder="Password" required/>
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="age" id="age" placeholder="age" required/>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">真实姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="address" id="address" placeholder="address" required/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="提交" class="btn btn-info" />
<input type="reset" value="重置" class="btn btn-info" />
<a href="/toAdd" th:href="@{/list}" class="btn btn-info">返回</a>
</div>
</div>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>修改</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body class="container">
<br/>
<h1>修改用户</h1>
<br/><br/>
<div class="with:80%">
<form class="form-horizontal" th:action="@{/edit}" th:object="${user}" method="post">
<input type="hidden" name="id" th:value="*{id}" />
<div class="form-group">
<label for="name" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="name" id="name" th:value="*{name}" placeholder="name"/>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label" >密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" name="password" id="password" th:value="*{password}" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<label for="age" class="col-sm-2 control-label">年龄</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="age" id="age" th:value="*{age}" placeholder="age"/>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">真实姓名</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="address" id="address" th:value="*{address}" placeholder="address"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="提交" class="btn btn-info" />
<a href="/toAdd" th:href="@{/list}" class="btn btn-info">返回</a>
</div>
</div>
</form>
</div>
</body>
</html>
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--包含Spring boot对logback日志的默认配置-->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<!--重写了Spring Boot框架 org/springframework/boot/logging/logback/file-appender.xml 配置-->
<appender name="TIME_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i</fileNamePattern>
<!--保留历史日志一个月的时间-->
<maxHistory>30</maxHistory>
<!--
Spring Boot默认情况下,日志文件10M时,会切分日志文件,这样设置日志文件会在100M时切分日志
-->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="TIME_FILE" />
</root>
</configuration>
<!--
1、继承Spring boot logback设置(可以在appliaction.yml或者application.properties设置logging.*属性)
2、重写了默认配置,设置日志文件大小在100MB时,按日期切分日志,切分后目录:
blog.2017-08-01.0 80MB
blog.2017-08-01.1 10MB
blog.2017-08-02.0 56MB
blog.2017-08-03.0 53MB
......
-->