1. 上傳(非重點)
1.1 導入jar
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
1.2 表單
<form action="${pageContext.request.contextPath }/upload/test1" method="post"
enctype="multipart/form-data">
file: <input type="file" name="source"/> <br>
<input type="submit" value="提交"/>
</form>
1.3 上傳解析器
<!-- 上傳解析器
id必須是:“multipartResolver”
-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 最大可上傳的文件大小 byte 超出後會拋出MaxUploadSizeExceededException異常,可以異常解析器捕獲 -->
<property name="maxUploadSize" value="2097152"></property>
</bean>
1.4 Handler
@RequestMapping("/test1")
public String hello1(String username,MultipartFile source,HttpSession session) {
//文件的原始名稱
String filename = source.getOriginalFilename();
//定製全局唯一的命名
String unique = UUID.randomUUID().toString();
//【獲得文件的後綴】
String ext = FilenameUtils.getExtension(filename);//abc.txt txt hello.html html
//定製全局唯一的文件名
String uniqueFileName = unique+"."+ext;
System.out.println("唯一的文件名:"+uniqueFileName);
//文件的類型
String type = source.getContentType();
System.out.println("filename:"+filename+" type:"+type);
//獲得 upload_file的磁盤路徑 ==> 在webapp目錄下創建一個目錄"upload_file",且此目錄初始不要爲空,否則編譯時被忽略
String real_path = session.getServletContext().getRealPath("/upload_file");
System.out.println("real_path:"+real_path);
//將上傳的文件,存入磁盤路徑中
//source.transferTo(new File("d:/xxxx/xxxx/xx.jpg"))
source.transferTo(new File(real_path+"\\"+uniqueFileName));
return "index";
}
2. 下載(非重點)
2.1 超鏈
<a href="${pageContext.request.contextPath}/download/test1?name=Koala.jpg">下載</a>
2.2 Handler
@RequestMapping("/test1")
public void hello1(String name,HttpSession session,HttpServletResponse response){
System.out.println("name:"+name);
//獲得要下載文件的絕對路徑
String path = session.getServletContext().getRealPath("/upload_file");
//文件的完整路徑
String real_path = path+File.separator+name;
//設置響應頭 告知瀏覽器,要以附件的形式保存內容 filename=瀏覽器顯示的下載文件名
response.setHeader("content-disposition","attachment;filename="+name);
//【讀取目標文件】,寫出給客戶端
IOUtils.copy(new FileInputStream(real_path), response.getOutputStream());
//上一步,已經是響應了,所以此handler直接是void
}
2.3 上傳下載注意事項
2.3.1 數據庫保存圖片問題
一般我們會將上傳的圖片打散存儲,並賦予新的名稱,參考《MVC案例(二)》
如果要將路徑存儲到數據庫,這裏建議是【存儲帶有uuid的圖片名稱】,因爲項目名稱或者服務器都會發生變動,一旦發生變動,對應的path就會改變,如果全路徑存儲,則維護成本會很高。
展示或者下載的時候,重新拼接路徑即可找到文件,最好使用【File.separator】,適配微軟和其他系統分隔符。
2.3.2 大圖片上傳異常
如果上傳的圖片超過【maxUploadSize】的規定大小,應該會報500錯誤,但也會發生tomcat服務器崩潰問題。解決辦法:將maxUpladSize的值調很大;然後設置攔截器進行判斷。
public class UploadInterceptor implements HandlerInterceptor{
private long fileSize;
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//校驗文件大小
ServletRequestContext ctx = new ServletRequestContext(request);
long realFileSize = ctx.contentLength();//文件大小
if(fileSize>=realFileSize){
return true;
}
//中斷前,響應錯誤頁面
response.sendRedirect(request.getContextPath()+"/error.jsp");
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
<!--web.xml文件配置,在這裏限制一個文件的大小-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/up/**"/>
<bean class="com.rj.interceptor.UploadInterceptor">
<property name="fileSize" value="2097152"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>
3. 驗證碼(非重點)
屏障,防止暴力破解
3.1 導入jar
<!-- Kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2 聲明驗證碼組件
依賴導入,組件在web.xml中聲明以後,可以直接使用,不需要創建servlet進行驗證碼的生成
另外,驗證碼組件都會默認將驗證碼放入一個session,以方便後面進行比對驗證。
另外,前端獲取驗證碼也只能是【${pageContext.request.contextPath}/captcha】,即captcha
<!--web.xml-->
<servlet>
<servlet-name>cap</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!--邊框-->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<!--長度-->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!--字符池-->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789</param-value>
</init-param>
<!--底色-->
<init-param>
<param-name>kaptcha.background.clear.to</param-name>
<param-value>211,229,237</param-value>
</init-param>
<!--session.setAttribuite("captcha","驗證碼")-->
<init-param>
<param-name>kaptcha.session.key</param-name>
<param-value>captcha</param-value>
</init-param>
</servlet>
<!--地址,可以直接訪問,返回圖片,在線預覽-->
<servlet-mapping>
<servlet-name>cap</servlet-name>
<url-pattern>/captcha</url-pattern>
</servlet-mapping>
3.3 Page
Captcha1是算數驗證碼;Captcha2是simple驗證碼驗證碼,是兩個工具類。
Captcha1是算數驗證碼工具類
/**
* 算術驗證碼
*/
public class Captcha1 {
public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200, 150, 255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);
char[] op = "+-".toCharArray();
Random r = new Random();
int index, len1 = op.length;
int result = 0, firstNum = 0, secondNum = 0;
char operation = '0';
String ex="";
for (int i = 0; i < 4; i++) {// 四次循環,最後生成 【數字1 運算符 數字2 等號】四個部分,如【1 + 2 =】
if (i != 1) index = r.nextInt(100);
else index = r.nextInt(len1);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
if (i == 0) {
//g.drawString(index+"", (i*15)+3, 18);
ex+=index+" ";
firstNum = index;
}
else if (i == 2) {
//g.drawString(index+"", (i*15)+3, 18);
ex+=index+" ";
secondNum = index;
}
else if (i == 1) {
//g.drawString(op[index]+"", (i*15)+3, 18);
ex+=op[index]+" ";
operation = op[index];
}
else {
//g.drawString("=", (i*15)+3, 18);
ex+="=";
}
}
// 繪製算術表達式:ex
g.drawString(ex,3,18);
// 計算結果
if (operation == '+') result = firstNum+secondNum;
else if (operation == '-') result = firstNum-secondNum;
else if (operation == '*') result = firstNum*secondNum;
// 結果存入session
request.getSession().setAttribute("captcha", result);
// 寫出驗證碼( 響應請求 )
response.setDateHeader("Expires", 0L);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
// 指向客戶端的輸出流
ServletOutputStream out = response.getOutputStream();
// 寫出驗證碼圖片,響應
ImageIO.write(bi, "JPG", out);
try {
out.flush();
} finally {
out.close();
}
}
}
simple驗證碼
public class Captcha2 {
public static void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
BufferedImage bi = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200, 150, 255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();//字符集合
Random r = new Random();
int len = ch.length, index;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 4; i++) {//驗證碼長度
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
g.drawString(ch[index]+"", (i*15)+3, 18);
sb.append(ch[index]);
}
//存入session
request.getSession().setAttribute("captcha", sb.toString());
// 寫出驗證碼( 響應請求 )
response.setDateHeader("Expires", 0L);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
ServletOutputStream out = response.getOutputStream();
ImageIO.write(bi, "JPG", out);
try {
out.flush();
} finally {
out.close();
}
}
}
@Controller
@RequestMapping("/cap")
public class CaptchaController {
@RequestMapping("/index")
public String index() {
System.out.println("goto captcha.jsp");
return "WEB-INF/captcha";
}
//kaptcha驗證碼組件可不需要創建servlet生成驗證碼,直接進行使用
@RequestMapping("/test1")
public String test1(HttpSession session){
Object captcha = session.getAttribute("captcha");
System.out.println("captcha:"+captcha);
return "index";
}
@RequestMapping("/test2")
public void test2(HttpSession session, HttpServletResponse res, HttpServletRequest req) throws IOException {
Captcha1.generateCaptcha(req,res);
}
@RequestMapping("/test3")
public void test3(HttpSession session,HttpServletResponse res, HttpServletRequest req) throws IOException {
Captcha2.generateCaptcha(req,res);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<input type="text">
<img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/captcha" style="width: 100px;vertical-align: middle">
<img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/cap/test2" style="width: 100px;vertical-align: middle">
<img onclick="refreshCode04(this);" src="${pageContext.request.contextPath}/cap/test3" style="width: 100px;vertical-align: middle">
<script>
function refreshCode04(a){
//刷新驗證碼
a.src="${pageContext.request.contextPath}/captcha?"+new Date().getTime();
}
</script>
</body>
</html>
<!--驗證碼校驗模版前端-->
<tr>
<td>驗證碼:</td>
<td>
<input type="text" name="code" id="inputCode">
<img src="${pageContext.request.contextPath}/cap" onclick="click1(this)"/>
<div id="yanzhengjieguo" style="color: red"></div>
</td>
</tr>
<script type="text/javascript">
function click1(img) {
img.src="${pageContext.request.contextPath}/cap?" + new Date().getTime();
}
$("#inputCode").blur(function () {
var code = $("#inputCode").val();
$.ajax({
url:"${pageContext.request.contextPath}/checkCode",
type:"get",
data:{"code":code},
success:function (data) {
if(data=='no') {
$("#yanzhengjieguo").text("驗證碼輸入錯誤");
$("#denglu").attr("disabled","disabled");
} else {
$("#denglu").removeAttr("disabled");
$("#yanzhengjieguo").text("輸入正確");
}
}
});
});
</script>