文章标签 ‘源码’
2013十二月20

Nutz:通过URL路径查找对应的类及入口函数

由于Nutz是零配置的,所以通过URL找到处理类以及跳转的页面,就显得很麻烦,不方便维护。

于是,我在大神兽的指导下,实现如下功能:在项目启动时,将URL路径、类、方法、以及跳转页面写入项目中的一个文件中,方便查看。

@UrlMappingBy(value=UrlMappingSet.class)
public class MainModule { 
}

在Nutz入口类,加入 @UrlMappingBy。

UrlMappingSet.java 实现在 /WEB-INF/ 目录下生成 paths.txt 文件,记录路径,文件格式如下:
       QQ截图20131220094847
UrlMappingSet.java 源码:
package com.hits.core;

import java.io.File;
import java.lang.reflect.Method;

import org.nutz.lang.Files;
import org.nutz.lang.Lang;
import org.nutz.mvc.ActionChainMaker;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.impl.UrlMappingImpl;

/**
 * 类描述: 创建人:Wizzer 联系方式:www.wizzer.cn 创建时间:2013-12-19 下午10:36:17
 * 
 * @version
 */
public class UrlMappingSet extends UrlMappingImpl {
	private static int count = 0;

	public void add(ActionChainMaker maker, ActionInfo ai, NutConfig config) {
		super.add(maker, ai, config);
		printActionMappingThis(ai);

	}

	protected void printActionMappingThis(ActionInfo ai) {

		String[] paths = ai.getPaths();
		StringBuilder sb = new StringBuilder();
		if (null != paths && paths.length > 0) {
			sb.append(paths[0]);
			for (int i = 1; i < paths.length; i++)
				sb.append(",").append(paths[i]);
		} else {
			throw Lang.impossible();
		}
		sb.append("\n");
		// 打印方法名
		Method method = ai.getMethod();
		String str;
		if (null != method)
			str = String.format("%-30s : %-10s", Lang.simpleMetodDesc(method),
					method.getReturnType().getSimpleName());
		else
			throw Lang.impossible();

		sb.append("\t" + ai.getModuleType().getName());
		sb.append("\n\r");
		sb.append("\t" + str);
		sb.append("\n");
		String filepath = Mvcs.getServletContext().getRealPath("/WEB-INF/")
				+ "/paths.txt";
		File f = new File(filepath);
		if (count == 0) {
			Files.write(f, sb.toString());
		} else {

			Files.appendWrite(f, sb.toString());
		}
		count++;
	}
}
2013三月25

Nutz:Java开发框架搭建基本完成

一直想拥有一个开发快捷、界面美观、用户体验好的java开发框架,网罗不来只好自己动手,现在框架基础功能已完成,界面还需要美工优化一下。(以下图片点击查看全图)

1

 

购买咨询Q:11624317
验证信息:框架

技术:Nutz + Velocity + c3p0 + zDialog +  jQuery + zTree

环境:JDK + Eclipse +Tomcat + Oracle/MySQL

1、系统采用国产开源Nutz框架,实现项目的“零配置”(这可比SSH轻松多了),Nutz在一个类中可以随意定义访问地址,返回String、JSON、对象或跳转到具体页面,也可以利用Velocity打印结果;
2、系统集成泽元CMS1.0系统中的弹出窗口及页面验证、控制JS,并结合jquery easyui实现标签页;
3、系统无缝集成jQuery,jquery和nutz真是天作之合,可方便的实现ajax功能,另外你也可以使用velocity在页面输出内容,比较灵活;
4、已完成系统管理模块,数据表设计合理,权限控制到按钮级,可按机构建用户角色等。

下面是一段简单的Nutz类实现,Nutz更多介绍可以访问官网:http://nutzam.com/

@IocBean
@At("/private")//访问路径
@Filters({ @By(type = GlobalsFilter.class) })
public class LoginAction extends BaseAction {

	@At //访问路径,不指定则为方法名称,即:/private/logout
	@Ok(">>:/private/login")//外连接,跳转到 /private/login
	public void logout(HttpSession session) {
		session.removeAttribute("userSession");
	}

