authorization

master
bseayin 2019-09-15 21:36:46 +08:00
parent 9b704c9eed
commit 7a549bb5bd
14 changed files with 804 additions and 0 deletions

View File

@ -0,0 +1,12 @@
package com.cy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootHomeworkApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootHomeworkApplication.class, args);
}
}

View File

@ -0,0 +1,195 @@
package com.cy.controller;
import com.cy.entity.Homework;
import com.cy.entity.HomeworkRankDTO;
import com.cy.entity.HomeworkUserDTO;
import com.cy.repository.DTODao;
import com.cy.service.HomeworkService;
import com.cy.utils.KeyUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.Array;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("homework")
public class HomeworkController {
@Resource
HomeworkService hs;
@Resource
DTODao dd;
@Value("${fileUpLoadPath}")
String filePath;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
@RequestMapping("showByType/{type}")
public List<Homework> showByType(@PathVariable("type") String type) {
java.util.Date d1 = new java.util.Date();
if (d1.getHours() <= 11 && "竞赛".equals(type)) {
Date datesql = new Date(d1.getTime());
return hs.findByTypeAndFinishTime(type, datesql);
} else if (d1.getHours() >= 12 && "结对".equals(type)) {
Date datesql2 = new Date(d1.getTime());
return hs.findByTypeAndFinishTime(type, datesql2);
} else {
return null;
}
}
@RequestMapping("showByTypeAndFinishTime")
public List<Homework> showByTypeAndFinishTime(HttpServletRequest request) {
String type = request.getParameter("type");
java.util.Date d1 = null;
try {
d1 = sdf.parse(request.getParameter("finishTime"));
} catch (ParseException e) {
e.printStackTrace();
}
Date d2 = new Date(d1.getTime());
return hs.findByTypeAndFinishTime(type, d2);
}
@RequestMapping("showByTypeAndFinishTime/{page}")
public Iterable<Homework> showByTypeAndFinishTime(@PathVariable("page") String page, HttpServletRequest request) {
Pageable pageable = new PageRequest(Integer.parseInt(page), 10);
String type = request.getParameter("type");
java.util.Date d1 = null;
try {
d1 = sdf.parse(request.getParameter("finishTime"));
} catch (ParseException e) {
e.printStackTrace();
}
Date d2 = new Date(d1.getTime());
return hs.findByTypeAndFinishTime(type, d2, pageable);
}
@RequestMapping("save")
public Homework save(@RequestBody Homework homework) {
homework.setId(KeyUtils.genUniqueKey());
homework.setUpdateTime(new Date(new java.util.Date().getTime()));
return hs.save(homework);
}
@RequestMapping("findAllById/{id}")
public List<Homework> findAllById(@PathVariable("id") String id) {
return hs.findAllById(id);
}
@RequestMapping("update")
public Homework update(@RequestBody Homework homework) {
return hs.update(homework);
}
@RequestMapping("deleteById/{id}")
public Map deleteById(@PathVariable("id") String id) {
Map map = new HashMap();
hs.deleteById(id);
if (hs.findAllById(id).size() == 0) {
map.put("rs", "success");
} else {
map.put("rs", "fail");
}
return map;
}
@RequestMapping("showdetails/{id}")
public ArrayList<HomeworkUserDTO> showdetails(@PathVariable("id") String hid) {
return hs.gethomeworkdetail(hs.findAllById(hid).get(0));
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map upload(@RequestParam MultipartFile myFile, HttpSession session) throws IOException {
String originalFilename = myFile.getOriginalFilename();
int pos = originalFilename.lastIndexOf(".");
String suffix = originalFilename.substring(pos);
String uuid = UUID.randomUUID().toString();
String fullPath = filePath + File.separator + uuid + suffix;
String homeworkid = File.separator + uuid + suffix;
InputStream in = null;
try {
in = myFile.getInputStream();
OutputStream out = new FileOutputStream(new File(fullPath));
int len = 0;
byte[] buf = new byte[3 * 1024];
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Map map = new HashMap();
map.put("result", homeworkid);
return map;
}
@RequestMapping(value = "/download/{homeworkid}", method = RequestMethod.GET)
public void downLoad(@PathVariable("homeworkid") String homeworkid, HttpServletResponse response) {
List<Map<String, Object>> list = dd.queryfindhomework(homeworkid);
for (int i=0;i<list.size();i++){
String fileName = (String)list.get(i).get("homeworkid");
String fullPath = filePath + File.separator + fileName;
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名;
//response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GBK"),"ISO-8859-1"));
try {
File downloadFile = new File(fullPath);
FileInputStream inputStream = new FileInputStream(downloadFile);
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@RequestMapping("saveDetails/{uid}/{hid}/{result}")
public Map saveDetails(@PathVariable("uid") String uid, @PathVariable("hid") String hid, @PathVariable("result") String homeworkid) {
Map map = new HashMap();
int rs = hs.savedetails(uid, hid, homeworkid);
if (rs > 0) {
map.put("rs", "success");
} else if (rs == -1) {
map.put("rs", "outtime");
} else {
map.put("rs", "fail");
}
return map;
}
@RequestMapping("rank/{type}")
public ArrayList<HomeworkRankDTO> rank(@PathVariable("type") String type) {
return hs.getRank(type);
}
}

View File

@ -0,0 +1,92 @@
package com.cy.controller;
import com.cy.entity.User;
import com.cy.service.UserService;
import com.cy.utils.KeyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class UserController {
//使用SpringIOC控制反转让spring容器创建对象
//userservice上添加@Service注解
@Resource
UserService us;
@RequestMapping("register")
public Object save(@RequestBody User user) {
user.setId(KeyUtils.genUniqueKey());
if (us.save(user) != null) {
return "success";
} else {
return "fail";
}
}
@RequestMapping("checkName")
@ResponseBody
public Map checkName(HttpServletRequest request) {
String username = request.getParameter("username");
List<User> user = us.findByName(username);
boolean result = false;
if (user.size() > 0) {
result = true;
}
Map map = new HashMap();
map.put("result", result);
return map;
}
@RequestMapping("login")
public User login(@RequestBody User user,HttpServletRequest request) {
String loginName = user.getUsername();
String password = user.getPassword();
User user1 = us.findByNameAndPassword(loginName, password);
if (user1 != null) {
HttpSession session = request.getSession();
session.setAttribute("currentuser",user1);
return user1;
} else {
return null;
}
}
@RequestMapping("showId")
public Map showId(HttpServletRequest request) {
Map map = new HashMap();
HttpSession session = request.getSession();
User currentuser = (User)session.getAttribute("currentuser");
map.put("username",currentuser.getUsername());
map.put("id",currentuser.getId());
map.put("type",currentuser.getType());
return map;
}
@RequestMapping("setId")
public Map setId(HttpServletRequest request){
Map map = new HashMap();
map.put("rs","y");
String name = request.getParameter("username");
String id = request.getParameter("id");
String type = request.getParameter("type");
HttpSession session = request.getSession();
session.setAttribute("username",name);
session.setAttribute("id",id);
session.setAttribute("type",type);
return map;
}
}

View File

@ -0,0 +1,66 @@
package com.cy.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.sql.Date;
@Entity
public class Homework {
@Id
@Column(length = 80)
private String id;
private String title;
private String type;
private Date updateTime;
private Date finishTime;
private String details;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public Date getFinishTime() {
return finishTime;
}
public void setFinishTime(Date finishTime) {
this.finishTime = finishTime;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}

View File

@ -0,0 +1,31 @@
package com.cy.entity;
public class HomeworkRankDTO {
private String username;
private String ac;
private String type;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAc() {
return ac;
}
public void setAc(String ac) {
this.ac = ac;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

View File

@ -0,0 +1,63 @@
package com.cy.entity;
import java.sql.Date;
public class HomeworkUserDTO {
private String id;
private String username;
private String hid;
private String completeTime;
private String status;
private String homeworkid;
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 getHid() {
return hid;
}
public void setHid(String hid) {
this.hid = hid;
}
public String getCompleteTime() {
return completeTime;
}
public void setCompleteTime(String completeTime) {
this.completeTime = completeTime;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getHomeworkid() {
return homeworkid;
}
public void setHomeworkid(String homeworkid) {
this.homeworkid = homeworkid;
}
}

View File

@ -0,0 +1,59 @@
package com.cy.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
@Column(length = 80)
private String id;
private String username;
private String password;
private String type;
public User(String id, String username, String password, String type) {
this.id = id;
this.username = username;
this.password = password;
this.type = type;
}
public User() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

View File

@ -0,0 +1,70 @@
package com.cy.repository;
import com.cy.entity.Homework;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.sql.Types;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Repository
public class DTODao {
@Resource
private JdbcTemplate jdbcTemplate;
public List<Map<String, Object>> queryHomeworkUserDTOListMap(Homework homework) {
String sql = "SELECT u.id,u.username,uh.h_id,uh.complete_time,uh.homeworkid from `user` u LEFT JOIN user_homework uh on (u.id=uh.u_id and uh.h_id= ? )where u.type='student'";
Object[] args = {homework.getId()};
int[] argTypes = {Types.VARCHAR};
return this.jdbcTemplate.queryForList(sql, args, argTypes);
}
public int queryuploadDTOListMap(String uid, String hid, String homeworkid,Date date) {
String sql = "insert into user_homework(h_id,u_id,complete_time,homeworkid,status) values(?,?,?,?,?)";
Object[] args = {hid, uid, date, homeworkid,"完成"};
int[] argTypes = {Types.VARCHAR, Types.VARCHAR, Types.DATE, Types.VARCHAR};
return this.jdbcTemplate.update(sql, args);
}
public int queryuploadDTOListMap2(String uid, String hid,String homeworkid, Date date) {
String sql = "update user_homework set complete_time =? , homeworkid=? where u_id=? AND h_id=?";
Object[] args = {date,homeworkid, uid,hid};
int[] argTypes = {Types.VARCHAR, Types.VARCHAR, Types.DATE, Types.VARCHAR};
return this.jdbcTemplate.update(sql, args);
}
public List<Map<String, Object>> queryRankDTOListMap(String type) {
if ("全部".equals(type)) {
String sql = "SELECT `user`.`username`,COUNT(user_homework.`status`) ac, `user`.type FROM `user` LEFT JOIN user_homework ON `user`.id=user_homework.u_id GROUP BY `user`.id HAVING `user`.type='student' ORDER BY COUNT(user_homework.`status`) DESC";
return this.jdbcTemplate.queryForList(sql);
} else {
String sql2 = "SELECT `user`.`username`,count(t.h_id) ac ,`user`.type FROM `user` LEFT JOIN (SELECT `user`.id,`user`.`username`,user_homework.h_id FROM `user` LEFT JOIN user_homework on `user`.id = user_homework.u_id LEFT JOIN homework on user_homework.h_id=homework.id where homework.type=?) t on t.id = `user`.id GROUP BY `user`.id HAVING `user`.type='student' ORDER BY COUNT(t.h_id) desc;";
Object[] args = {type};
int[] argTypes = {Types.VARCHAR};
return this.jdbcTemplate.queryForList(sql2, args, argTypes);
}
}
public List<Map<String, Object>> queryfindhomework(String homeworkid) {
String sql = ("select * from user_homework where homeworkid=? ");
Object[] args = {homeworkid};
int[] argTypes = {Types.VARCHAR};
return this.jdbcTemplate.queryForList(sql, args,argTypes);
}
public List<Map<String, Object>> queryfindexit(String uid,String hid) {
String sql = ("select * from user_homework where u_id=? AND h_id=? ");
Object[] args = {uid,hid};
int[] argTypes = {Types.VARCHAR,Types.VARCHAR};
return this.jdbcTemplate.queryForList(sql, args,argTypes);
}
}

View File

@ -0,0 +1,15 @@
package com.cy.repository;
import com.cy.entity.Homework;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.sql.Date;
import java.util.List;
public interface HomeworkRepository extends JpaRepository<Homework,String> {
List<Homework> findByTypeAndFinishTime(String type, Date date);
List<Homework> findAllById(String id);
Page<Homework> findByTypeAndFinishTime(String type, Date date, Pageable pageable);
}

View File

@ -0,0 +1,13 @@
package com.cy.repository;
import com.cy.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface UserRepository extends JpaRepository<User,String> {
List<User> findByUsername(String username);
User findByUsernameAndPassword(String username, String password);
}

View File

@ -0,0 +1,127 @@
package com.cy.service;
import com.cy.entity.Homework;
import com.cy.entity.HomeworkRankDTO;
import com.cy.entity.HomeworkUserDTO;
import com.cy.repository.DTODao;
import com.cy.repository.HomeworkRepository;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class HomeworkService {
@Resource
HomeworkRepository hr;
@Resource
DTODao dd;
public List<Homework> findByTypeAndFinishTime(String type, Date date) {
return hr.findByTypeAndFinishTime(type, date);
}
public Iterable<Homework> findByTypeAndFinishTime(String type, Date date, Pageable pageable){
return hr.findByTypeAndFinishTime(type,date,pageable);
}
public Homework save(Homework homework) {
return hr.save(homework);
}
public List<Homework> findAllById(String id) {
return hr.findAllById(id);
}
public Homework update(Homework homework) {
return hr.save(homework);
}
public void deleteById(String id) {
hr.deleteById(id);
}
public ArrayList<HomeworkUserDTO> gethomeworkdetail(Homework homework) {
ArrayList<HomeworkUserDTO> ah = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
List<Map<String, Object>> listmap = dd.queryHomeworkUserDTOListMap(homework);
for (int i = 0; i < listmap.size(); i++) {
HomeworkUserDTO hud = new HomeworkUserDTO();
String id = (String) listmap.get(i).get("id");
String username = (String) listmap.get(i).get("username");
String hid = (String) listmap.get(i).get("hid");
String homeworkid = (String) listmap.get(i).get("homeworkid");
try {
if (listmap.get(i).get("complete_time") != null) {
Date completeTime = new Date(sdf.parse(listmap.get(i).get("complete_time").toString()).getTime());
hud.setCompleteTime(sdf.format(completeTime));
} else {
hud.setCompleteTime("");
}
} catch (ParseException e) {
e.printStackTrace();
}
hud.setId(id);
hud.setUsername(username);
hud.setHid(hid);
hud.setHomeworkid(homeworkid);
if (hud.getCompleteTime() == "") {
hud.setStatus("未完成");
} else {
hud.setStatus("完成");
}
ah.add(hud);
}
return ah;
}
public ArrayList<HomeworkRankDTO> getRank(String type1) {
ArrayList<HomeworkRankDTO> hr = new ArrayList<>();
List<Map<String, Object>> listmap = dd.queryRankDTOListMap(type1);
for (int i = 0; i < listmap.size(); i++) {
HomeworkRankDTO hrd = new HomeworkRankDTO();
String username = (String) listmap.get(i).get("username");
String ac = listmap.get(i).get("ac").toString();
String type = (String) listmap.get(i).get("type");
hrd.setUsername(username);
hrd.setAc(ac);
hrd.setType(type);
hr.add(hrd);
}
return hr;
}
public int savedetails(String uid, String hid,String homeworkid) {
int rs = 0;
List<Homework> list = hr.findAllById(hid);
if (new Date(System.currentTimeMillis()).getTime() > list.get(0).getFinishTime().getTime()) {
rs = -1;
} else {
// dd.queryuploadDTOListMap(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
// rs = 1;
if (dd.queryfindexit(uid,hid).size() > 0) {
dd.queryuploadDTOListMap2(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
rs = 1;
} else {
dd.queryuploadDTOListMap(uid, hid, homeworkid,new Timestamp(new java.util.Date().getTime()));
rs = 1;
}
}
return rs;
}
}

View File

@ -0,0 +1,31 @@
package com.cy.service;
import com.cy.entity.Homework;
import com.cy.entity.User;
import com.cy.repository.UserRepository;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
@Resource
UserRepository ur;
public User save(User user) {
return ur.save(user);
}
public List<User> findByName(String name){
return ur.findByUsername(name);
}
public User findByNameAndPassword(String name,String password){
return ur.findByUsernameAndPassword(name,password);
}
}

View File

@ -0,0 +1,11 @@
package com.cy.utils;
import java.util.Random;
public class KeyUtils {
public static synchronized String genUniqueKey() {
Random random = new Random();
Integer number = random.nextInt(900000) + 100000;
return System.currentTimeMillis() + String.valueOf(number);
}
}

View File

@ -0,0 +1,19 @@
package com.cy.utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResourceHandler是指你想在url请求的路径
//addResourceLocations是图片存放的真实路径
registry.addResourceHandler("/homework/**").addResourceLocations("file:D:/tmp/").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}