(一)上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)

 

最近做了个用户维护功能,涉及到照片的操作。

照片是存到数据库oracle中的Blob字段中。

难点有两个:

1,图片的上传;2,Blob字段的读取。

 

先说图片的上传吧,

我使用common-fileupload来实现的

写个servlet,实现上传到服务器。

 

UpPhotoServlet.java

 

package org.hd.tempuser.serv;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hd.util.BlobUtil;
import org.hd.util.RamdomUtil;

public class UpPhotoServlet extends HttpServlet {

	public UpPhotoServlet(){
		super();
	}
	
	public void destroy(){
		super.destroy();
	}	

	/**
	 * Handles GET requests 处理下载请求
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		doPost(request, response);
	}
	/**
	 * Handles POST requests 处理上传请求
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		response.setContentType("text/html");
		response.setHeader("Cache-Control", "no-cache");
		//IntoLineService intoLineService = (IntoLineService)ContainerManager.getComponent(IntoLineService.BEAN_ID);
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        String jobNumber="";
        if(request.getParameter("jobNumber")!=null){
        	jobNumber=request.getParameter("jobNumber").trim();
        }
        ///////////////////
        final long MAX_SIZE = 6 * 1024 * 1024;// 设置上传文件最大为 3M 
        final int TEMP_MAX_SIZE = 6 * 1024 * 1024;// 设置上传文件最大为 3M 
     // 允许上传的文件格式的列表   
          final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt","doc", "docx", "mp3", "wma", "m4a" };  
        // 文件上傳部分
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
        if (isMultipart == true) {
            try {
            	DiskFileItemFactory  factory = new DiskFileItemFactory();
                factory.setSizeThreshold(TEMP_MAX_SIZE);
                factory.setRepository(new File(request.getSession().getServletContext().getRealPath("/") + "StrutsImagesUploadTemp")); 
                
                ServletFileUpload upload = new ServletFileUpload(factory);
                upload.setSizeMax(MAX_SIZE);
                
                
                // 得到所有的表单域,它们目前都被当作FileItem
                List<FileItem> fileItems = upload.parseRequest(request);
                for(int i=0;i<fileItems.size();i++){
                	FileItem ff=(FileItem)fileItems.get(i);
                	if(ff.isFormField()){
                        // 如果item是正常的表单域
                    	String ffname = ff.getFieldName();
                        String ffvalue = ff.getString();
                        if(ffname.trim().equals("gonghao")){
                        	jobNumber=ffvalue;
                        }
                    	//continue;
                    }
                }
                Iterator<FileItem> iter = fileItems.iterator();
                
                if(fileItems==null||fileItems.size()==0){
                	return;
                }
                // 依次处理每个表单域
                while (iter.hasNext()) {
                	FileItem item = null;   
                	String path = null;   
                	long size = 0; 
                    item = (FileItem) iter.next();
                    if(item == null ||item.isFormField()){
                        // 如果item是正常的表单域
                    	String name = item.getFieldName();
                        String value = item.getString();
                        System.out.print("表单域名为:"+name+"表单域值为:"+value);
                        if(name.trim().equals("gonghao")){
                        	jobNumber=value;
                        }
                    	//continue;
                    }else{
                    	// 得到文件的完整路径    
                        // 如果item是文件上传表单域
                        
                        // 获得文件名及路径
                    	path = item.getName();  
                    	size = item.getSize();
                    	if ("".equals(path) || size == 0) { 
                    		return;
                    	}
                        String fileName = item.getName();
                        System.out.println("item.getName()----"+fileName);
                        if (fileName != null) {
                            File fullFile = new File(item.getName());                            
                                                        
                            // 如果文件存在则上传
                           // if(fullFile.exists()){
//                                File fileOnServer = new File(BlobUtil.makeDirByParamForOds(jobNumber, BlobUtil.DirTypeTempupload),
//                                        fullFile.getName());
                            	String temprepath=BlobUtil.makeDirByParamForOdsRealPath(jobNumber,BlobUtil.DirTypeTempupload)+BlobUtil.getFileSuffix(fileName);
                            	String temprepathxie=BlobUtil.makeDirByParamForOds(jobNumber,BlobUtil.DirTypeTempupload)+BlobUtil.getFileSuffix(fileName);
                            	
                            	String serpp=BlobUtil.BASE_PATH+temprepath;
                                File fileOnServer = new File(serpp);
                                
                                //删除已经存在的文件
                                if(fileOnServer.exists()&&fileOnServer.isFile()){
                                	fileOnServer.delete();
                                }
                                item.write(fileOnServer);
                                
                                String forWrite="\\\\tempphoto"+temprepath;
                                String forWebShow="/tempphoto"+temprepathxie;
                                
                                request.getSession().setAttribute("tempupload"+jobNumber, "/tempphoto"+temprepathxie);
//                                out.write(temprepathxie);
                                //加参数(随机数)防止浏览器从缓存中读取图片
                                String ramStr=RamdomUtil.getRamdomDateStr();
                                String contextpp=request.getContextPath()+"/tempphoto"+temprepathxie+"?randomStr="+ramStr;
                                String htmlstr=" <img src=\""+contextpp+"\" width=\"75px\" height=\"95px\" id=\"person_img\"/>";
                                htmlstr+="<script>";
                                htmlstr+="parent.window.rebackUrl('"+forWebShow+"','"+forWrite+"');";
                                htmlstr+="";
                                htmlstr+="";
                                htmlstr+="";
                                htmlstr+="</script>";
                                out.write(htmlstr);
/*
 <img src="<%=path%>/resource/images/preson_img.jpg" width="75px" height="95px" id="person_img"/>
 */
                                System.out.println("文件"+fileOnServer.getName()+"上传成功");
                           // }
                        }
                    }
                }                
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("the enctype must be multipart/form-data");
        }
        
        // 跳回原頁面
       // RequestDispatcher dispatcher = request
       //         .getRequestDispatcher("/web/page/uploadtoserver.jsp");
       // dispatcher.forward(request, response);
       // return;

        //////////////////
		//out.write("YES");
		out.close();
	}
	
}


web.xml配置servlet

	    <servlet>
		<servlet-name>upphoto</servlet-name>
		<servlet-class>
			org.hd.tempuser.serv.UpPhotoServlet
		</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>upphoto</servlet-name>
		<url-pattern>/upphoto/upphotoServlet</url-pattern>
	</servlet-mapping>
	
	


 

 

 

要说的有以下几点:

