authorization

master
bseayin 2019-08-31 20:08:47 +08:00
parent 76b9ab3daa
commit 702cf6e2a4
38 changed files with 2101 additions and 1 deletions

View File

@ -0,0 +1,21 @@
package com.zz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* --run as application mainspringboot
SpringBoot tomcat main tomcat
* @author jiyu
*
*/
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,70 @@
package com.zz.controller;
import java.util.HashMap;
import java.util.Map;
import com.zz.entity.User;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("test")
public class TestController {
//路径传值
@RequestMapping("t1/{p1}")
public Map t1(@PathVariable("p1") String paramter1){
Map map=new HashMap();
map.put("rs",paramter1);
return map;
}
//? 传值
@RequestMapping("t2")
public Map t2(@RequestParam("p1") String paramter1)
{
System.out.println(paramter1);
Map map=new HashMap();
map.put("rs",paramter1);
return map;
}
//Body参数
//application/jason
@RequestMapping("t3")
public Map t3(@RequestBody User person){
Map map=new HashMap();
map.put("rs",person.getName());
return map;
}
// 无注解form提交
//form-data
@RequestMapping("t4")
public Map t4(User person){
Map map=new HashMap();
map.put("rs",person.getName());
return map;
}
// 请求头参数以及Cookie
@RequestMapping("t5")
public Map t5(@RequestHeader(name ="myHeader") String myHeader,
@CookieValue(name = "myCookie") String myCookie){
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
Map map=new HashMap();
map.put("rs",myHeader);
return map;
}
// 表单的参数写在Controller相应的方法的形参中
// 适用于get方式提交不适用于post方式提交。
@RequestMapping("t6")
public Map t6(String name,String pwd){
Map map=new HashMap();
map.put("rs",name);
return map;
}
}

View File