	@At("/login")
	@Ok("->:/private/login.html")//内连接,输出到 /private/login.html
	public void login(HttpServletRequest req) {
		req.setAttribute("menulist", "helloworld");//页面可以用velocity语言输出
	}
	@At
	@Ok("raw") //返回字符串类型,也可以是json、对象等
	public int Online(@Param("loginname") String loginname,HttpSession session) { 
		Sys_user user = (Sys_user) session.getAttribute("userSession");
		if(user==null){ 
			return -2;
		}
		if (loginname != null&&!"".equals(loginname)) {
			OnlineUtil.addUser(loginname, String.valueOf(1));
		} 
		return OnlineUtil.getOnlineCount(String.valueOf(1));
	} 

}

2

 

3

 

4

5

2012十二月11

JS源码:网页滚动右下角出现返回顶部goTop

效果如图:

直接贴代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <HEAD>
  <TITLE> Wizzer.cn </TITLE>
  <style type="text/css" media="screen">
#goTop {position:fixed;right:20px;bottom:20px;width:40px;height:32px;padding:8px 0 0;background-color:#69c;border-radius:6px;cursor:pointer;}
#goTop:hover {background-color:#369;}
#goTop:hover .gotop1 {border-left:12px solid #369;border-right:12px solid #369;}
#goTop .gotop1 {width:0;margin:0 auto;border-bottom:12px solid #FFF;border-left:12px solid #69c;border-right:12px solid #69c;}
#goTop .gotop2 {width:10px;height:10px;margin:0 auto;background-color:#FFF;}
</style>
 </HEAD>

 <BODY>

a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>
a<br><br>

<div title="返回顶部" id="goTop" style="display:none;">
	<div class="gotop1"></div>
	<div class="gotop2"></div>
</div>

<script type="text/javascript">
	    function $getId(Id) {
	        return document.getElementById(Id);
	    }
	    var goTop = $getId("goTop");
	    window.onscroll = function () {
	        if (document.documentElement.scrollTop + document.body.scrollTop > 350) {
	            goTop.style.display = "";
	        } else {
	            goTop.style.display = "none";
	        }
	    }
	    goTop.onclick = function () {
	        var Timer = setInterval(GoTop, 10);
	        function GoTop() {
	            if (document.documentElement.scrollTop + document.body.scrollTop < 1) {
	                clearInterval(Timer);
	            } else {
	                document.documentElement.scrollTop /= 1.1;
	                document.body.scrollTop /= 1.1;
	            }
	        }
	    }
	</script>
 </BODY>
</HTML>

 

 

2011九月6

VB实现自动上传文件网页ActiveX控件(模拟form提交)

网页中实现自动上传本地文件,而不需要用户选择,这种应用场景很多,例如业务系统中需要使用的二代身份证扫描器、一体机(扫描仪)、摄像头拍照等。

首先介绍一个国外网站:http://www.planet-source-code.com/ 里面有许多可用的源代码供参考,搜索 upload file 找到 vb6 file uploader (类似的代码比较多,这个是比较好的一个)。

VB通过模拟HTTP POST过程把文件提交至服务器。

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1
Const BOUNDARY = "Xu02=$"
Const HEADER = "--Xu02=$"
Const FOOTER = "--Xu02=$--"