common-fileupload已经帮你读文件了,你做的只是确定要写的文件。

这个你只要获取工程的实际路径并创建相应的目录,对应好文件名即可。

说白了就是你要提供要写的文件的path。

还有一点,文件上传后,使用PrintWriter输出html代码

(response.setContentType("text/html");)

这个html代码就是你上传完后在页面看到的效果,

我加了一段js,可以调用父页面的方法。

注意:照片只是一个字段,为了不让返回的页面整个变化,我使用了iframe。

就是照片的页面在一个iframe中。

所以这就涉及到iframe父子页面传值的问题(怎么传,我的代码已经有例子了。)

另外,上传图片成功后我会把图片的一个url返回给页面以便在页面显示你上传的图片,

这是url后面需要加一个随即参数,不加的话,如果第二次再显示修改后的照片,你会发现

图片的url是正确的(鼠标右键查看),但显示的却是原先的图片!

原因就是浏览器缓存!只要url没有变,浏览器就从缓存中读取图片,所以你加一个随即的参数

让url每次都不一样就可以了,浏览器每次都不从缓存中读。

 

随机参数随便写,不一样就可以,例如RamdomUtil.java

package org.hd.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class RamdomUtil {
	
	public static String getRamdomIntStr(){
		String res="";
		Random random1 = new Random();
        res=String.valueOf(random1.nextInt()).trim();
		return res;
	}
	
	public static String getRamdomDateStr(){
		String res="";
		Date dd=new Date();
		SimpleDateFormat  sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		res=sdf.format(dd);
		return res;
	}
	
	public static void main(String[]dsf){
		RamdomUtil.getRamdomIntStr();
		System.out.println(RamdomUtil.getRamdomDateStr());
	}

}


 

 

 

新增用户页面add_user.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page import="org.hd.tempuser.model.TempUser" %>
<%
	String path = request.getContextPath();
%>
<%
	String addSuccess = "";
   if(request.getAttribute("addSuccess")!=null){
	   addSuccess=(String)request.getAttribute("addSuccess");
   }
%>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=path%>/resource/css/style.css" rel="stylesheet" type="text/css" />
	<script src="<%=path%>/script/jquery-1.7.1.js" type="text/javascript"></script>
	<script src="<%=path%>/script/queryHeader.js" type="text/javascript"></script>
	<script src="<%=path%>/script/main.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/plugin_core.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar_util.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar.js" type="text/javascript"></script>
	<script src="<%=path%>/script/hd/validate.js" type="text/javascript"></script>

</head>
	<body style="background:#828282">
	<input type="hidden" id="path" value="<%=path%>" />
	<input type="hidden" id="addSuccess" value="<%=addSuccess%>" />
	<div style="overflow-y:scroll">

	    <form id="formadd" method="post" action="<%=path%>/tempUser/addTempUser.action">
	    
	    <input type="hidden" id="localPhotoUrl" name="localPhotoUrl" value="" />
	    <input type="hidden" id="sex"  name="addTempUser.sex" value="" />
	    <input type="hidden" id="job_level"  name="addTempUser.job_level" value="" />
	    <input type="hidden" id="remark" name="addTempUser.remark"  value="" />
	       	 
	       	
			<table width="100%" height="30" border="0" cellspacing="0" cellpadding="0" id="box_title">
	      	  <tr>
	            <td class="left" width="6"></td>
	            <td class="title">新增坐席</td>
	          </tr>
	        </table>
	        
	       	<table width="100%" height="160px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody">
	          				<table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
					  		  		<td class="td1">账号:</td><td class="td2"><input type="text"  name="addTempUser.uname" class="inputbox1" id="uname" style="width:175px;" value=""/></td>
									<td class="td1">性别:</td><td class="td2"><select style="width: 178px; height: 21px" id="fakesex" class="blackn12" name="addTempUser.fakesex"><option value=''>...请选择</option><option value='男'>男</option><option value='女'>女</option></select></td>
								</tr>
					    		<tr>
					    			<td class="td1">密码:</td><td class="td2"><input type="text"  name="addTempUser.upass" class="inputbox1" id="upass" style="width:175px;" value=""/></td>
					  			
									<td class="td1">姓名:</td><td class="td2"><input type="text"  name="addTempUser.realname" class="inputbox1" id="realname" style="width:175px;" value=""/></td>
					  			</tr>	  		  	
					  			<tr>
					    			<td class="td1">邮件地址:</td><td class="td2"><input type="text"  name="addTempUser.email" class="inputbox1" id="email" style="width:175px;" value=""/></td>
					  		  	    <td class="td1">手机号码:</td><td class="td2"><input type="text"  name="addTempUser.cellphone" class="inputbox1" id="cellphone" style="width:175px;" value=""/></td>
								</tr>
					    		<tr >
					  		  		
									<td class="td1">分机:</td><td class="td2"><input type="text"  name="addTempUser.ext" class="inputbox1" id="ext" style="width:175px;" value=""/></td>
									<td class="td1">电话:</td><td class="td2"><input type="text"  name="addTempUser.phone" class="inputbox1" id="phone" style="width:175px;" value=""/></td>
									
					  		  	</tr>
					  		  
					  		  	<tr>
									<td class="td1">职级:</td><td class="td2"><select style="width: 178px; height: 21px" id="fakejob_level" class="blackn12" name="addTempUser.fakejob_level"><option value=''>...请选择</option><option value='坐席'>坐席</option><option value='坐席班长'>坐席班长</option></select></td>
								<td class="td1"></td>
					  		  	<td class="td2">
					  		  	</td>
					  		  	
			
					  		  	
					  		  	</tr>
					  		  	
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>
	    	
	    	   <div style="background:#f3f3f3">
	    	<table width="100%" height="50px" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  
					  		  	<tr>
								<td style="height:50px;width:160px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">备注:</td>
					  		  	<td style="height:50px;width:50px;text-align:left;">
					  		  			  		  	<textarea rows="3" cols="26"  name="addTempUser.fakeremark" id="fakeremark" >

</textarea>
					  		  	</td>
					  		  	<td style="height:50px;width:80px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">照片:</td>
					  		  	<td style="height:50px;text-align:left;">
