1.前臺的form表單創建,注意action、enctype的內容,前端
2.經過添加一個隱藏的iframe標籤使form的target指向iframe來達到不跳轉頁面的效果,同時須要在js裏獲取iframe裏的內容(即後臺利用GSON傳回來的返回值)。java
代碼部分:tomcat
<form id="form1" action="../PublishPostingsServlet" enctype="multipart/form-data" method="POST" target="iframe_userInterface">session
<!-- 正文區域--多行文本框 -->ide
<textarea name="ptext" id="ptext" cols="30" rows="10"></textarea>post
<!-- 圖片和標籤選擇區域 -->this
<ul id="ptext_ul">編碼
<li>spa
<a id="photo" href="javaScript:;" onclick="showPic();">版本控制
<em class="iconfont"></em>圖片
</a>
</li>
<li id="lable">
<a href="javaScript:;" onclick="showLable();">
<em class="iconfont"></em>標籤
</a>
</li>
</ul>
<div id="tupianqu">
<span class="ziti">本地上傳</span>
<input id="tupian_btn" name="tupian_btn" type="file" accept="image/gif,image/jpeg,image/jpg,image/png" onchange="selectFile();" />
</div>
<button id="ptext_btn" type="submit">發佈</button>
</form>
<iframe id="iframe_userInterface" name="iframe_userInterface" style="display: none;"></iframe>
3.js裏獲取文本代碼以下:
$("#iframe_userInterface").load(function(){
var text = $(this).contents().find("body").text();//獲取iframe裏的內容
console.log(text);//打印iframe頁面的內容
}
})
能夠利用text來進行驗證
後臺要接收form表單傳過去的數據,而且利用GSON將返回值傳回到iframe裏,
代碼:
@WebServlet("/PublishPostingsServlet")
@MultipartConfig // 標識Servlet支持文件上傳
public class PublishPostingsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;// 主要用於版本控制
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 設置數據的編碼方式爲utf-8
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 返回的是項目在tomcat中的實際發佈運行的根路徑
String savePath = request.getServletContext().getRealPath("/picture");
Part part = request.getPart("tupian_btn");
String header = part.getHeader("content-disposition");// 獲取請求頭--form-data; name="tupian_btn"; filename=""
String fileName = getFileName(header);// 獲取文件名
System.out.println("文件名:" + fileName);
part.write(savePath + File.separator + fileName);// 獲取文件類型
/*判斷登陸狀態*/
String id = null;
int result = 0;// 返回給前端的結果
HttpSession session = request.getSession();
id = (String) session.getAttribute("Account");
System.out.println("session裏的id:" + id);
if (id == null) {
result = 4;// 當id爲空的時候,登陸失效,返回4
}
String ptext = request.getParameter("ptext");// 獲取前臺頁面傳遞的參數
String label = Tools.getTable(ptext);
String ptime = Tools.getTime();
while (result == 0) {
result = PostingsService.publishPostings(id, ptext, ptime, label, fileName);// result接收數據在處理的結果1或2或3
}
Gson gson = new Gson();
String postinfsInfo = gson.toJson(result);// 定義postingsInfo存放GSON要傳回的數據
response.getWriter().write(postinfsInfo);// 返回數據
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);// 調用doGet
}
}