@ -0,0 +1,43 @@
package com.zz.entity;
public class User {
private String id;
private String name;
private String pwd;
private String sex;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

View File

@ -0,0 +1,134 @@
package com.zz.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.zz.entity.User;
import com.zz.util.JDBCComon;
@Service
public class UserService {
JDBCComon jdbc=new JDBCComon();
//登录
public User login(String name,String pwd){
User user=null;
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user where name='"+name+"' and pwd='"+pwd+"'";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
if(rss.next()){
user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
//验证用户名是否存在
public User checkName(String name){
User user=null;
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user where name='"+name+"' ";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
if(rss.next()){
user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public List<User> selectAll(){
List<User> ulist=new ArrayList();
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user ";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
while(rss.next()){
User user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
user.setAge(rss.getInt("age"));
ulist.add(user);
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ulist;
}
public boolean deleteById(String id){
Connection conn;
boolean flag=false;
try {
conn = jdbc.getConnection();
String sql="delete from user where id=?";
PreparedStatement st=conn.prepareStatement(sql);
st.setString(1, id);
if(st.executeUpdate()>0){
flag=true;
};
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}

View File

@ -0,0 +1,23 @@
package com.zz.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCComon {
public Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
//java10是数据库的名字
String url="jdbc:mysql://localhost:3306/java10?useSSL=false&serverTimezone=Asia/Shanghai";
//登录数据库用户名
String username="root";
//登录数据库密码
String pwd="Java20190713*yy";
Connection conn = DriverManager.getConnection(url,username,pwd);
return conn;
}
}

View File

@ -0,0 +1,70 @@
package com.zz.util;
import java.time.LocalDateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TimerDemo1 {
/**
* fixedRate
使
使
@Scheduled(fixedRate = 3000)
public void scheduledTask() {
System.out.println("Task executed at " + LocalDateTime.now());
}
*/
/**https://www.jianshu.com/p/73784dff0b0e
* Cron
96
2018.08.01 22:23* 580 201 0 1
Cron Spring @Scheduled
Cron 6 7 使
6 Cron
Seconds Minutes Hours DayofMonth Month DayofWeek
7 Cron
Seconds Minutes Hours DayofMonth Month DayofWeek Year
使
Seconds0~59 , - * /
Minutes Seconds
Hours0~23 , - * /
DayofMonth0~31 , - * / ? L W C
Month1~12 JAN ~ DEC , - * /
DayofWeek1~7 SUN ~ SAT , - * / ? L C # 1
Year1970~2099 , - * /
*/
/**
* (1) ,
Seconds 使 10,15,25 10 15 25
*/
@Scheduled(cron = "10,15,25 * * * * ?")
public void scheduledTask() {
System.out.println("Task executed at " + LocalDateTime.now());
}
//每个月的30号凌晨执行
@Scheduled(cron = "0 0 0 30 * ? ")
public void scheduledTask2() {
System.out.println("Task executed at " + LocalDateTime.now());
}
}

View File

@ -25,6 +25,20 @@
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version> <version>8.0.15</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
</dependencies> </dependencies>
<repositories> <repositories>

View File

@ -0,0 +1,30 @@
package com.zz.excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* @Description: java
* @Author: Bsea
* @CreateDate: 2019/8/26$ 20:55$
*/
public class Demo1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个excel文件
HSSFWorkbook wb= new HSSFWorkbook();
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("c:\\tmp1\\workbook2019.xls");
wb.write(fileOut);
fileOut.close();
} catch ( IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// FileOutputStream fileOut= new FileOutputStream("c:/workbook.xls");
}
}

View File

@ -0,0 +1,56 @@
package com.zz.excel;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* @Description: java
* @Author: Bsea
* @CreateDate: 2019/8/26$ 20:58$
*/
public class Demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
HSSFWorkbook wb = new HSSFWorkbook(); //建立新HSSFWorkbook对象
HSSFSheet sheet = wb.createSheet("java10"); //建立新的sheet对象
HSSFRow row = sheet.createRow((short)0);
//在sheet里创建一行参数为行号第一行此处可想象成数组
HSSFCell cell = row.createCell((short)0);
//在row里建立新cell单元格参数为列号第一列
cell.setCellValue("2019");
//cell.set
//设置cell的整数类型的值
row.createCell((short)1).setCellValue(1.2); //设置cell浮点类型的值
row.createCell((short)2).setCellValue("test"); //设置cell字符类型的值
row.createCell((short)3).setCellValue(true); //设置cell布尔类型的值
HSSFCellStyle cellStyle = wb.createCellStyle(); //建立新的cell样式
cellStyle.setDataFormat(HSSFDataFormat. getBuiltinFormat("m/d/yy h:mm"));
//设置cell样式为定制的日期格式
HSSFCell dCell =row.createCell((short)4);
dCell.setCellValue(new Date()); //设置cell为日期类型的值
dCell.setCellStyle(cellStyle); //设置该cell日期的显示格式
HSSFCell csCell =row.createCell((short)5);
//csCell.setEncoding(HSSFCell.ENCODING_UTF_16);
//设置cell编码解决中文高位字节截断
csCell.setCellValue("中文测试_Chinese Words Test"); //设置中西文结合字符串
row.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_ERROR);
//建立错误cell
try {
FileOutputStream fileOut = new FileOutputStream("c:\\tmp1\\workbook1.xls");
wb.write(fileOut);
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,229 @@
package com.zz.excel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @Description: java
* @Author: Bsea
* @CreateDate: 2019/8/26$ 21:29$
*/
public class Demoxlsx {
public static void main(String[] args) throws IOException, InvalidFormatException {
String xlsPath = "C:/tmp1/测试.xlsx";
// excel文档对象
XSSFWorkbook wk = new XSSFWorkbook();
// sheet对象
XSSFSheet sheet = wk.createSheet("测试");
// 字体样式
XSSFFont xssfFont = wk.createFont();
// 加粗
xssfFont.setBold(true);
// 字体名称
xssfFont.setFontName("楷体");
// 字体大小
xssfFont.setFontHeight(12);
// 表头样式
XSSFCellStyle headStyle = wk.createCellStyle();
// 设置字体css
headStyle.setFont(xssfFont);
// 竖向居中
headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
headStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
// headStyle.setBorderBottom(Borde*rStyle.THIN);
headStyle.setBorderLeft(BorderStyle.THIN);
headStyle.setBorderRight(BorderStyle.THIN);
headStyle.setBorderTop(BorderStyle.THIN);
// 内容字体样式
XSSFFont contFont = wk.createFont();
// 加粗
contFont.setBold(false);
// 字体名称
contFont.setFontName("楷体");
// 字体大小
contFont.setFontHeight(11);
// 内容样式
XSSFCellStyle contentStyle = wk.createCellStyle();
// 设置字体css
contentStyle.setFont(contFont);
// 竖向居中
contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
//contentStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
contentStyle.setBorderBottom(BorderStyle.THIN);
contentStyle.setBorderLeft(BorderStyle.THIN);
contentStyle.setBorderRight(BorderStyle.THIN);
contentStyle.setBorderTop(BorderStyle.THIN);
// 自动换行
contentStyle.setWrapText(true);
// 数字样式
XSSFCellStyle numStyle = wk.createCellStyle();
// 设置字体css
numStyle.setFont(contFont);
// 竖向居中
numStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
numStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
numStyle.setBorderBottom(BorderStyle.THIN);
numStyle.setBorderLeft(BorderStyle.THIN);
numStyle.setBorderRight(BorderStyle.THIN);
numStyle.setBorderTop(BorderStyle.THIN);
// 标题字体样式
XSSFFont titleFont = wk.createFont();
// 加粗
titleFont.setBold(false);
// 字体名称
titleFont.setFontName("宋体");
// 字体大小
titleFont.setFontHeight(16);
// 标题样式
XSSFCellStyle titleStyle = wk.createCellStyle();
titleStyle.setFont(titleFont);
// 竖向居中
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 横向居中
titleStyle.setAlignment(HorizontalAlignment.CENTER);
// 边框
titleStyle.setBorderBottom(BorderStyle.THIN);
titleStyle.setBorderLeft(BorderStyle.THIN);
titleStyle.setBorderRight(BorderStyle.THIN);
titleStyle.setBorderTop(BorderStyle.THIN);
// 合并单元格(第一行、标题)
CellRangeAddress cAddress = new CellRangeAddress(0, 0, 0, 3);
sheet.addMergedRegion(cAddress);
// 合并单元格(第一个分类)
CellRangeAddress cAddress2 = new CellRangeAddress(2, 3, 0, 0);
sheet.addMergedRegion(cAddress2);
// 创建第一行
XSSFRow row1 = sheet.createRow(0);
// 创建第一行第一列
XSSFCell row1Cell1 = row1.createCell(0);
row1Cell1.setCellValue("title");
row1Cell1.setCellStyle(titleStyle);
XSSFCell row1Cell2 = row1.createCell(1);
// 为了保证合并的单元格能有效追加外框、被合并的单元格、内容要设置为空
row1Cell2.setCellValue("");
row1Cell2.setCellStyle(titleStyle);
XSSFCell row1Cell3 = row1.createCell(2);
row1Cell3.setCellValue("");
row1Cell3.setCellStyle(titleStyle);
XSSFCell row1Cell4 = row1.createCell(3);
row1Cell4.setCellValue("");
row1Cell4.setCellStyle(titleStyle);
// 创建第二行
XSSFRow row2 = sheet.createRow(1);
// 创建第二行第一列
XSSFCell row2Cell1 = row2.createCell(0);
row2Cell1.setCellValue("分类");
row2Cell1.setCellStyle(headStyle);
// 列宽
sheet.setColumnWidth(row2Cell1.getColumnIndex(), 60 * 50);
// 创建第二行第二列
XSSFCell row2Cell2 = row2.createCell(1);
row2Cell2.setCellValue("内容");
row2Cell2.setCellStyle(headStyle);
// 列宽
sheet.setColumnWidth(row2Cell2.getColumnIndex(), 356 * 50);
// 创建第二行第三列
XSSFCell row2Cell3 = row2.createCell(2);
row2Cell3.setCellValue("标准");
row2Cell3.setCellStyle(headStyle);
// 列宽
sheet.setColumnWidth(row2Cell3.getColumnIndex(), 70 * 50);
// 创建第二行第四列
XSSFCell row2Cell4 = row2.createCell(3);
row2Cell4.setCellValue("备注");
row2Cell4.setCellStyle(headStyle);
// 列宽
sheet.setColumnWidth(row2Cell4.getColumnIndex(), 70 * 50);
// 创建第三行
XSSFRow row3 = sheet.createRow(2);
// 创建第三行第一列
XSSFCell row3Cell1 = row3.createCell(0);
row3Cell1.setCellValue("分类1");
row3Cell1.setCellStyle(contentStyle);
// 创建第三行第二列
XSSFCell row3Cell2 = row3.createCell(1);
row3Cell2.setCellValue("AAAAAAAAAAAAAAAAAAAAAA");
row3Cell2.setCellStyle(contentStyle);
// 创建第三行第三列
XSSFCell row3Cell3 = row3.createCell(2);
row3Cell3.setCellValue(10);
row3Cell3.setCellStyle(numStyle);
// 创建第三行第四列
XSSFCell row3Cell4 = row3.createCell(3);
row3Cell4.setCellValue(6);
row3Cell4.setCellStyle(numStyle);
// 创建第四行
XSSFRow row4 = sheet.createRow(3);
// 创建第四行第一列
XSSFCell row4Cell1 = row4.createCell(0);
row4Cell1.setCellValue("");
row4Cell1.setCellStyle(contentStyle);
// 创建第四行第二列
XSSFCell row4Cell2 = row4.createCell(1);
row4Cell2.setCellValue("BBBBBBBBBBBBBBBBBBBBBBBBBBBB");
row4Cell2.setCellStyle(contentStyle);
// 创建第四行第三列
XSSFCell row4Cell3 = row4.createCell(2);
row4Cell3.setCellValue(10);
row4Cell3.setCellStyle(numStyle);
// 创建第四行第四列
XSSFCell row4Cell4 = row4.createCell(3);
row4Cell4.setCellValue(6);
row4Cell4.setCellStyle(numStyle);
// 创建第五行
XSSFRow row5 = sheet.createRow(4);
// 创建第五行第一列
XSSFCell row5Cell1 = row5.createCell(0);
row5Cell1.setCellValue("分类2");
row5Cell1.setCellStyle(contentStyle);
// 创建第五行第二列
XSSFCell row5Cell2 = row5.createCell(1);
row5Cell2.setCellValue("CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC");
row5Cell2.setCellStyle(contentStyle);
// 创建第五行第三列
XSSFCell row5Cell3 = row5.createCell(2);
row5Cell3.setCellValue(10);
row5Cell3.setCellStyle(numStyle);
// 创建第五行第四列
XSSFCell row5Cell4 = row5.createCell(3);
row5Cell4.setCellValue(6);
row5Cell4.setCellStyle(numStyle);
FileOutputStream outputStream = new FileOutputStream(xlsPath);
wk.write(outputStream);
outputStream.flush();
}
}

View File

@ -0,0 +1,142 @@
package com.zz.excel;
/**
* @Description: java
* @Author: Bsea
* @CreateDate: 2019/8/26$ 21:35$
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
* excel */
public class POIUtil {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* excel
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException{
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//把数字当成String来读避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}

View File

@ -0,0 +1,21 @@
package com.zz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* --run as application mainspringboot
SpringBoot tomcat main tomcat
* @author jiyu
*
*/
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,21 @@
package com.zz.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* controller
* 1 @RestController json
* 2 @Controller
* @author jiyu
*
*/
@Controller
public class IndexController {
@RequestMapping("ddd")
public String toIndex(){
return "index.html";
}
}

View File

@ -0,0 +1,28 @@
package com.zz.controller;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Slf4j
public class TestController {
@RequestMapping("hello")
public String t1()
{
log.info("t1 comming");
return "hello SpringBoot";
}
@RequestMapping("test2")
public Map t2(){
// 多态
//变量类型是父类,构造方法是子类
Map map=new HashMap();
map.put("key1", "你好");
return map;
}
}

View File

@ -0,0 +1,35 @@
package com.zz.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zz.entity.User;
import com.zz.service.UserService;
@RestController
public class UserController {
@RequestMapping("all")
public List<User> getAll(){
UserService us=new UserService();
List<User> userlist=us.selectAll();
return userlist;
}
@RequestMapping("delete")
public Map remove(HttpServletRequest request){
UserService us=new UserService();
String id=request.getParameter("uid");
boolean rs=us.deleteById(id);
Map map=new HashMap();
map.put("result", rs);
return map;
}
}

View File

@ -0,0 +1,41 @@
package com.zz.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zz.entity.User;
import com.zz.service.UserService;
@RestController
//在类的上面,配置一个拦截路径,那么这个类里面所有方法的
//路径前面必须加上这个us2. 避免和其他类的路径重复
@RequestMapping("us2")
public class UserController2 {
//使用spring的ioc 控制反转。让spring容器帮我们创建对象
@Resource
UserService us;
//拦截路径是http://localhost:9080/a/us2/all
@RequestMapping("all")
public List<User> getAll(){
List<User> userlist=us.selectAll();
return userlist;
}
@RequestMapping("delete")
public Map remove(HttpServletRequest request){
String id=request.getParameter("uid");
boolean rs=us.deleteById(id);
Map map=new HashMap();
map.put("result", rs);
return map;
}
}

View File

@ -0,0 +1,17 @@
package com.zz.entity;
import lombok.Data;
@Data
public class User {
private String id;
private String name;
private String pwd;
private String sex;
private int age;
}

View File

@ -0,0 +1,134 @@
package com.zz.service;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;
import com.zz.entity.User;
import com.zz.util.JDBCComon;
@Service
public class UserService {
JDBCComon jdbc=new JDBCComon();
//登录
public User login(String name,String pwd){
User user=null;
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user where name='"+name+"' and pwd='"+pwd+"'";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
if(rss.next()){
user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
//验证用户名是否存在
public User checkName(String name){
User user=null;
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user where name='"+name+"' ";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
if(rss.next()){
user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
public List<User> selectAll(){
List<User> ulist=new ArrayList();
try {
Connection conn=jdbc.getConnection();
Statement st=conn.createStatement();
String sql="select * from user ";
System.out.println("sql--->"+sql);
ResultSet rss=st.executeQuery(sql);
//rss.next()只要 结果集合里至少有一条记录next方法就会返回true
while(rss.next()){
User user=new User();
user.setId(rss.getString("id"));
user.setName(rss.getString("name"));
user.setAge(rss.getInt("age"));
ulist.add(user);
}
//从下往上关
rss.close();
st.close();
conn.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ulist;
}
public boolean deleteById(String id){
Connection conn;
boolean flag=false;
try {
conn = jdbc.getConnection();
String sql="delete from user where id=?";
PreparedStatement st=conn.prepareStatement(sql);
st.setString(1, id);
if(st.executeUpdate()>0){
flag=true;
};
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}

View File

@ -0,0 +1,23 @@
package com.zz.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCComon {
public Connection getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.cj.jdbc.Driver");
//java10是数据库的名字
String url="jdbc:mysql://localhost:3306/java10?useSSL=false&serverTimezone=Asia/Shanghai";
//登录数据库用户名
String username="root";
//登录数据库密码
String pwd="Java20190713*yy";
Connection conn = DriverManager.getConnection(url,username,pwd);
return conn;
}
}

View File

@ -0,0 +1,70 @@
package com.zz.util;
import java.time.LocalDateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class TimerDemo1 {
/**
* fixedRate
使
使
@Scheduled(fixedRate = 3000)
public void scheduledTask() {
System.out.println("Task executed at " + LocalDateTime.now());
}
*/
/**https://www.jianshu.com/p/73784dff0b0e
* Cron
96
2018.08.01 22:23* 580 201 0 1
Cron Spring @Scheduled
Cron 6 7 使
6 Cron
Seconds Minutes Hours DayofMonth Month DayofWeek
7 Cron
Seconds Minutes Hours DayofMonth Month DayofWeek Year
使
Seconds0~59 , - * /
Minutes Seconds
Hours0~23 , - * /
DayofMonth0~31 , - * / ? L W C
Month1~12 JAN ~ DEC , - * /
DayofWeek1~7 SUN ~ SAT , - * / ? L C # 1
Year1970~2099 , - * /
*/
/**
* (1) ,
Seconds 使 10,15,25 10 15 25
*/
@Scheduled(cron = "10,15,25 * * * * ?")
public void scheduledTask() {
System.out.println("Task executed at " + LocalDateTime.now());
}
//每个月的30号凌晨执行
@Scheduled(cron = "0 0 0 30 * ? ")
public void scheduledTask2() {
System.out.println("Task executed at " + LocalDateTime.now());
}
}

View File

@ -0,0 +1,2 @@
server.port=9089
server.servlet.context-path=/lombok

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello controller
</body>
</html>

View File

@ -0,0 +1,84 @@
$(document).ready(function(){
// 在这里写你的代码...
$.getJSON("all", function(json){
console.log(json);
$("#tbodymainbtn").empty();
for(var i=0;i<json.length;i++){
$("#tbodymainbtn").append(
"<tr id='tridval"+i+"'>"
+"<td>"+ json[i].id
+"</td>"
+"<td>"+ json[i].name
+"</td>"
+"<td>"+ json[i].age
+"</td>"
+"<td><button type='button' name='btn001' class='btn btn-info btn-sm' id='btn1"+i+"'>修改</button>" +"&nbsp&nbsp&nbsp<button type='button' name='btn003' class='btn btn-danger btn-sm' id='btn3"+json[i].id +"'>删除</button>"
+"</td></tr>"
);
$("#tbodymainbtn").append(
"<tr style='display:none' id='tridval2"+i+"'><form>"
+"<td><input type='text' value='"+ json[i].id
+"'/></td>"
+"<td><input type='text' id='name2"+i+"' value='"+ json[i].name
+"'/></td>"
+"<td><input type='text' id='age2"+i+"' value='"+ json[i].age
+"'/></td>"
+"<td><button type='button' name='btn002' class='btn btn-primary btn-sm' id='btn2"+i+"'>保存</button>"
+"</td></form></tr>"
);
}
//jquery 样式查找 “点+样式名字”
$("button[name='btn001']").click(function(){
var id=this.id;
//截取剩余
var numb = id.slice(4);
console.log("****************"+id);
$("#tridval"+numb).hide();
$("#tridval2"+numb).show();
});
$("button[name='btn002']").click(function(){
var id=this.id;
//截取剩余
var numb = id.slice(4);
console.log("****************"+id);
var nval=$("#name2"+numb).val();
var aval=$("#age2"+numb).val();
console.log("********name2********"+nval);
console.log("********age2********"+aval);
$("#tridval"+numb).show();
$("#tridval2"+numb).hide();
});
$("button[name='btn003']").click(function(){
var id=this.id;
//截取剩余
var numb = id.slice(4);
console.log("****************"+id);
console.log("****************"+numb);
$.getJSON("delete", { uid: numb}, function(json){
console.log("******delete**********"+numb,json);
window.location.href="table.html"
});
});
});//$.getJSON("UserServlet", function(json){
});

View File

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<title>用户管理</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>用户管理</h2>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
</thead>
<tbody id="tbodymainbtn">
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="js/table.js"></script>
</body>
</html>

View File

@ -0,0 +1,21 @@
package com.zz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* --run as application mainspringboot
SpringBoot tomcat main tomcat
* @author jiyu
*
*/
@SpringBootApplication
@EnableScheduling
public class App {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,97 @@
package com.zz.config;
import java.util.LinkedHashMap;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/login");
shiroFilterFactoryBean.setSuccessUrl("/index");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
filterChainDefinitionMap.put("/css/**", "anon");
filterChainDefinitionMap.put("/js/**", "anon");
filterChainDefinitionMap.put("/register.html", "anon");
filterChainDefinitionMap.put("/fonts/**", "anon");
filterChainDefinitionMap.put("/img/**", "anon");
filterChainDefinitionMap.put("/druid/**", "anon");
filterChainDefinitionMap.put("/logout", "logout");
filterChainDefinitionMap.put("/user/register", "anon");
filterChainDefinitionMap.put("/", "anon");
filterChainDefinitionMap.put("/**", "user");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
@Bean
public SecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
securityManager.setRememberMeManager(rememberMeManager());
return securityManager;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public ShiroRealm shiroRealm(){
ShiroRealm shiroRealm = new ShiroRealm();
return shiroRealm;
}
/**
* cookie
* @return
*/
public SimpleCookie rememberMeCookie() {
// 设置cookie名称对应login.html页面的<input type="checkbox" name="rememberMe"/>
SimpleCookie cookie = new SimpleCookie("rememberMe");
// 设置cookie的过期时间单位为秒这里为一天
cookie.setMaxAge(86400);
return cookie;
}
/**
* cookie
* @return
*/
public CookieRememberMeManager rememberMeManager() {
//Cookie 数据存在客户端的浏览器
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
// rememberMe cookie加密的密钥
cookieRememberMeManager.setCipherKey(Base64.decode("3AvVhmFLUs0KTA3Kprsdag=="));
return cookieRememberMeManager;
}
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}

View File

@ -0,0 +1,95 @@
package com.zz.config;
import javax.annotation.Resource;
import com.zz.entity.Permission;
import com.zz.entity.Role;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import com.zz.entity.User;
import com.zz.repository.UserRepository;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
//import com.springboot.dao.UserMapper;
//import com.springboot.pojo.User;
@Slf4j
public class ShiroRealm extends AuthorizingRealm {
@Resource
private UserRepository userRepository;
/**
*
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
String userName = user.getUsername();
System.out.println("用户" + userName + "获取权限-----ShiroRealm.doGetAuthorizationInfo");
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 获取用户角色集
Set<String> roleSet = new HashSet<String>();
Set<Permission> permissionList= new HashSet<Permission>();
Set<Role> roles=user.getRoles();
for (Role r : roles) {
roleSet.add(r.getName());
permissionList.addAll(r.getPermissions());
}
simpleAuthorizationInfo.setRoles(roleSet);
// 获取用户权限集
Set<String> permissionSet = new HashSet<String>();
for (Permission p : permissionList) {
permissionSet.add(p.getName());
}
simpleAuthorizationInfo.setStringPermissions(permissionSet);
return simpleAuthorizationInfo;
}
/**
*
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName = (String) token.getPrincipal();
String password = new String((char[]) token.getCredentials());
System.out.println("用户" + userName + "认证-----ShiroRealm.doGetAuthenticationInfo");
// User user = userMapper.findByUserName(userName);
User user = userRepository.findByUsername(userName);
// User user=new User();
if (user == null) {
throw new UnknownAccountException("用户名错误!");
}
//1. MD5加密不可以破解
//2. 登录比较的是,两个密文
if (!password.equals(user.getPasswd())) {
throw new IncorrectCredentialsException("密码错误!");
}
if (user.getStatus().equals("0")) {
throw new LockedAccountException("账号已被锁定,请联系管理员!");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
return info;
}
}

View File

@ -0,0 +1,68 @@
package com.zz.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zz.entity.User;
import com.zz.pojo.ResponseBo;
import com.zz.util.MD5Utils;
@Controller
public class LoginController {
@GetMapping("/login")
public String login() {
return "login1.html";
}
@PostMapping("/login")
@ResponseBody
public ResponseBo login(String username, String password, Boolean rememberMe) {
password = MD5Utils.encrypt(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
return ResponseBo.ok();
} catch (UnknownAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (IncorrectCredentialsException e) {
return ResponseBo.error(e.getMessage());
} catch (LockedAccountException e) {
return ResponseBo.error(e.getMessage());
} catch (AuthenticationException e) {
return ResponseBo.error("认证失败!");
}
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index1.html";
}
@PostMapping("/getlogin")
@ResponseBody
public User getLoginUser(){
return (User) SecurityUtils.getSubject().getPrincipal();
}
}

View File

@ -0,0 +1,87 @@
package com.zz.controller;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zz.entity.User;
import com.zz.pojo.ResponseBo;
import com.zz.service.UserService;
import com.zz.util.KeyUtil;
import com.zz.util.MD5Utils;
@Controller
@RequestMapping("/user")
public class UserController {
@RequiresPermissions("user:user")
@RequestMapping("list")
public String userList() {
return "/index1.html";
}
@RequiresPermissions("user:add")
@RequestMapping("add")
public String userAdd(Model model) {
model.addAttribute("value", "新增用户");
return "/index1.html";
}
@RequiresPermissions("user:delete")
@RequestMapping("delete")
public String userDelete(Model model) {
model.addAttribute("value", "删除用户");
return "/index1.html";
}
@Resource
UserService userService;
@GetMapping("/register")
public String login() {
return "register.html";
}
@PostMapping("/register")
@ResponseBody
public ResponseBo register(User user) {
String password = MD5Utils.encrypt(user.getUsername(), user.getPasswd());
user.setPasswd(password);
user.setId(KeyUtil.genUniqueKey());
userService.save(user);
return ResponseBo.ok();
}
@RequestMapping("/")
public String redirectIndex() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index(Model model) {
User user = (User) SecurityUtils.getSubject().getPrincipal();
model.addAttribute("user", user);
return "index1.html";
}
@PostMapping("/getlogin")
@ResponseBody
public User getLoginUser(){
return (User) SecurityUtils.getSubject().getPrincipal();
}
}

View File

@ -0,0 +1,93 @@
package com.zz.entity;
import lombok.Data;
import org.hibernate.annotations.Proxy;
import java.io.Serializable;
import java.sql.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="T_USER")
@Proxy(lazy = false)
public class User implements Serializable{
@Id
@Column(length = 50)
private String id;
//用户名
private String username;
private String passwd;
//是否有效 1有效 0锁定
private String status;
//创建时间
private Date createTime;
//使用 @ManyToMany 注解来映射多对多关联关系
//使用 @JoinTable 来映射中间表
//1. name 指向中间表的名字
//2. joinColumns 映射当前类所在的表在中间表中的外键
//2.1 name 指定外键列的列名
//2.2 referencedColumnName 指定外键列关联当前表的哪一列
//3. inverseJoinColumns 映射关联的类所在中间表的外键
// @ManyToMany注释表示Teacher是多对多关系的一端。
// @JoinTable描述了多对多关系的数据表关系。name属性指定中间表名称joinColumns定义中间表与Teacher表的外键关系。
// 中间表Teacher_Student的Teacher_ID列是Teacher表的主键列对应的外键列inverseJoinColumns属性定义了中间表与另外一端(Student)的外键关系。
@ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER)
@JoinTable(name = "T_USER_ROLE", joinColumns = { @JoinColumn(name = "u_id") },
inverseJoinColumns = {
@JoinColumn(name = "r_id") })
private Set<Role> roles = new HashSet<Role>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}

View File

@ -0,0 +1,50 @@
package com.zz.pojo;
import java.util.HashMap;
import java.util.Map;
public class ResponseBo extends HashMap<String, Object>{
private static final long serialVersionUID = 1L;
public ResponseBo() {
put("code", 0);
put("msg", "操作成功");
}
public static ResponseBo error() {
return error(1, "操作失败");
}
public static ResponseBo error(String msg) {
return error(500, msg);
}
public static ResponseBo error(int code, String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("code", code);
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(String msg) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.put("msg", msg);
return ResponseBo;
}
public static ResponseBo ok(Map<String, Object> map) {
ResponseBo ResponseBo = new ResponseBo();
ResponseBo.putAll(map);
return ResponseBo;
}
public static ResponseBo ok() {
return new ResponseBo();
}
@Override
public ResponseBo put(String key, Object value) {
super.put(key, value);
return this;
}
}

View File

@ -0,0 +1,14 @@
package com.zz.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import com.zz.entity.User;
public interface UserRepository extends JpaRepository<User,String>{
public User findByUsername(String name);
}

View File

@ -0,0 +1,31 @@
package com.zz.service;
import javax.annotation.Resource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import com.zz.entity.User;
import com.zz.repository.UserRepository;
@Service
public class UserService {
@Resource
UserRepository userRepository;
public User save(User user){
return userRepository.save(user);
};
public Page<User> findAll(String page, String limit){
Pageable pageable = PageRequest.of(Integer.parseInt(page), Integer.parseInt(limit));
Page<User> pageinfo=userRepository.findAll(pageable);
return pageinfo;
}
}

View File

@ -0,0 +1,16 @@
package com.zz.util;
import java.util.Random;
public class KeyUtil {
/**
*
* : +
* @return
*/
public static String genUniqueKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;
return System.currentTimeMillis() + String.valueOf(number);
}
}

View File

@ -0,0 +1,29 @@
package com.zz.util;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
public class MD5Utils {
private static final String SALT = "zzjava10";
private static final String ALGORITH_NAME = "md5";
private static final int HASH_ITERATIONS = 2;
public static String encrypt(String pswd) {
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
return newPassword;
}
public static String encrypt(String username, String pswd) {
//加盐密码
String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username + SALT),
HASH_ITERATIONS).toHex();
return newPassword;
}
public static void main(String[] args) {
System.out.println(MD5Utils.encrypt("test", "123456"));
}
}

View File

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 实例</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>基础表格</h2>
<p id="info"></p>
<table class="table">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@example.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@example.com</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$.post("/r/getlogin",
function(data){
console.log(data); // 2pm
var loginname=data.name;
$("#info").text(loginname);
}, "json");
</script>
</body>
</html>

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 实例</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>堆叠表单</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" name='rememberMe' type="checkbox"> Remember me
</label>
</div>
<button type="button" id="subtn" class="btn btn-primary">Submit</button>
</form>
</div>
<script type="text/javascript">
$("#subtn").click(function(){
var rememberMe =$("input[name='rememberMe']").is(':checked');
$.post("/r/login", { "username": $("#email").val(),"password": $("#pwd").val(),"rememberMe": rememberMe },
function(data){
console.log(data); //
window.location.href="index1.html";
}, "json");
});
</script>
</body>
</html>

View File

@ -0,0 +1,47 @@
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 实例</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.12.5/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>堆叠表单</h2>
<form>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" placeholder="Enter password">
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" name='rememberMe' type="checkbox"> Remember me
</label>
</div>
<button type="button" id="subtn" class="btn btn-primary">Submit</button>
</form>
</div>
<script type="text/javascript">
$("#subtn").click(function(){
$.post("/r/user/register", { "username": $("#email").val(),"passwd": $("#pwd").val()},
function(data){
console.log(data); //
window.location.href="index1.html";
}, "json");
});
</script>
</body>
</html>