<iframe src="<%=path%>/jsp/hd/home/usermanage/photo.jsp" name="photoframe" width="300px" height="100px" scrolling="auto">
	          				  
	          				</iframe>
					  		  	</td>
					  		  	</tr>
			</table>
			</div>
		
			
			<div style="background:#ffffff;padding-top:20px;">
			   <table width="100%" height="30px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
			   <tr>
	        		<td style="width:20%;text-align:right;padding-right:12px;">
	        		</td>
	        		<td style="width:20%;text-align:right;padding-right:20px;">
	        		  <input type="button"  value="提交" onclick="tijiao()" />
									
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:35px;">
	        		  <input type="button"  value="取消" onclick="cancelBack()" />
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:12px;">
									
	        		</td>
	        	</tr>
	       	</table>
			</div>
				
	    	
	    	
	       	<table width="100%" height="50px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody"><table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
									<td class="td2"></td>
									<td class="td2">
									</td>
								</tr>
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>
	    	
	    	<table width="100%" height="10" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  <tr>
			    <td class="left" width="7"></td>
			    <td class="mid"> </td>
			    <td class="right" width="7"></td>
			  </tr>
			</table>
			
			
	    </form>

 </div>
	</body>
</html>

<script>
var path=document.getElementById("path").value;
var addSuccess=document.getElementById("addSuccess").value;

if($.trim(addSuccess)=="addSuccess"){
	//alert("addSuccess");
	var urlpath=path+"/tempUser/listTempUser.action";
	window.location.href=urlpath;
}

function cancelBack(){
	var urlpath=path+"/tempUser/listTempUser.action";
	window.location.href=urlpath;
}
function testformsubmit(){
	var testform=document.getElementById("testform");
	testform.submit();
}
	
function getUploadPhotoUrl(){
$.ajax({
	   type: "POST",
	   url: "some.php",
	   data: "name=John&location=Boston",
	   success: function(msg){
	     alert( "Data Saved: " + msg );
	   }
	});
}
function  addTempUser(){
	var urlpath=path+"/tempUser/addTempUser.action";
	
	$.ajax({
		   type: "POST",
		   url: "some.php",
		   data: "name=John&location=Boston",
		   success: function(msg){
		     alert( "Data Saved: " + msg );
		   }
		});
}

function tijiao(){
	$("#sex").val($("#fakesex").val());
	$("#job_level").val($("#fakejob_level").val());
	$("#remark").val($("#fakeremark").val());
	//alert($("#sex").val()+$("#job_level").val()+$("#remark").val());
	if (validateAddTempUser()) {
		$('#formadd').submit();
	}
	
}

function validateAddTempUser(){
	var flag=true;//成功为true
	var alertStr="";
	var uname=$('#uname').val();
	var upass=$('#upass').val();
	var realname=$('#realname').val();
	var email=$('#email').val();
	var cellphone=$('#cellphone').val();
	var ext=$('#ext').val();
	var phone=$('#phone').val();
	var job_level=$('#fakejob_level').val();
	var remark=$('#remark').val();
	var sex=$("#fakesex").val();
	var localPhotoUrl=$("#localPhotoUrl").val();
	
	if(ValidateUtil.isNull(uname)){
		flag=false;
		alertStr+="账号不可为空!\r\n";
	}
	if(ValidateUtil.isNull(sex)){
		flag=false;
		alertStr+="请选择性别!\r\n";
	}
	if(ValidateUtil.isNull(job_level)){
		flag=false;
		alertStr+="请选择职级!\r\n";
	}
	if(ValidateUtil.isNull(localPhotoUrl)){
		flag=false;
		alertStr+="请上传照片!\r\n";
	}
	
	
	if(!flag){
		alert(alertStr);
	}
	
	return flag;
}
/*
var isRightUploadPhotoFalg=false;
function shangchuan(){
	isRightUploadPhotoFalg=false;
	var photoUrl = document.getElementById("uploadPhoto").value;
	var jobNumber=$('#uname').val();
	var urlpath=path+"/tempUser/uploadPhotoToTempDir.action?photoUrl="+photoUrl+"&jobNumber="+jobNumber;
	var tempUrl="";
	$.ajax({
		   type: "POST",
		   url: urlpath,
		   success: function(msg){
		     var mm=$.trim(msg);
		     if(msg=="NO"){
		     }else{
		    	 tempUrl=path+mm;
		    	 //js换图片
		    	 var hhtt="<img src=\""+tempUrl+"\" id=\"tempPhotoFileUrl\"/>";
		    	 $("#uploadPhotoView").html(hhtt);
		    	 //uploadPhotoViewParent  
		    	 $("#uploadPhotoViewParent").html("");
		    	 $("#uploadPhotoViewParent").hide();
		    	 isRightUploadPhotoFalg=true;
		    	 alert(mm);
		    	 document.getElementById("localPhotoUrl").value=mm;
		    	 
		     }
		   }
		});
	
}


function strutsUpload(){
	
	alert("strutsUpload");
	var strutsFormPhoto=document.getElementById("strutsFormPhoto");
	strutsFormPhoto.submit();
}
*/
$("#uname").blur( function () { 
	//给子页面赋值
	var jobnum=document.getElementById("uname").value;
	window.frames[0].window.receivJobNum(jobnum);
} );
function tt(){
	alert("tt");
}
//上传成功后,需要页面显示图片的web路径和在服务器上的路径
function rebackUrl(showurl,writeurl){
	//alert(showurl+"--"+writeurl);
	document.getElementById("localPhotoUrl").value=writeurl;
	
}
</script>


 

里面嵌套的照片页面photo.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page import="org.hd.tempuser.model.TempUser" %>
<%
	String path = request.getContextPath();
%>
<%
	String addSuccess = "";
   if(request.getAttribute("addSuccess")!=null){
	   addSuccess=(String)request.getAttribute("addSuccess");
   }
%>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=path%>/resource/css/style.css" rel="stylesheet" type="text/css" />
	<script src="<%=path%>/script/jquery-1.7.1.js" type="text/javascript"></script>

</head>
	<body style="background:#f3f3f3">
	<input type="hidden" id="path" value="<%=path%>" />
	请上传图片
		 <form id="testform" action="<%=path%>/upphoto/upphotoServlet" method="post" enctype="multipart/form-data">
					  		  	     <input type="file"  id="testfile" name="uploadPhoto" class="inputbox1" style="width:175px;" value=""/>
					  		  	     <input type="hidden"  id="gonghao" name="gonghao" value=""/>
					  		  		 <input type="hidden"  id="jobNumberTest" name="jobNumberTest" value="gh.value"/>
					  		  		  <input type="button"  value="上传" onclick="testformsubmit()" />
					  		  	 
					  		  	 </form>
	</body>
</html>

<script>
var path=document.getElementById("path").value;


