文章标签 ‘JAVA’
20133 月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

201112 月22

JAVA源码:将GPS、google地图经纬度坐标转换为百度地图坐标

package smsService;

import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.entity.StringEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpEntity;
import org.json.me.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import smsService.cfg.Globals;
import smsService.sms.StringUtil;
import smsService.util.JWD;
import smsService.util.SecBase64;

/**
Wizzer.cn
 */
public class baidu {
    public static void main(String args[]) {
        baidu b = new baidu();
        b.getData("117.3094928", "31.875676");
        System.out.println("");
    }

    public static JWD getData(String jd, String wd) {
        JSONObject holder = new JSONObject();
        String wizzer = "";
        JWD jwd=null;
        try {
            BasicHttpParams httpParameters = new BasicHttpParams();
            // Set the default socket timeout (SO_TIMEOUT)
            HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
            // in milliseconds which is the timeout for waiting for data.
            HttpConnectionParams.setSoTimeout(httpParameters, 15000);

            DefaultHttpClient client = new DefaultHttpClient(httpParameters);
            HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.NETSCAPE);//CookiePolicy.BROWSER_COMPATIBILITY);
            String type="0";//详见百度坐标转换API文档示例
            type=StringUtil.null2String(Globals.SYS_COM_CONFIG.get("sys.baidu.type"));
            HttpGet get = new HttpGet("http://api.map.baidu.com/ag/coord/convert?from="+type +"&to=4&x=" + jd + "&y=" + wd + "&callback=wizzer");
            HttpResponse resp = client.execute(get);
            HttpEntity entity = resp.getEntity();
            BufferedReader br = new BufferedReader(new InputStreamReader(entity
                    .getContent(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            String result = br.readLine();
            while (result != null) {
                sb.append(result);
                result = br.readLine();
            }

            String res = StringUtil.null2String(sb.toString());
            if (res.indexOf("(") > 0 && res.indexOf(")") > 0) {
                String str = res.substring(res.indexOf("(") + 1, res.indexOf(")"));
                String err = res.substring(res.indexOf("error") + 7, res.indexOf("error") + 8);

                if ("0".equals(err)) {
                    jwd=new JWD();
                    JSONObject js = new JSONObject(str);
                    String x = new String(SecBase64.decode(js.getString("x").getBytes()));
                    String y = new String(SecBase64.decode(js.getString("y").getBytes()));
                    jwd.setX(x);
                    jwd.setY(y);
                }
            }
            return jwd;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
201112 月22

JAVA源码:通过google地图API将经纬度坐标转换为位置描述

package smsService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/*
Wizzer.cn
 */
public class Demo {
	public static void main(String[] args) {
		String addr = GetAddr("31.875676", "117.3094928");
		System.out.println(addr);
		//getCoordinate("中国");
	}

	/**
	 * 根据经纬度反向解析地址,有时需要多尝试几次
	 * 注意:(摘自:http://code.google.com/intl/zh-CN/apis/maps/faq.html
	 * 提交的地址解析请求次数是否有限制?) 如果在 24 小时时段内收到来自一个 IP 地址超过 15,000 个地址解析请求, 或从一个 IP
	 * 地址提交的地址解析请求速率过快,Google 地图 API 编码器将用 620 状态代码开始响应。 如果地址解析器的使用仍然过多,则从该 IP
	 * 地址对 Google 地图 API 地址解析器的访问可能被永久阻止。
	 *
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @return
	 */
	public static String GetAddr(String latitude, String longitude) {
		String addr = "";

		// 也可以是http://maps.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s,不过解析出来的是英文地址
		// 密钥可以随便写一个key=abc
		// output=csv,也可以是xml或json,不过使用csv返回的数据最简洁方便解析
		String url = String.format(
				"http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
				latitude, longitude);
		URL myURL = null;
		URLConnection httpsConn = null;
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}
		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addr = retList[2];
						addr = addr.replace("\"", "");
					} else {
						addr = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return addr;
	}

	public static void getCoordinate(String addr)
	{
		String addrs = "";
	    String address = null;
		try {
			address = java.net.URLEncoder.encode(addr,"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		};
        String output = "csv";
        String key = "abc";
        String url = String.format("http://maps.google.com/maps/geo?q=%s&output=%s&key=%s", address, output, key);
        URL myURL = null;
        URLConnection httpsConn = null;
        //进行转码
		try {
			myURL = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {
			httpsConn = (URLConnection) myURL.openConnection();
			if (httpsConn != null) {
				InputStreamReader insr = new InputStreamReader(
						httpsConn.getInputStream(), "UTF-8");
				BufferedReader br = new BufferedReader(insr);
				String data = null;
				if ((data = br.readLine()) != null) {
					System.out.println(data);
					String[] retList = data.split(",");
					/*
		            String latitude = retList[2];
		            String longitude = retList[3];

		            System.out.println("纬度"+ latitude);
		            System.out.println("经度"+ longitude);
		            */

					if (retList.length > 2 && ("200".equals(retList[0]))) {
						addrs = retList[2];
						addrs = addr.replace("\"", "");
					} else {
						addrs = "";
					}
				}
				insr.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(addrs);
	}
}
201111 月23

JAVA Oauth 认证服务器的搭建

1、软件下载

Oauth服务端: http://code.google.com/p/oauth/  通过SVN,下载源码。

                          或者下载站长整合好的示例源码:http://115.com/file/aqvpzqhz

客户端下载:http://code.google.com/p/oauth-signpost/  oauth-signpost

                         或者下载站长整合好的示例源码:http://115.com/file/bhy1d2ce

2、服务端源码下载后,把相关代码整合在一起(或直接下载站长整合好的代码),修改net.oauth.provider.core.SampleOAuthProvider  类,把从 provider.properties 读取的信息改为从数据库中读取,如APP_KEY、APP_SCERET、描述、回调地址。

3、net.oauth.example.provider.servlets下面的四个类,这里对应着oauth3个请求url,跟一个用于测试的链接,可以根据需求修改,如将调用Oauth的用户信息记录下来。

4、修改web.xml 增加三个请求url

<servlet>
		<servlet-name>request_token</servlet-name>
		<servlet-class>net.oauth.provider.servlets.RequestTokenServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>request_token</servlet-name>
		<url-pattern>/oauth/request_token</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>access_token</servlet-name>
		<servlet-class>net.oauth.provider.servlets.AccessTokenServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>access_token</servlet-name>
		<url-pattern>/oauth/access_token</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>authorize</servlet-name>
		<servlet-class>net.oauth.provider.servlets.AuthorizationServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>authorize</servlet-name>
		<url-pattern>/oauth/authorize</url-pattern>
	</servlet-mapping>

5、做个拦截器,只要通过某url访问的都需要进行Oauth认证:

web.xml

<filter>
	   <filter-name>OauthFilter</filter-name>
	   <filter-class>web.school.phone.OauthFilter</filter-class>
	</filter>
	<filter-mapping>
	   <filter-name>OauthFilter</filter-name>
	   <url-pattern>/phone/*</url-pattern>
	</filter-mapping>

 web.school.phone.OauthFilter

	package web.school.phone;
         import java.io.IOException;

	import javax.servlet.Filter;
	import javax.servlet.FilterChain;
	import javax.servlet.FilterConfig;
	import javax.servlet.ServletException;
	import javax.servlet.ServletRequest;
	import javax.servlet.ServletResponse;
	import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;

	import net.oauth.OAuthAccessor;
	import net.oauth.OAuthMessage;
	import net.oauth.provider.core.SampleOAuthProvider;
	import net.oauth.server.OAuthServlet;

	public class OauthFilter implements Filter {

	  public void destroy() {
	  }

	  public void init(FilterConfig fConfig) throws ServletException {
	  }

	  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
	  throws IOException, ServletException {
	    HttpServletRequest req=(HttpServletRequest)request;
	    HttpServletResponse res=(HttpServletResponse)response;

	    try{
            OAuthMessage requestMessage = OAuthServlet.getMessage(req, null);
            OAuthAccessor accessor = SampleOAuthProvider.getAccessor(requestMessage);
            SampleOAuthProvider.VALIDATOR.validateMessage(requestMessage, accessor);

            System.out.println("[OauthFilter:passed]:"+req.getRequestURI());
            chain.doFilter(request, response);//验证通过则转向

        } catch (Exception e){
        	//验证不通过
            SampleOAuthProvider.handleException(e, req, res, false);
        }

	  }

}

6、执行客户端代码,提示输入验证码时,把控制台打印的URL放到浏览器里打开,输入授权码:

(服务端AuthorizationServlet 里面修改验证不通过要跳转的页面,页面上会打印一些参数)

20115 月4

合肥 Android/Java开发交流群:26310065

手机开发:WM、Android、iOS
WEB开发:Java、.NET、ASP、PHP、JSP
应用开发:C#、JAVA……

欢迎IT从业人士加入,交流开发经验、技术,项目外包等信息。
QQ群:26310065

201012 月31

JAVA发送EMAIL的例子

import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Wizzer
 * Date: 2010-12-29
 * Time: 16:39:50
 * To change this template use File | Settings | File Templates.
 */
public class Mail {
    public static void main(String args[]) throws MessagingException, UnsupportedEncodingException {
    Properties props = new Properties();
    props.put("mail.smtp.host","smtp.qq.com");
    props.put("mail.smtp.auth","true");
    PopupAuthenticator auth = new PopupAuthenticator(); 
    Session session = Session.getInstance(props, auth);
    MimeMessage message = new MimeMessage(session);
    Address addressFrom = new InternetAddress(PopupAuthenticator.mailuser+"@qq.com", "George Bush");
    Address addressTo = new InternetAddress("116****@qq.com", "George Bush");//收件人
    message.setText("邮件发送成功");
    message.setSubject("Javamal最终测试");
    message.setFrom(addressFrom);
    message.addRecipient(Message.RecipientType.TO,addressTo);
    message.saveChanges();
    Transport transport = session.getTransport("smtp");
    transport.connect("smtp.qq.com", PopupAuthenticator.mailuser,PopupAuthenticator.password);
    transport.send(message);
    transport.close();
    }

}
class PopupAuthenticator extends Authenticator {
public static final String mailuser="wizzer"; 
public static final String password="********";
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailuser,password);
}
}
20108 月10

开源的JS JAVA工作流设计器

XiorkFlow  这个设计器UI还是不错的,可以自动生成XML文件,只是节点和连接线如果能双击弹出窗口设置相关属性就好了,没办法,只能进行二次开发了。。:(

谁有更好的开源工作流设计器吗?

下载地址:http://www.pudn.com/downloads78/sourcecode/java/detail298487.html

其他不多述了,自己下了部署下,可以看看效果。