1)準備工具Ideahtml
2)瞭解實現的功能點 1)新建項目 2)部署war 3)訪問jsp 4)針對錯誤頁的顯示 5)配置端口 6)鏈接數據庫 7)CRUD 8)分頁java
2)按步驟完成 紅色標記可修改mysql
4)配置pom.xml 也就是同步架包git
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.song</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <description>springboot</description> <name>demo</name> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> </dependency> <!-- servlet依賴. --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- tomcat的支持.--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!--熱部署--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <!-- 這個須要爲 true 熱部署纔有效 --> </dependency> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!-- mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- pagehelper 分頁使用 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency> </dependencies> <!--版本--> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
5)選擇自動導入 時間根據maven的配置下載地址下載github
6)Java下新建操做包及webapp,重構com.song.demo修改成com.song DemoApplication要放在com.song包下, 結果結構以下web
7)main下新建webapp ->WEB-INF->jsp 用來存放jsp文件 spring
8)目錄新建完畢。接下來咱們要來講明文件夾的做用sql
config-->配置類 分頁使用數據庫
mapper->映射相關的類 增刪改查使用apache
pojo->實體類
web->控制器
jsp->存放視圖的地方
9)首先想操做數據庫 須要新建數據庫 spring 並新建表 Category
10)必須得有實體類 在pojo下新建類 Category 建議與數據庫表名相同
package com.song.pojo; public class Category { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
11)綁定映射 在mapper下新建映射類
package com.song.mapper; import java.util.List; import org.apache.ibatis.annotations.*; import com.song.pojo.Category; @Mapper public interface CategoryMapper { @Select("select * from category") List<Category> findAll(); @Insert("insert into category ( name ) values (#{name}) ") public int save(Category category); @Delete(" delete from category where id= #{id} ") public void delete(int id); @Select("select * from category where id= #{id} ") public Category get(int id); @Update("update category set name=#{name} where id=#{id} ") public int update(Category category); }
12)導入分頁的配置 在config下錄入類
package com.song.config; import java.util.Properties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.pagehelper.PageHelper; @Configuration public class PageHelperConfig { @Bean public PageHelper pageHelper() { PageHelper pageHelper = new PageHelper(); Properties p = new Properties(); p.setProperty("offsetAsPageNum", "true"); p.setProperty("rowBoundsWithCount", "true"); p.setProperty("reasonable", "true"); pageHelper.setProperties(p); return pageHelper; } }
13)resources下applocation.properties 配置 1)jsp訪問的配置及MYBATIS配置 2)文件上傳的配置
#jsp配置 spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp #端口配置及路徑 server.port=8888 server.context-path=/test #配置切換 #spring.profiles.active=dev #Mybatis配置 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=123 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update #文件上傳 spring.http.multipart.maxFileSize=100Mb spring.http.multipart.maxRequestSize=100Mb
14)建立控制器,在web下新建以下控制器
1)HelloController 用於測試異常頁的顯示
package com.song.web; import java.text.DateFormat; import java.util.Date; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("/hello") public String hello(Model m) throws Exception{ m.addAttribute("now", DateFormat.getDateTimeInstance().format(new Date()));
//註釋此處代碼便可直接進入hello頁 if(true){ throw new Exception("some exception"); } return "hello"; } }
1.1)GlobalExceptionHandler 異常方法 非控制器
package com.song.web; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.servlet.ModelAndView; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName("errorPage"); return mav; } }
2)CategoryController 實現分頁及CRUD
package com.song.web; import java.util.List; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.song.mapper.CategoryMapper; import com.song.pojo.Category; import org.springframework.web.bind.annotation.RequestParam; @Controller public class CategoryController { @Autowired CategoryMapper categoryMapper; @RequestMapping("/listCategory") public String listCategory(Model m, @RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception { PageHelper.startPage(start,size,"id desc"); List<Category> cs=categoryMapper.findAll(); PageInfo<Category> page = new PageInfo<>(cs); m.addAttribute("page", page); //m.addAttribute("cs", cs); return "listCategory"; } @RequestMapping("/addCategory") public String listCategory(Category c) throws Exception { categoryMapper.save(c); return "redirect:listCategory"; } @RequestMapping("/deleteCategory") public String deleteCategory(Category c) throws Exception { categoryMapper.delete(c.getId()); return "redirect:listCategory"; } @RequestMapping("/updateCategory") public String updateCategory(Category c) throws Exception { categoryMapper.update(c); return "redirect:listCategory"; } @RequestMapping("/editCategory") public String listCategory(int id,Model m) throws Exception { Category c= categoryMapper.get(id); m.addAttribute("c", c); return "editCategory"; } }
3)UploadController 實現文件上傳
package com.song.web; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadController { @RequestMapping("/uploadPage") public String uploadPage() { return "uploadPage"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(HttpServletRequest req, @RequestParam("file") MultipartFile file,Model m) { try { String fileName = System.currentTimeMillis()+file.getOriginalFilename(); String destFileName=req.getServletContext().getRealPath("")+"uploaded"+File.separator+fileName; File destFile = new File(destFileName); destFile.getParentFile().mkdirs(); file.transferTo(destFile); m.addAttribute("fileName",fileName); } catch (FileNotFoundException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } catch (IOException e) { e.printStackTrace(); return "上傳失敗," + e.getMessage(); } return "showImg"; } }
15)完成目錄以下
16)修改 DemoApplication 由於使用war部署方式,因此之前jar的不使用
package com.song; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication @ServletComponentScan public class DemoApplicationTests extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(DemoApplicationTests.class); } public static void main(String[] args) { SpringApplication.run(DemoApplicationTests.class, args); } }
17)增長視圖 在 jsp文件夾下
1)hello.jsp 在hello控制器下注釋相應代碼if(true)部分,進入的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> Hi JSP. 如今時間是 ${now}
2)errorPage.jsp 錯誤提示頁
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div style="width:500px;border:1px solid lightgray;margin:200px auto;padding:80px"> 系統 出現了異常,異常緣由是: ${exception} <br><br> 出現異常的地址是: ${url} </div>
3)listCategory.jsp 列表頁
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <div align="center"> </div> <div style="width:500px;margin:20px auto;text-align: center"> <table align='center' border='1' cellspacing='0'> <tr> <td>id</td> <td>name</td> <td>編輯</td> <td>刪除</td> </tr> <c:forEach items="${page.list}" var="c" varStatus="st"> <tr> <td>${c.id}</td> <td>${c.name}</td> <td><a href="editCategory?id=${c.id}">編輯</a></td> <td><a href="deleteCategory?id=${c.id}">刪除</a></td> </tr> </c:forEach> </table> <br> <div> <a href="?start=1">[首 頁]</a> <a href="?start=${page.pageNum-1}">[上一頁]</a> <a href="?start=${page.pageNum+1}">[下一頁]</a> <a href="?start=${page.pages}">[末 頁]</a> </div> <br> <form action="addCategory" method="post"> name: <input name="name"> <br> <button type="submit">提交</button> </form> </div>
4)editCategory.jsp 編輯頁
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%> <div style="margin:0px auto; width:500px"> <form action="updateCategory" method="post"> name: <input name="name" value="${c.name}"> <br> <input name="id" type="hidden" value="${c.id}"> <button type="submit">提交</button> </form> </div>
5)showImg.jsp 圖片展現頁
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 圖片 ${fileName} <img src="uploaded/${fileName}">
6)uploadPage.jsp 文件上傳頁
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <form action="upload" method="post" enctype="multipart/form-data"> 選擇圖片:<input type="file" name="file" accept="image/*" /> <br> <input type="submit" value="上傳"> </form>
18)完成目錄以下
19) 運行測試
http://127.0.0.1:8888/test/listCategory //列表頁
http://127.0.0.1:8888/test/hello //異常頁
http://127.0.0.1:8888/test/uploadPage //上傳文件頁
20)重點記憶
1)idea下pom.xml下不該有<scope></scope>
2)