function testformsubmit(){
	var testform=document.getElementById("testform");
	var gonghao=document.getElementById("gonghao").value;
	if(gonghao==null||gonghao==""||gonghao=="null"){
		alert("请先输入账号!");
	}else{
		testform.submit();
	}
	
}
	
function gg(){
	//调用父页面方法
	parent.window.tt();
}


function receivJobNum(jobnum){
	document.getElementById("gonghao").value=jobnum;
}
</script>


 

编辑用户的时候也需要编辑照片,但这个逻辑稍稍不一样,还是一个编辑页面,iframe中嵌套一个照片页面。

user_edit.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page import="org.hd.tempuser.model.TempUser" %>
<%
	String path = request.getContextPath();
%>
<%
   String tempuserid="";
   if(request.getParameter("tempuserid")!=null){
	   tempuserid=(String)request.getParameter("tempuserid");
   }
   
	String editSuccess = "";
	   if(request.getAttribute("editSuccess")!=null){
		   editSuccess=(String)request.getAttribute("editSuccess");
	   }
%>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=path%>/resource/css/style.css" rel="stylesheet" type="text/css" />
	<script src="<%=path%>/script/jquery-1.7.1.js" type="text/javascript"></script>
	<script src="<%=path%>/script/queryHeader.js" type="text/javascript"></script>
	<script src="<%=path%>/script/main.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/plugin_core.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar_util.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar.js" type="text/javascript"></script>
	<script src="<%=path%>/script/hd/validate.js" type="text/javascript"></script>
</head>
	<body style="background:#828282">
<input type="hidden" id="path" value="<%=path%>" />
<input type="hidden" id="tempuserid" value="<%=tempuserid%>" />
<input type="hidden" id="editSuccess" value="<%=editSuccess%>" />

		
	    <form id="formedit" method="post" action="<%=path%>/tempUser/submitEditTempUser.action">
	        <input type="hidden" id="ischangePhoto" name="ischangePhoto" value="NO" />
	       	<input type="hidden" id="localPhotoUrl" name="localPhotoUrl" value="" />
	       	<input type="hidden" id="oldlocalPhotoUrl" name="oldlocalPhotoUrl" value="<s:property value='#request.editTempUser.tempUrl.trim()'/>  " />
			<input type="hidden" id="hduid" name="editTempUser.hduid" value="<s:property value='#request.editTempUser.hduid.trim()'/>  " />
			
			
	    <input type="hidden" id="sex"  name="editTempUser.sex" value="" />
	    <input type="hidden" id="job_level"  name="editTempUser.job_level" value="" />
	    <input type="hidden" id="remark" name="editTempUser.remark"  value="" />
	       	 
		<!-- 临时转换值 -->
		<input type="hidden" id="tempsex"   value="<s:property value='#request.editTempUser.sex'/>" />
	    <input type="hidden" id="tempjob_level"  value="<s:property value='#request.editTempUser.job_level'/>" />
	    
			<table width="100%" height="30" border="0" cellspacing="0" cellpadding="0" id="box_title">
	      	  <tr>
	            <td class="left" width="6"></td>
	            <td class="title">编辑坐席信息</td>
	          </tr>
	        </table>
	        
	       	<table width="100%" height="160px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody">
	          				<table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
					  		  		<td class="td1">账号:</td><td class="td2"><input type="text" value="<s:property value='#request.editTempUser.uname'/>  " name="editTempUser.uname" class="inputbox1" id="uname" style="width:175px;" </td>
									<td class="td1">性别:</td><td class="td2"><select style="width: 178px; height: 21px" id="fakesex" class="blackn12" name="editTempUser.fake"><option value=''>...请选择</option><option value='男'>男</option><option value='女'>女</option></select></td>
								</tr>
					    		<tr>
					    			<td class="td1">密码:</td><td class="td2"><input type="text" value="<s:property value='#request.editTempUser.upass'/>"  name="editTempUser.upass" class="inputbox1" id="upass" style="width:175px;" </td>
					  			
									<td class="td1">姓名:</td><td class="td2"><input type="text"  value="<s:property value='#request.editTempUser.realname'/>"  name="editTempUser.realname" class="inputbox1" id="realname" style="width:175px;" </td>
					  			</tr>	  		  	
					  			<tr>
					    			<td class="td1">邮件地址:</td><td class="td2"><input type="text"  value="<s:property value='#request.editTempUser.email'/>"  name="editTempUser.email" class="inputbox1" id="email" style="width:175px;" </td>
					  		  	    <td class="td1">手机号码:</td><td class="td2"><input type="text"  value="<s:property value='#request.editTempUser.cellphone'/>"   name="editTempUser.cellphone" class="inputbox1" id="cellphone" style="width:175px;" </td>
								</tr>
					    		<tr >
					  		  		
									<td class="td1">分机:</td><td class="td2"><input type="text"  value="<s:property value='#request.editTempUser.ext'/>"  name="editTempUser.ext" class="inputbox1" id="ext" style="width:175px;" </td>
									<td class="td1">电话:</td><td class="td2"><input type="text"  value="<s:property value='#request.editTempUser.phone'/>" name="editTempUser.phone" class="inputbox1" id="phone" style="width:175px;" </td>
									
					  		  	</tr>
					  		  
					  		  	<tr>
									<td class="td1">职级:</td><td class="td2"><select style="width: 178px; height: 21px" id="fakejob_level" class="blackn12" name="editTempUser.fake"><option value=''>...请选择</option><option value='坐席'>坐席</option><option value='坐席班长'>坐席班长</option></select></td>
								
									<td class="td1"></td><td class="td2"></td>
					  		  	</tr>
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>


	    	   <div style="background:#f3f3f3">
	    	<table width="100%" height="50px" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  
					  		  	<tr>
								<td style="height:50px;width:160px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">备注:</td>
					  		  	<td style="height:50px;width:50px;text-align:left;">
<textarea rows="3" cols="26"  name="editTempUser.fakeremark" id="fakeremark" >
     <s:property value='#request.editTempUser.remark'/>  
