自己学习AJAX的post提交

DisPic.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">

-->
<script src="<%=basePath%>js/jquery-1.2.6.download.js"></script>
<script language="javascript">

function checkName()
{
var user=$("#username").val();
$.post("<%=basePath%>servlet/AJAXDisPicservlet?id="+user,encType="multipart/form-data",handleRequest);

}
function handleRequest(tom)
{
var d=$("#dd");
d.html(tom);
}

</script>

</head>

<body>

<form method="post" action="" encType="multipart/form-data">
<table border="1">
<tr>
<td>
用户名
</td>

<td>
<input type="file" id="username" name="username"
onblur="checkName()">
</td>
<td rowspan="2">
<span id="dd"></span>
</td>
</tr>
<tr>
<td colspan="3">
<input type=submit value="提交">
</table>

</form>

</body>
</html>


java代码

package com.cstp.servlet;

public class AJAXDisPicservlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

doPost(request,response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
String name = request.getParameter("id");

String fileName = "";
String filePath ="";
try {
String path = this.getServletContext().getRealPath("/upload");
java.io.File file = new java.io.File(path);
if(!file.exists()){
file.mkdir();
}
SmartUpload upload = new SmartUpload();
upload.initialize(this.getServletConfig(),(HttpServletRequest) request, response);
upload.upload();
for(int i=0;i<upload.getFiles().getCount(); i++){
com.jspsmart.upload.File myFile = upload.getFiles().getFile(i);
if(!myFile.isMissing()){
fileName = myFile.getFileName();
myFile.saveAs(path+"/"+fileName,com.jspsmart.upload.File.SAVEAS_PHYSICAL);
}
}

filePath = path+"/"+fileName;
PrintWriter out = response.getWriter();
out.print("<img src= "+path+"/"+fileName+" width=100 height =60>");
System.out.println(path+"/"+name+"路径");
System.out.println("文件"+fileName+",名字");
System.out.println(name);

} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

你可能感兴趣的:(java,jquery,jsp,Ajax,servlet)