Function UploadFiles(DirPath As String, strFileName As Variant, strFileForm As Variant, strURL As String, _
Optional postName As Variant, Optional postVar As Variant, Optional strUserName As String, _
Optional strPassword As String) As String

    Dim fName As String
    Dim strFile As String
    Dim strBody As String
    Dim aPostBody() As Byte
    Dim nFile As Integer
    Dim p As Integer

    Set WinHttpReq = New WinHttpRequest

    ' Turn error trapping on
    On Error GoTo SaveErrHandler

    ' Assemble an HTTP request.
    WinHttpReq.Open "POST", strURL, False

    If strUserName <> "" And strPassword <> "" Then
        ' Set the user name and password, for server request authentication
        WinHttpReq.SetCredentials strUserName, strPassword, _
        HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
    End If

    '-------------------------- Becareful not to mingle too much here -----------------------------------

    ' Set the header
    WinHttpReq.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY

    ' Assemble the body
    ' Starting tag
    strBody = HEADER

    For i = 0 To UBound(strFileName)

        ' Grap the name
        fName = strFileName(i)

        ' Grap the file
        strFile = GetFile(DirPath & "\" & fName)

            strBody = strBody & vbCrLf & "Content-Disposition: form-data; name=""" & strFileForm(i) & _
             """; filename=""" & fName & """ " & vbCrLf & "Content-type: file" & _
            vbCrLf & vbCrLf & strFile & vbCrLf

        If i < UBound(strFileName) Then
            ' This is boundary tag between two files
            strBody = strBody & "--Xu02=$"
        End If
        strFile = ""

    Next i

'Posted Variable

    For p = 0 To UBound(postName)
    strBody = strBody & HEADER & vbCrLf
    strBody = strBody & "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf
    strBody = strBody & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    'Debug.Print "Content-Disposition: form-data; name=""" & postName(p) & """" & vbCrLf & vbCrLf & postVar(p) & vbCrLf
    'Debug.Print "-----------------------------------------------------------------------------------------------------"
    Next p

    ' Ending tag
    strBody = strBody & FOOTER

    ' Because of binary zeros, post body has to convert to byte array
    aPostBody = StrConv(strBody, vbFromUnicode)

    ' Send the HTTP Request.
    WinHttpReq.Send aPostBody

    ' Display the status code and response headers.
    'debug.print WinHttpReq.GetAllResponseHeaders & "  " & WinHttpReq.ResponseText

    UploadFiles = WinHttpReq.ResponseText
    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & WinHttpReq.ResponseText

    Set WinHttpReq = Nothing
    Exit Function

SaveErrHandler:

    Debug.Print "[UploadScript::UploadFiles]" & vbCrLf & Err.Description
    UploadFiles = WinHttpReq.ResponseText
    Set WinHttpReq = Nothing

End Function

Function GetFile(strFileName As String) As String

    Dim strFile As String

    ' Grap the file
    nFile = FreeFile
    Open strFileName For Binary As #nFile
    strFile = String(LOF(nFile), " ")
    Get #nFile, , strFile
    Close #nFile

    GetFile = strFile

End Function

'-----------------------------------------------------------
Private Sub Command1_Click()
Dim pst As New clsUploadEngine

'file path (make sure put "\" after folder name)
filepath = App.Path & "\sample\"

'filename array
filearr = Array("scenery1.jpg", "scenery2.jpg", "scenery3.jpg")

'form file post name (equivalent to <input type="file" name="filename">
fileform = Array("fileA", "fileB", "fileC")

'url to post file/information
uploadurl = "http://127.0.0.1:8080/savefile.jsp"

'post parameter & posted variable (optional)
'if no post parameter, just put dummy post, if not error will occur
postparam = Array("id", "uname", "passwd", "op")
postVar = Array("1", "root", "", "tdrupload")

pst.UploadFiles CStr(filepath), filearr, fileform, CStr(uploadurl), postparam, postVar

End Sub

在此基础上,做成ActiveX控件即可。但问题是这个源码上传到服务器的文本文件虽然看起来正常但文件结尾会有空编码、图片损坏。囧。

后来发现 WebNoteEditor 可以实现粘贴QQ截图,自动把文件上传到服务器,于是联系作者。作者是个好人哈,分享了一些经验甚至代码。目前在作者的帮助下,已实现的网页控件的文件自动上传功能,可传多个文件、多表单项。

下面要解决如何在线安装的问题了……

2011五月28

Android:指定分辨率和清晰度的图片压缩方法源码

public void transImage(String fromFile, String toFile, int width, int height, int quality)
	{
		try
		{
			Bitmap bitmap = BitmapFactory.decodeFile(fromFile);
			int bitmapWidth = bitmap.getWidth();
			int bitmapHeight = bitmap.getHeight();
			// 缩放图片的尺寸
			float scaleWidth = (float) width / bitmapWidth;
			float scaleHeight = (float) height / bitmapHeight; 
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeight);
			// 产生缩放后的Bitmap对象
			Bitmap resizeBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, false);
			// save file
			File myCaptureFile = new File(toFile);
			FileOutputStream out = new FileOutputStream(myCaptureFile);
			if(resizeBitmap.compress(Bitmap.CompressFormat.JPEG, quality, out)){
				out.flush();
				out.close();
			}
			if(!bitmap.isRecycled()){
				bitmap.recycle();//记得释放资源,否则会内存溢出
			}
			if(!resizeBitmap.isRecycled()){
				resizeBitmap.recycle();
			}

		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException ex)
		{
			ex.printStackTrace();
		}
	}