</textarea>
					  		  	</td>
					  		  	<td style="height:50px;width:80px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">照片:</td>
					  		  	<td style="height:50px;text-align:left;">
					  		  	
					  		  	<div id="photoshow" >
					  		  	<img src="<%=path%><s:property value='#request.editTempUser.tempUrl'/>" width="75px" height="95px" id="person_img"/>
					  		  	<input type="button"  onclick="editPhotoFunc()" value="编辑照片" />
		
					  		  	</div>
					  		  		    	   <div id="photoiframe" style="background:#f3f3f3;display:none">
					  		  		    	 <iframe src="<%=path%>/jsp/hd/home/usermanage/editphoto.jsp" name="photoframe" width="300px" height="100px" scrolling="auto">
	                                        </iframe>
					  		  		    	   </div>

					  		  	</td>
					  		  	</tr>
			</table>
			</div>
		
						
			<div style="background:#ffffff;padding-top:20px;">
			   <table width="100%" height="30px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
			   <tr>
	        		<td style="width:20%;text-align:right;padding-right:12px;">
	        		</td>
	        		<td style="width:20%;text-align:right;padding-right:20px;">
									<input type="button"  value="提交" onclick="tijiao()" />
								
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:35px;">
	        		  <input type="button"  value="返回" onclick="javascript:history.back(-1);" />
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:12px;">
									
	        		</td>
	        	</tr>
	       	</table>
			</div>
				
	    	
	    	
	       	<table width="100%" height="50px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody"><table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
									<td class="td2"></td>
									<td class="td2">
									</td>
								</tr>
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>
	    	
	    	<table width="100%" height="10" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  <tr>
			    <td class="left" width="7"></td>
			    <td class="mid"> </td>
			    <td class="right" width="7"></td>
			  </tr>
			</table>
			
			
	    </form>
	</body>
</html>

<script>
var path=document.getElementById("path").value;
var editSuccess=document.getElementById("editSuccess").value;

if($.trim(editSuccess)=="editSuccess"){
	//alert("editSuccess");
	var urlpath=path+"/tempUser/listTempUser.action";
	window.location.href=urlpath;
}
//下拉框赋值
	var sexone=$.trim($("#tempsex").val());
	setSelectValue('fakesex',sexone);
	var jobone=$.trim($("#tempjob_level").val());
	setSelectValue('fakejob_level',jobone);
	
function setSelectValue(sid,va){
	var strva=$.trim(va);
	var opt = document.getElementById(sid);
	 for (var i = 0; i < opt.length; i++) {
		 if($.trim(opt[i].innerText)==strva){
			 opt.options[i].selected=true;
		 }
	}
}

function editPhotoFunc(){
	$("#photoiframe").show();
	$("#photoshow").hide();
}

function cancelEditPhotoFunc(){
	$("#photoshow").show();
	$("#photoiframe").hide();
	
}

function testformsubmit(){
	var testform=document.getElementById("testform");
	testform.submit();
}
	

function tijiao(){
	var ssxx=$.trim($("#fakesex").val());
	$("#sex").val(ssxx);
	var jobll=$.trim($("#fakejob_level").val());
	$("#job_level").val(jobll);
	var fakrem=$.trim($("#fakeremark").val());
	$("#remark").val(fakrem);
	//alert($("#sex").val()+$("#job_level").val()+$("#remark").val());
	if (validateAddTempUser()) {
		$('#formedit').submit();
	}
	
}

function validateAddTempUser(){
	var flag=true;//成功为true
	var alertStr="";
	var uname=$('#uname').val();
	var upass=$('#upass').val();
	var realname=$('#realname').val();
	var email=$('#email').val();
	var cellphone=$('#cellphone').val();
	var ext=$('#ext').val();
	var phone=$('#phone').val();
	var job_level=$('#fakejob_level').val();
	var remark=$('#remark').val();
	var sex=$("#fakesex").val();
	var localPhotoUrl=$("#localPhotoUrl").val();
	var ischangePhoto=$.trim($("#ischangePhoto").val());
	
	if(ValidateUtil.isNull(uname)){
		flag=false;
		alertStr+="账号不可为空!\r\n";
	}
	if(ValidateUtil.isNull(sex)){
		flag=false;
		alertStr+="请选择性别!\r\n";
	}
	if(ValidateUtil.isNull(job_level)){
		flag=false;
		alertStr+="请选择职级!\r\n";
	}
	if(ischangePhoto=="YES"){
		var local=$.trim($("#localPhotoUrl").val());
		if(local==""){
			alertStr+="请上传照片!\r\n";
		}
	}else{
		document.getElementById("localPhotoUrl").value=document.getElementById("oldlocalPhotoUrl").value;
	}
	
	
	if(!flag){
		alert(alertStr);
	}
	
	return flag;
}
$("#uname").blur( function () { 
	//给子页面赋值
	var jobnum=document.getElementById("uname").value;
	window.frames[0].window.receivJobNum(jobnum);
} );
//给子页面赋值,这个是为了子页面调用 
function geivUnameToChild(){
	var jobnum=document.getElementById("uname").value;
	window.frames[0].window.receivJobNum(jobnum);
}
function tt(){
	alert("tt");
}
//上传成功后,需要页面显示图片的web路径和在服务器上的路径
function rebackUrl(showurl,writeurl){
	//alert(showurl+"--"+writeurl);
	$("#ischangePhoto").val("YES");
	document.getElementById("localPhotoUrl").value=writeurl;
	//刷新子页面
}
</script>


 

editphoto.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page import="org.hd.tempuser.model.TempUser" %>
<%
	String path = request.getContextPath();
%>
<%
	String addSuccess = "";
   if(request.getAttribute("addSuccess")!=null){
	   addSuccess=(String)request.getAttribute("addSuccess");
   }
%>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=path%>/resource/css/style.css" rel="stylesheet" type="text/css" />
	<script src="<%=path%>/script/jquery-1.7.1.js" type="text/javascript"></script>

</head>
	<body style="background:#f3f3f3">
	<input type="hidden" id="path" value="<%=path%>" />
	请上传图片
		 <form id="testform" action="<%=path%>/upphoto/upphotoServlet" method="post" enctype="multipart/form-data">
					  		  	     <input type="file"  id="testfile" name="uploadPhoto" class="inputbox1" style="width:175px;" value=""/>
					  		  	     <input type="hidden"  id="gonghao" name="gonghao" value=""/>
					  		  		 <input type="hidden"  id="jobNumberTest" name="jobNumberTest" value="gh.value"/>
					  		  		  <input type="button"  value="上传" onclick="testformsubmit()" />
					  		  	 <input type="button"  value="取消" onclick="cancelPhoto()" />
					  		  	 
					  		  	 </form>
	</body>
</html>

<script>
var path=document.getElementById("path").value;

//获取工号
parent.window.geivUnameToChild();

