基于javaweb+mysql的ssm+maven二手图书商城平台(java+ssm+jsp+js+jquery+mysql)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SSM+Maven二手图书商城平台(java+ssm+jsp+js+jquery+mysql)
项目介绍
用户角色包含以下功能: 用户登录,查看商品详情,按分类查看,查看我的书架,上传二手书等功能。 PS:这个没有管理员角色。
环境需要
1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。 2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA; 3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可 4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS; 5.数据库:MySql 5.7版本; 6.是否Maven项目:是;
技术栈
- 后端:Spring+SpringMVC+Mybatis 2. 前端:JSP+CSS+JavaScript+jquery
使用说明
- 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件; 2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven; 若为maven项目,导入成功后请执行maven clean;maven install命令,然后运行; 3. 将项目中jdbc.properties配置文件中的数据库配置改为自己的配置; 4. 运行项目,输入localhost:8080/ssm_sebook_market 登录
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RequestMapping(value = "/sessions",method = RequestMethod.POST)
@ResponseBody
public Result checkLogin(@RequestBody User user, HttpServletRequest request) {
// userService验证是否登录成功
boolean flag = userService.checkUser(user);
log.info("request: user/login , user: " + user.toString());
if (flag) {
Map data = new HashMap();
data.put("currentUser",user);
// 登录成功,将登录信息放入session
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理response的字符编码
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 转型为与协议相关对象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 对request包装增强
HttpServletRequest myrequest = (HttpServletRequest) new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否编码的标记
private boolean hasEncode;
//定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
public MyRequest(HttpServletRequest request) {
super(request);// super必须写
this.request = request;
}
// 对需要增强方法 进行覆盖
@Override
public Map<String, String[]> getParameterMap() {
// 先获得请求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post请求
try {
// 处理post乱码
request.setCharacterEncoding("UTF-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get请求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 确保get手动编码逻辑只运行一次
for (String parameterName : parameterMap.keySet()) {
*/
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception exc)
throws Exception {
}
/**
* Handler执行之后,ModelAndView返回之前调用这个方法
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
/**
* Handler执行之前调用这个方法
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//获取请求的URL
String url = request.getRequestURI();
//URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的,其它的URL都进行拦截控制
if(url.indexOf("/users")>=0){
return true;
}
//获取Session
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if(user != null){
return true;
}
//不符合条件的,跳转到登录界面
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
return false;
}
}
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private UserService userService;
@Autowired
private BookService bookService;
@Autowired
private BookImageService bookImageService;
@Autowired
private CategoryService categoryService;
// 日志文件
private static final Logger log = Logger.getLogger(BookController.class);
/**
* 书本详情页
* @param id 图书ID
* @return 该ID图书的详情页
*/
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ModelAndView getBookDetail(@PathVariable("id") String id) {
ModelAndView mav = new ModelAndView("bookDetail");
int intId = Integer.parseInt(id);
Book curBook = bookService.get(intId);
curBook.setBookImage(bookImageService.getByBookId(intId));
curBook.setUser(userService.get(bookService.getUserId(intId)));
mav.addObject("book",curBook);
* @param book
* 应该使用GET的,但是会产生不合法URI异常,待解决
*/
@RequestMapping(value = "/categories")
public Result getCategory(@RequestBody Book book){
JSONObject data = new JSONObject();
Category category = bookService.get(book.getId()).getCategory();
log.info("request: book/category/get , bookId: " + book.getId()+" , category:"+category.toString());
if (category.getId() != 0){
data.put("categoryId",category.getId());
return ResultGenerator.genSuccessResult(data);
}else {
return ResultGenerator.genFailResult("无效的Category!");
}
}
/**
* 更新图书内容
* @param request 用于获取路径
* @param book 除图片外其他的图书信息
* @param file 图片
* @return
* 应该使用PUT,可是需要上传图片,表单提交无法用PUT,待解决
*/
@RequestMapping(value = "/renewal",method = RequestMethod.POST)
public Result editBook(HttpServletRequest request, Book book,
@RequestParam(value = "image" , required = false) MultipartFile file){
try {
bookService.update(book);
if (file != null) {
BookImage bookImage = bookImageService.getByBookId(book.getId());
bookImage.setBook(book);
bookImageService.update(bookImage);
String imageName = bookImage.getId() + ".jpg";
String imagePath = request.getServletContext().getRealPath("/img/book-list/article/");
File filePath = new File(imagePath, imageName);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdir();
}else if (filePath.exists()){
//filePath.delete();
}
file.transferTo(new File(imagePath + File.separator + imageName));
}
log.info("request: book/update , book: " + book.toString());
return ResultGenerator.genSuccessResult();
} catch (IOException e) {
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一个值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回参数的第一个值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
package com.daniel.controller;
@Controller
public class ForeController {
@Autowired
private BookService bookService;
@Autowired
@ExceptionHandler(HttpMessageNotReadableException.class)
public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("could_not_read_json...",e);
return new Response().failure("could not read json");
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MethodArgumentNotValidException.class})
public Response handleValidationException(MethodArgumentNotValidException e) {
log.error("parameter_validation_exception...", e);
return new Response().failure("parameter_validation_exception");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Response handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
log.error("request_method_not_supported...", e);
return new Response().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
public Response handleHttpMediaTypeNotSupportedException(Exception e) {
log.error("content_type_not_supported...", e);
return new Response().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
@Controller
public class SearchController {
@Autowired
private BookService bookService;
@RequestMapping("searchBook.do")
public ModelAndView searchBook(Book book) throws IOException, ParseException {
ModelAndView mav = new ModelAndView("searchBook");
// 关键字
String keyword = book.getName();
System.out.println(keyword);
// 准备中文分词器
MyIKAnalyzer analyzer = new MyIKAnalyzer();
// 索引
Directory index = createIndex(analyzer);
// 查询器
Query query = new QueryParser("name",analyzer).parse(keyword);
// 搜索
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
int numberPerPage = 10;
ScoreDoc[] hits = searcher.search(query,numberPerPage).scoreDocs;
List<Book> books = new ArrayList<>();
for (int i = 0; i < hits.length; i++) {
ScoreDoc scoreDoc = hits[i];
int docId = scoreDoc.doc;
Document document = searcher.doc(docId);
Book tmpBook = bookService.get(Integer.parseInt(document.get("id")));
books.add(tmpBook);
}
mav.addObject("books",books);
return mav;
}
private Directory createIndex(MyIKAnalyzer analyzer) throws IOException {
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(index,config);
// 关键字
String keyword = book.getName();
System.out.println(keyword);
// 准备中文分词器
MyIKAnalyzer analyzer = new MyIKAnalyzer();
// 索引
Directory index = createIndex(analyzer);
// 查询器
Query query = new QueryParser("name",analyzer).parse(keyword);
// 搜索
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
int numberPerPage = 10;
ScoreDoc[] hits = searcher.search(query,numberPerPage).scoreDocs;
List<Book> books = new ArrayList<>();
for (int i = 0; i < hits.length; i++) {
ScoreDoc scoreDoc = hits[i];
int docId = scoreDoc.doc;
Document document = searcher.doc(docId);
Book tmpBook = bookService.get(Integer.parseInt(document.get("id")));
books.add(tmpBook);
}
mav.addObject("books",books);
return mav;
}
private Directory createIndex(MyIKAnalyzer analyzer) throws IOException {
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(index,config);
List<Book> books = bookService.listByBookType(1);
for (Book book : books) {
addDoc(writer,book);
}
writer.close();
return index;
}
private void addDoc(IndexWriter writer,Book book) throws IOException {
Document doc = new Document();
doc.add(new TextField("id",book.getId()+"",Field.Store.YES));
doc.add(new TextField("name",book.getName(),Field.Store.YES));
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RequestMapping(value = "/sessions",method = RequestMethod.POST)
@ResponseBody
public Result checkLogin(@RequestBody User user, HttpServletRequest request) {
// userService验证是否登录成功
boolean flag = userService.checkUser(user);
log.info("request: user/login , user: " + user.toString());
if (flag) {
Map data = new HashMap();
data.put("currentUser",user);
// 关键字
String keyword = book.getName();
System.out.println(keyword);
// 准备中文分词器
MyIKAnalyzer analyzer = new MyIKAnalyzer();
// 索引
Directory index = createIndex(analyzer);
// 查询器
Query query = new QueryParser("name",analyzer).parse(keyword);
// 搜索
IndexReader reader = DirectoryReader.open(index);
IndexSearcher searcher = new IndexSearcher(reader);
int numberPerPage = 10;
ScoreDoc[] hits = searcher.search(query,numberPerPage).scoreDocs;
List<Book> books = new ArrayList<>();
for (int i = 0; i < hits.length; i++) {
ScoreDoc scoreDoc = hits[i];
int docId = scoreDoc.doc;
Document document = searcher.doc(docId);
Book tmpBook = bookService.get(Integer.parseInt(document.get("id")));
books.add(tmpBook);
}
mav.addObject("books",books);
return mav;
}
private Directory createIndex(MyIKAnalyzer analyzer) throws IOException {
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(index,config);
List<Book> books = bookService.listByBookType(1);
for (Book book : books) {
addDoc(writer,book);
}
writer.close();
return index;
}
private void addDoc(IndexWriter writer,Book book) throws IOException {
Document doc = new Document();
doc.add(new TextField("id",book.getId()+"",Field.Store.YES));
doc.add(new TextField("name",book.getName(),Field.Store.YES));
writer.addDocument(doc);
}
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RequestMapping(value = "/sessions",method = RequestMethod.POST)
@ResponseBody
public Result checkLogin(@RequestBody User user, HttpServletRequest request) {
// userService验证是否登录成功
boolean flag = userService.checkUser(user);
log.info("request: user/login , user: " + user.toString());
if (flag) {
Map data = new HashMap();
data.put("currentUser",user);
// 登录成功,将登录信息放入session
request.getSession().setAttribute("user",userService.getByStudentid(user.getStudentid()));
return ResultGenerator.genSuccessResult(data);
}else {
return ResultGenerator.genFailResult("学号或密码输入错误!");
}
}
/**
* 登出操作
* @param request 用于获取session中的User对象
* @return 登出后跳转至登录界面
*/
@RequestMapping(value = "/sessions",method = RequestMethod.DELETE)
public Result logout(HttpServletRequest request) {
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler({MethodArgumentNotValidException.class})
public Response handleValidationException(MethodArgumentNotValidException e) {
log.error("parameter_validation_exception...", e);
return new Response().failure("parameter_validation_exception");
}
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Response handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
log.error("request_method_not_supported...", e);
return new Response().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
public Response handleHttpMediaTypeNotSupportedException(Exception e) {
log.error("content_type_not_supported...", e);
return new Response().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RequestMapping(value = "/sessions",method = RequestMethod.POST)
@ResponseBody
public Result checkLogin(@RequestBody User user, HttpServletRequest request) {
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private UserService userService;
@Autowired
private BookService bookService;
@Autowired
private BookImageService bookImageService;
@Autowired
private CategoryService categoryService;
// 日志文件
private static final Logger log = Logger.getLogger(BookController.class);
/**
* 书本详情页
* @param id 图书ID
* @return 该ID图书的详情页
*/
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ModelAndView getBookDetail(@PathVariable("id") String id) {
ModelAndView mav = new ModelAndView("bookDetail");
int intId = Integer.parseInt(id);
Book curBook = bookService.get(intId);
curBook.setBookImage(bookImageService.getByBookId(intId));
curBook.setUser(userService.get(bookService.getUserId(intId)));
mav.addObject("book",curBook);
return mav;
}
/**
* 上传图书
* @param request 用于获取当前用户信息
* @param book 图书实体类
* @param file 图片文件
*/
@RequestMapping(value = "",method = RequestMethod.POST)
private Directory createIndex(MyIKAnalyzer analyzer) throws IOException {
Directory index = new RAMDirectory();
IndexWriterConfig config = new IndexWriterConfig(analyzer);
IndexWriter writer = new IndexWriter(index,config);
List<Book> books = bookService.listByBookType(1);
for (Book book : books) {
addDoc(writer,book);
}
writer.close();
return index;
}
private void addDoc(IndexWriter writer,Book book) throws IOException {
Document doc = new Document();
doc.add(new TextField("id",book.getId()+"",Field.Store.YES));
doc.add(new TextField("name",book.getName(),Field.Store.YES));
writer.addDocument(doc);
}
}
package com.daniel.aspect;
@ControllerAdvice
@ResponseBody
public class ExceptionAspect {
private static final Logger log = Logger.getLogger(ExceptionAspect.class);
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Response handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("could_not_read_json...",e);
return new Response().failure("could not read json");
}
return mav;
}
/**
* 根据ID获取书的Category
* @param book
* 应该使用GET的,但是会产生不合法URI异常,待解决
*/
@RequestMapping(value = "/categories")
public Result getCategory(@RequestBody Book book){
JSONObject data = new JSONObject();
Category category = bookService.get(book.getId()).getCategory();
log.info("request: book/category/get , bookId: " + book.getId()+" , category:"+category.toString());
if (category.getId() != 0){
data.put("categoryId",category.getId());
return ResultGenerator.genSuccessResult(data);
}else {
return ResultGenerator.genFailResult("无效的Category!");
}
}
/**
* 更新图书内容
* @param request 用于获取路径
* @param book 除图片外其他的图书信息
* @param file 图片
* @return
* 应该使用PUT,可是需要上传图片,表单提交无法用PUT,待解决
*/
@RequestMapping(value = "/renewal",method = RequestMethod.POST)
public Result editBook(HttpServletRequest request, Book book,
@RequestParam(value = "image" , required = false) MultipartFile file){
try {
bookService.update(book);
if (file != null) {
BookImage bookImage = bookImageService.getByBookId(book.getId());
bookImage.setBook(book);
bookImageService.update(bookImage);
String imageName = bookImage.getId() + ".jpg";
String imagePath = request.getServletContext().getRealPath("/img/book-list/article/");
File filePath = new File(imagePath, imageName);
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdir();
}else if (filePath.exists()){
//filePath.delete();
}
file.transferTo(new File(imagePath + File.separator + imageName));
}
log.info("request: book/update , book: " + book.toString());
return ResultGenerator.genSuccessResult();
public Result uploadSell(HttpServletRequest request,Book book,
@RequestParam(value = "image" , required = false) MultipartFile file){
// 获取当前用户的信息
User user = (User) request.getSession().getAttribute("user");
try {
if(file != null && book != null){
// 写入图书信息
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long time = System.currentTimeMillis();
String timeStr= sdf.format(time);
book.setDate(timeStr);
book.setUser(user);
bookService.add(book);
BookImage bookImage = new BookImage();
bookImage.setBook(book);
bookImageService.add(bookImage);
String imageName = bookImage.getId()+".jpg";
String imagePath = request.getServletContext().getRealPath("/img/book-list/article/");
File filePath = new File(imagePath,imageName);
if (!filePath.getParentFile().exists()){
filePath.getParentFile().mkdir();
}
file.transferTo(new File(imagePath + File.separator + imageName));
log.info("request: book/upload , book: " + book.toString());
return ResultGenerator.genSuccessResult();
}else {
return ResultGenerator.genFailResult("信息填写不完整或未上传图片!");
}
} catch (IOException e) {
e.printStackTrace();
return ResultGenerator.genFailResult("上传失败");
}
}
/**
* 更新图书的视图
* @param id 图书的ID
* @return 该ID的图书的更新界面
*/
@RequestMapping(value = "/renewal/{id}",method = RequestMethod.GET)
public ModelAndView goEditBook(@PathVariable String id){
ModelAndView mav = new ModelAndView("editBook");
int bookId = Integer.parseInt(id);
Book curBook = bookService.get(bookId);
log.info("request: book/update , book: " + curBook.toString());
if (curBook != null){
curBook.setBookImage(bookImageService.getByBookId(bookId));
}
mav.addObject("askBooks",askBooks);
return mav;
}
@RequestMapping("/goUpload.do")
public ModelAndView upload(Book book){
String path = book.getBookType()==1?"uploadSell":"uploadAsk";
ModelAndView mav = new ModelAndView(path);
Map<Integer,String> categories = categoryService.listByMap();
mav.addObject("categories",categories);
return mav;
}
@RequestMapping("/goBookStore.do")
public ModelAndView goBookStore(Page page,Category category){
ModelAndView mav = new ModelAndView("bookStore");
Map<Integer, String> categories = categoryService.listByMap();
Category curCategory = category.getId() !=0?categoryService.get(category.getId()):new Category();
String categoryName = curCategory.getName() == null?"所有二手书":curCategory.getName();
int total = bookService.count();
page.calculateEnd(total);
if (page.getStart() < 0) {
page.setStart(0);
}else if (page.getStart() > total){
page.setEnd(page.getEnd());
}
PageHelper.offsetPage(page.getStart(),16);
List<Book> books = curCategory.getId() == 0?bookService.listByBookType(1):bookService.listByCategoryId(1,curCategory.getId());
mav.addObject("categoryName",categoryName);
mav.addObject("books",books);
mav.addObject("categories",categories);
return mav;
}
@RequestMapping("/goAskBookStore.do")
public ModelAndView goAskBookStore(Page page){
ModelAndView mav = new ModelAndView("askBookStore");
int total = bookService.count();
page.calculateEnd(total);
if (page.getStart() < 0) {
page.setStart(0);
}else if (page.getStart() > total){
page.setEnd(page.getEnd());
}
PageHelper.offsetPage(page.getStart(),16);
List<Book> books = bookService.listByBookType(0);
mav.addObject("books",books);
return mav;
}
}
package com.daniel.controller;
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private UserService userService;
@Autowired
private BookService bookService;
@Autowired
private BookImageService bookImageService;
@Autowired
private CategoryService categoryService;
// 日志文件
private static final Logger log = Logger.getLogger(BookController.class);
/**
* 书本详情页
* @param id 图书ID
* @return 该ID图书的详情页
*/
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ModelAndView getBookDetail(@PathVariable("id") String id) {
ModelAndView mav = new ModelAndView("bookDetail");
int intId = Integer.parseInt(id);
Book curBook = bookService.get(intId);
curBook.setBookImage(bookImageService.getByBookId(intId));
curBook.setUser(userService.get(bookService.getUserId(intId)));
mav.addObject("book",curBook);
return mav;
}
/**
* 上传图书
* @param request 用于获取当前用户信息
* @param book 图书实体类
* @param file 图片文件
*/
@RequestMapping(value = "",method = RequestMethod.POST)
public Result uploadSell(HttpServletRequest request,Book book,
@RequestParam(value = "image" , required = false) MultipartFile file){
// 获取当前用户的信息
User user = (User) request.getSession().getAttribute("user");
try {
if(file != null && book != null){
// 写入图书信息
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post请求
try {
// 处理post乱码
request.setCharacterEncoding("UTF-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get请求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 确保get手动编码逻辑只运行一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 处理get乱码
values[i] = new String(values[i]
.getBytes("UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一个值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回参数的第一个值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
package com.daniel.controller;
}
file.transferTo(new File(imagePath + File.separator + imageName));
}
log.info("request: book/update , book: " + book.toString());
return ResultGenerator.genSuccessResult();
} catch (IOException e) {
e.printStackTrace();
return ResultGenerator.genFailResult("修改失败!");
}
}
/**
* 删除一本或多本图书
* @param request 用于获取路径,删除图片
* @param bookIds 要删除的图书ID数组
*/
@RequestMapping(value = "/deleteByBookId")
public Result deleteBook(HttpServletRequest request, @RequestParam(value = "bookIds", required = false) String[] bookIds){
if (bookIds != null) {
// 遍历每个ID
for (String bookId : bookIds) {
int id = Integer.parseInt(bookId);
// 获取当前图书的图片名称与存放路径
String imageName = bookImageService.getByBookId(id).getId() + ".jpg";
String imagePath = request.getServletContext().getRealPath("/img/book-list/article/");
File filePath = new File(imagePath, imageName);
// 删除图片
if (filePath.exists()){
//filePath.delete();
}
// 删除数据库中的图书
bookImageService.deleteByBookId(id);
bookService.delete(id);
}
log.info("request: book/delete , bookIds: " + Arrays.toString(bookIds));
return ResultGenerator.genSuccessResult();
}else {
/**
* 405 - Method Not Allowed
*/
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Response handleHttpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException e) {
log.error("request_method_not_supported...", e);
return new Response().failure("request_method_not_supported");
}
/**
* 415 - Unsupported Media Type
*/
@ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler({ HttpMediaTypeNotSupportedException.class })
public Response handleHttpMediaTypeNotSupportedException(Exception e) {
log.error("content_type_not_supported...", e);
return new Response().failure("content_type_not_supported");
}
/**
* 500 - Internal Server Error
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
*/
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public Response handleException(Exception e) {
log.error("Internal Server Error...", e);
return new Response().failure("Internal Server Error");
}
}
package com.daniel.controller;
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
// 日志文件
private static final Logger log = Logger.getLogger(UserController.class);
@RequestMapping("")
public ModelAndView login() {
return new ModelAndView("login");
}
/**
* 验证登录
* @param user 用户输入的学号与密码封装成的User对象
* @param request 登录成功时将user存入session当中
* @return 登录成功后跳转至首页
*/
@RequestMapping(value = "/sessions",method = RequestMethod.POST)
@ResponseBody
public Result checkLogin(@RequestBody User user, HttpServletRequest request) {
// userService验证是否登录成功
boolean flag = userService.checkUser(user);
log.info("request: user/login , user: " + user.toString());
if (flag) {
Map data = new HashMap();
data.put("currentUser",user);
// 登录成功,将登录信息放入session
request.getSession().setAttribute("user",userService.getByStudentid(user.getStudentid()));
return ResultGenerator.genSuccessResult(data);
}else {
return ResultGenerator.genFailResult("学号或密码输入错误!");
}
}