function testformsubmit(){
	var testform=document.getElementById("testform");
	var gonghao=document.getElementById("gonghao").value;
	if(gonghao==null||gonghao==""||gonghao=="null"){
		alert("请先输入账号!");
	}else{
		testform.submit();
	}
	
}
	
function gg(){
	//调用父页面方法
	parent.window.tt();
}


function receivJobNum(jobnum){
	document.getElementById("gonghao").value=jobnum;
}

function cancelPhoto(){
	parent.window.cancelEditPhotoFunc();
}
</script>


user_view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ page import="org.hd.tempuser.model.TempUser" %>
<%
	String path = request.getContextPath();
%>
<%
   String tempuserid="";
   if(request.getParameter("tempuserid")!=null){
	   tempuserid=(String)request.getParameter("tempuserid");
   }
%>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<link href="<%=path%>/resource/css/style.css" rel="stylesheet" type="text/css" />
	<script src="<%=path%>/script/jquery-1.7.1.js" type="text/javascript"></script>
	<script src="<%=path%>/script/queryHeader.js" type="text/javascript"></script>
	<script src="<%=path%>/script/main.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/plugin_core.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar_util.js" type="text/javascript"></script>
	<script src="<%=path%>/script/plugin/calendar/calendar.js" type="text/javascript"></script>

</head>
	<body style="background:#828282">
<input type="hidden" id="path" value="<%=path%>" />
<input type="hidden" id="tempuserid" value="<%=tempuserid%>" />
		
	    <form id="formadd" method="post" action="<%=path%>/tempUser/viewTempUser.action">
	       	<input type="hidden" id="localPhotoUrl" name="localPhotoUrl" value="" />
			<table width="100%" height="30" border="0" cellspacing="0" cellpadding="0" id="box_title">
	      	  <tr>
	            <td class="left" width="6"></td>
	            <td class="title">详细信息</td>
	          </tr>
	        </table>
	        
	       	<table width="100%" height="160px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody">
	          				<table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
					  		  		<td class="td1">账号:</td><td class="td2"><input type="text" disabled readonly value="<s:property value='#request.viewTempUser.uname'/>  " name="viewTempUser.uname" class="inputbox1" id="uname" style="width:175px;" /></td>
									<td class="td1">性别:</td><td class="td2">
									<input type="text"  disabled readonly value="<s:property value='#request.viewTempUser.sex'/>  " name="viewTempUser.sex" class="inputbox1" id="sex" style="width:175px;" />
									</td>
								</tr>
					    		<tr>
					    			<td class="td1">密码:</td><td class="td2"><input type="text"  disabled  readonly value="<s:property value='#request.viewTempUser.upass'/>"  name="viewTempUser.upass" class="inputbox1" id="upass" style="width:175px;" /></td>
					  			
									<td class="td1">姓名:</td><td class="td2"><input type="text"   disabled  readonly value="<s:property value='#request.viewTempUser.realname'/>"  name="viewTempUser.realname" class="inputbox1" id="realname" style="width:175px;" /></td>
					  			</tr>	  		  	
					  			<tr>
					    			<td class="td1">邮件地址:</td><td class="td2"><input type="text"   disabled readonly  value="<s:property value='#request.viewTempUser.email'/>"  name="viewTempUser.email" class="inputbox1" id="email" style="width:175px;" /></td>
					  		  	    <td class="td1">手机号码:</td><td class="td2"><input type="text"   disabled readonly  value="<s:property value='#request.viewTempUser.cellphone'/>"   name="viewTempUser.cellphone" class="inputbox1" id="cellphone" style="width:175px;"/> </td>
								</tr>
					    		<tr >
					  		  		
									<td class="td1">分机:</td><td class="td2"><input type="text"  disabled  readonly  value="<s:property value='#request.viewTempUser.ext'/>"  name="viewTempUser.ext" class="inputbox1" id="ext" style="width:175px;" /></td>
									<td class="td1">电话:</td><td class="td2"><input type="text"  disabled  readonly  value="<s:property value='#request.viewTempUser.phone'/>" name="viewTempUser.phone" class="inputbox1" id="phone" style="width:175px;" /></td>
									
					  		  	</tr>
					  		  
					  		  	<tr>
									<td class="td1">职级:</td><td class="td2">
									<input type="text"  disabled readonly value="<s:property value='#request.viewTempUser.job_level'/>  " name="viewTempUser.job_level" class="inputbox1" id="job_level" style="width:175px;" />
									</td>
								
									<td class="td1"></td><td class="td2"></td>
					  		  	</tr>
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>


	    	   <div style="background:#f3f3f3">
	    	<table width="100%" height="50px" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  
					  		  	<tr>
								<td style="height:50px;width:160px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">备注:</td>
					  		  	<td style="height:50px;width:50px;text-align:left;">
<textarea  disabled readonly rows="3" cols="26"  name="addTempUser.fakeremark" id="fakeremark" >
  <s:property value='#request.viewTempUser.remark'/>  
</textarea>
					  		  	</td>
					  		  	<td style="height:50px;width:80px;text-align:right;padding-right:12px;font-size:12px; color:#333; ">照片:</td>
					  		  	<td style="height:50px;text-align:left;">
<img src="<%=path%><s:property value='#request.viewTempUser.tempUrl'/>" width="75px" height="95px" id="person_img"/>
					  		  	</td>
					  		  	</tr>
			</table>
			</div>
		
						
			<div style="background:#ffffff;padding-top:20px;">
			   <table width="100%" height="30px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
			   <tr>
	        		<td style="width:20%;text-align:right;padding-right:12px;">
	        		</td>
	        		<td style="width:20%;text-align:right;padding-right:20px;">
									
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:35px;">
	        		  <input type="button"  value="返回" onclick="javascript:history.back(-1);" />
	        		</td>
	        		<td style="width:30%;text-align:left;padding-left:12px;">
									
	        		</td>
	        	</tr>
	       	</table>
			</div>
				
	    	
	    	
	       	<table width="100%" height="50px" border="0" cellspacing="0" cellpadding="0" class="nbox11" style="padding-left:6px">
	       		<tr>
	        		<td>
	          			<div class="contentBody"><table class="nbox14 blackn12" border="0" cellspacing="0" cellpadding="0" width="800px">
					  		  	<tr >
									<td class="td2"></td>
									<td class="td2">
									</td>
								</tr>
			  				</table>
			  			</div>
	      			</td>
	      		</tr>
	    	</table>
	    	
	    	<table width="100%" height="10" border="0" cellpadding="0" cellspacing="0" id="box_foot">
			  <tr>
			    <td class="left" width="7"></td>
			    <td class="mid"> </td>
			    <td class="right" width="7"></td>
			  </tr>
			</table>
			
			
	    </form>
	</body>
</html>

<script>
var path=document.getElementById("path").value;

</script>


 

 

 

要说的有几点,编辑用户可能修改照片,可能不修改。

我分了这两种情况。用一个参数来区别。

下面是所有action

AddTempUserAction.java

package org.hd.tempuser.action;

import java.io.PrintWriter;
import java.sql.Blob;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.sql.BLOB;

import org.apache.struts2.ServletActionContext;
import org.hd.tempuser.model.TempUser;
import org.hd.tempuser.service.TempUserService;
import org.hd.util.BlobUtil;
import org.hibernate.SessionFactory;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.hibernate.ConfigurableSessionFactoryBean;
import org.rd.framework.query.sort.SortCriterion;
import org.rd.framework.struts.action.CommonAction;

import org.hibernate.impl.SessionFactoryImpl;

import com.opensymphony.xwork2.ActionContext;

public class AddTempUserAction extends CommonAction{
	private TempUserService tempUserService = (TempUserService)ContainerManager.getComponent(TempUserService.BEAN_ID);
	
	private TempUser addTempUser;
	private String localPhotoUrl="";
	public String addTempUser() throws Exception{
		
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); 
		HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		
		if(getAddTempUser()!=null){
			if(getLocalPhotoUrl()==null||getLocalPhotoUrl().trim().equals("")){
				
			}else{
				System.out.println("临时上传路径:"+getLocalPhotoUrl());
				String loginUserJobNum=this.getLoginUserJobNumber();
				tempUserService.addTempUserWriteBlob(getAddTempUser(),getLocalPhotoUrl(),loginUserJobNum);
			}
		}
		out.println("YES");
		request.setAttribute("addSuccess", "addSuccess");
		return SUCCESS;
	}
	
	public String execute() throws Exception{
		return SUCCESS;
	}

	public TempUser getAddTempUser() {
		return addTempUser;
	}

	public void setAddTempUser(TempUser addTempUser) {
		this.addTempUser = addTempUser;
	}

	public String getLocalPhotoUrl() {
		return localPhotoUrl;
	}

	public void setLocalPhotoUrl(String localPhotoUrl) {
		this.localPhotoUrl = localPhotoUrl;
	}
}


DelTempUserAction.java

 

package org.hd.tempuser.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hd.tempuser.model.TempUser;
import org.hd.tempuser.service.TempUserService;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.query.interceptor.QueryParameterAware;
import org.rd.framework.query.sort.SortCriterion;
import org.rd.framework.struts.action.BodyListAction;
import org.rd.framework.util.DateUtils;

import com.opensymphony.xwork2.ActionContext;

public class DelTempUserAction extends BodyListAction implements QueryParameterAware{
	private TempUserService tempUserService = (TempUserService)ContainerManager.getComponent(TempUserService.BEAN_ID);
	private String tempuserid="";
	private TempUser delTempUser=null;
	
	public String delTempUser() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); 
		HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
//		setTempuserid(request.getParameter("tempuserid"));
		if(request.getParameter("tempuserid")!=null&&!request.getParameter("tempuserid").trim().equals("")){
			tempUserService.delTempUserById(request.getParameter("tempuserid"));
			out.println("YES");
		}else{
			out.println("NO");
		}
		
		return NONE;
	}
	
	public String execute() throws Exception{
		return SUCCESS;
	}

	public String getTempuserid() {
		return tempuserid;
	}

	public void setTempuserid(String tempuserid) {
		this.tempuserid = tempuserid;
	}

	public TempUser getDelTempUser() {
		return delTempUser;
	}

	public void setDelTempUser(TempUser delTempUser) {
		this.delTempUser = delTempUser;
	}


}


EditTempUserAction.java

package org.hd.tempuser.action;

import java.io.PrintWriter;
import java.sql.Blob;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oracle.sql.BLOB;

import org.apache.struts2.ServletActionContext;
import org.hd.login.service.LoginService;
import org.hd.tempuser.model.TempUser;
import org.hd.tempuser.service.TempUserService;
import org.hd.util.BlobUtil;
import org.hd.util.RamdomUtil;
import org.hibernate.SessionFactory;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.hibernate.ConfigurableSessionFactoryBean;
import org.rd.framework.query.sort.SortCriterion;
import org.rd.framework.struts.action.CommonAction;

import org.hibernate.impl.SessionFactoryImpl;

import com.opensymphony.xwork2.ActionContext;

public class EditTempUserAction extends CommonAction{
	private TempUserService tempUserService = (TempUserService)ContainerManager.getComponent(TempUserService.BEAN_ID);
	private LoginService hdLoginService = (LoginService)ContainerManager.getComponent(LoginService.BEAN_ID);
	
	private TempUser editTempUser;
	private String localPhotoUrl="";
	private String ischangePhoto="";
	
	public String editTempUser() throws Exception{
		//先取数据展现
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); 
		HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		if(request.getParameter("tempuserid")!=null&&!request.getParameter("tempuserid").trim().equals("")){
			TempUser tt=tempUserService.getTempUserById(request.getParameter("tempuserid"));
			String photoPath=hdLoginService.getTempPhoto(tt);
			photoPath+="?randomStr="+RamdomUtil.getRamdomDateStr();//加随机参数
			tt.setTempUrl(photoPath);
			setEditTempUser(tt);
		}else{
		}
		return SUCCESS;
	}
	public String submitEditTempUser() throws Exception{
		//提交数据
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); 
		HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		if(getEditTempUser()!=null){
			String hduid=getEditTempUser().getHduid().trim();
			getEditTempUser().setHduid(hduid);
			String loginUserJobNum=this.getLoginUserJobNumber();
			
            if(getIschangePhoto()!=null&&getIschangePhoto().trim().equals("YES")){
				//修改照片
    			if(getLocalPhotoUrl()==null||getLocalPhotoUrl().trim().equals("")){
    				
    			} else {
    				System.out.println("临时上传路径:" + getLocalPhotoUrl());
    				tempUserService.clearPhotoBlob(getEditTempUser());
    				tempUserService.editTempUserWriteBlob(getEditTempUser(),
    						getLocalPhotoUrl(), loginUserJobNum);
    			}
			}else{
				//不修改照片
				tempUserService.editTempUserWithoutBlob(getEditTempUser(), loginUserJobNum);
			}
            request.setAttribute("editSuccess", "editSuccess");
			

			
		}
		return SUCCESS;
	}
	public String execute() throws Exception{
		return SUCCESS;
	}

	public String getLocalPhotoUrl() {
		return localPhotoUrl;
	}

	public void setLocalPhotoUrl(String localPhotoUrl) {
		this.localPhotoUrl = localPhotoUrl;
	}

	public TempUser getEditTempUser() {
		return editTempUser;
	}

	public void setEditTempUser(TempUser editTempUser) {
		this.editTempUser = editTempUser;
	}
	public String getIschangePhoto() {
		return ischangePhoto;
	}
	public void setIschangePhoto(String ischangePhoto) {
		this.ischangePhoto = ischangePhoto;
	}
}


ListTempUserAction.java

package org.hd.tempuser.action;

import org.hd.tempuser.service.TempUserService;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.query.interceptor.QueryParameterAware;
import org.rd.framework.query.sort.SortCriterion;
import org.rd.framework.struts.action.BodyListAction;
import org.rd.framework.util.DateUtils;

public class ListTempUserAction extends BodyListAction implements QueryParameterAware{
	private TempUserService tempUserService = (TempUserService)ContainerManager.getComponent(TempUserService.BEAN_ID);
	public String listTempUser() throws Exception{
		if (firstSorter == null && null == paginationSupport.getSorter()) {
			firstSorter = new SortCriterion();
	        firstSorter.setField("queryby.hduid");  
	        firstSorter.setOrder(SortCriterion.DESCENDING);      
 	    }else if(firstSorter == null && paginationSupport.getSorter() != null){
	    	firstSorter = paginationSupport.getSorter();
	    }
	    paginationSupport.setSorter(firstSorter);
	    bodyList = tempUserService.getTempUserList(queryParams, paginationSupport);
		return SUCCESS;
	}
	
	public String execute() throws Exception{
		return SUCCESS;
	}
	
    public String getTableid() {
		return "HD_USER_000";
	}
}


ViewTempUserAction.java

package org.hd.tempuser.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.hd.login.service.LoginService;
import org.hd.tempuser.model.TempUser;
import org.hd.tempuser.service.TempUserService;
import org.hd.util.RamdomUtil;
import org.rd.framework.common.container.ContainerManager;
import org.rd.framework.query.interceptor.QueryParameterAware;
import org.rd.framework.query.sort.SortCriterion;
import org.rd.framework.struts.action.BodyListAction;
import org.rd.framework.util.DateUtils;

import com.opensymphony.xwork2.ActionContext;

public class ViewTempUserAction extends BodyListAction implements QueryParameterAware{
	private TempUserService tempUserService = (TempUserService)ContainerManager.getComponent(TempUserService.BEAN_ID);
	private LoginService hdLoginService = (LoginService)ContainerManager.getComponent(LoginService.BEAN_ID);
	
	private TempUser viewTempUser=null;
	private String command="";
	
	public String viewTempUser() throws Exception{
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); 
		HttpServletRequest request  = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); 
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		if(request.getParameter("tempuserid")!=null&&!request.getParameter("tempuserid").trim().equals("")){
			TempUser tt=tempUserService.getTempUserById(request.getParameter("tempuserid"));
			String photoPath=hdLoginService.getTempPhoto(tt);
			photoPath+="?randomStr="+RamdomUtil.getRamdomDateStr();//加随机参数
			tt.setTempUrl(photoPath);
			setViewTempUser(tt);
		}else{
		}
		return SUCCESS;
	}
	
	public String execute() throws Exception{
		return SUCCESS;
	}

	public TempUser getViewTempUser() {
		return viewTempUser;
	}

	public void setViewTempUser(TempUser viewTempUser) {
		this.viewTempUser = viewTempUser;
	}

	public String getCommand() {
		return command;
	}

	public void setCommand(String command) {
		this.command = command;
	}
	
}

 struts_tempuser.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name="tempUser" extends="cx-struts-default" namespace="/tempUser">
		<action name="listTempUser" class="org.hd.tempuser.action.ListTempUserAction" method="listTempUser">
		     <result name="success">/jsp/hd/home/usermanage/uesrs.jsp</result>
		</action>
		<action name="delTempUser" class="org.hd.tempuser.action.DelTempUserAction" method="delTempUser">
		</action>
		<action name="addTempUser" class="org.hd.tempuser.action.AddTempUserAction" method="addTempUser">
		     <result name="success">/jsp/hd/home/usermanage/add_user.jsp</result>
		</action>
		<action name="viewTempUser" class="org.hd.tempuser.action.ViewTempUserAction" method="viewTempUser">
		     <result name="success">/jsp/hd/home/usermanage/user_view.jsp</result>
		</action>
		<action name="editTempUser" class="org.hd.tempuser.action.EditTempUserAction" method="editTempUser">
		     <result name="success">/jsp/hd/home/usermanage/user_edit.jsp</result>
		</action>
		<action name="submitEditTempUser" class="org.hd.tempuser.action.EditTempUserAction" method="submitEditTempUser">
		     <result name="success">/jsp/hd/home/usermanage/user_edit.jsp</result>
		</action>
		<action name="uploadPhotoToTempDir" class="org.hd.tempuser.action.UploadPhotoAction" method="uploadPhotoToTempDir">
		</action>
		
		<action name="uploadWithStruts" class="org.hd.tempuser.action.UploadWithStrutsAction" method="uploadWithStruts">
            <!-- 限制图片的格式和图片的大小 -->
            <interceptor-ref name="fileUpload">
                <param name="allowedTypes">
                    image/bmp,image/png,image/gif,image/jpeg,image/jpg
                </param>
                <param name="maximumSize">102400</param>
            </interceptor-ref>
            <!-- 默认的拦截器,必须要写 -->
            <interceptor-ref name="defaultStack" />
            <result name="success">/jsp/hd/home/usermanage/add_user.jsp</result>
        </action>
		
		<action name="goPageuploadWithStruts" class="org.hd.tempuser.action.UploadWithStrutsAction">
           <result name="success">/jsp/hd/home/usermanage/add_user.jsp</result>
        </action>
		
	</package>
</struts>


 

 

 

至于读取blob,看第二篇文章吧

(二)上传图片至服务器,写入到数据库Blob字段中,以及从数据库读取Blob信息(iframe父子页面传值)


 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(数据库,iframe,String,服务器,Class,Path)