Google App Engine 数据库

环境设置:《在gae平台上开发jsp网站


Broker.java 一段java读写数据库的操作

package bagebit;

// java 标准库
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import java.util.Date;
// GAE 标准库
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.*;
// 第三方库
// ...

/**
* 用户【User】表定义
*
* ******************************************************************************
* @login
* @password
* @email
* @nickname 
*/

/**
* 资源【Resource】表定义
* ******************************************************************************
* @type  [picture, audio, video, text, url]
* @link
* @login -> User::login
* @tags
*/

/**
* 标签【Tag】表定义
* ******************************************************************************
* @tag -> Resource::tags
* @popular
*/


public class Broker extends HttpServlet {

	// 系统日志
    private static final Logger log = 
						Logger.getLogger(Broker.class.getName());
				
	// 数据库连接
	private static final DatastoreService datastore = 
						DatastoreServiceFactory.getDatastoreService();
	
	/**
	* 所有HTTP GET请求的入口
	*/
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
			log.info("Broker::doGet called at: " + (new java.util.Date()).toString());
            resp.setContentType("text/html;charset=UTF-8");
			
			// 根据请求的方法调度
			String method = req.getParameter("method");
			
			// 接口 - 创建用户
			if (method.compareToIgnoreCase("CreateUser") == 0){
				String login = req.getParameter("login");
				if (login == null || login.isEmpty()){
					return ;
				}
				String password = req.getParameter("password");
				if (password == null || password.isEmpty()){
					return ;
				}
				String email = req.getParameter("email");
				if (email == null){
					email = "";
				}				
				String nickname = req.getParameter("nickname");
				if (nickname == null){
					nickname = "";
				}
				
				if (!CreateUser(login, password, email, nickname)){
					log.warning("Failed to create User.");
				}else{
					log.info("OK, User [" + login + "] created");
				}
				
				//ListUsers(resp);
				
			}else 
			
			// 接口 - 创建资源
			if (method.compareToIgnoreCase("CreateResource") == 0){
				String resource = req.getParameter("resource");
				CreateResource(resource);
			}else
			
			// 接口 - 创建标签
			if (method.compareToIgnoreCase("CreateTag") == 0) {
				String tag = req.getParameter("tag");
				if (!CreateTag(tag)){
					
				}else{
				
				}
				//ListTags(resp);
			}
			
			// 接口 - 未定义
			else{
				// TODO: log
			}
		}
	

	
	/**
	* 创建用户
	* **************************************************************************
	* 参数
	* @login       - 登录名
	* @password    - 登录密码
	* @email       - 注册邮箱
	* @nickname    - 昵称
	* **************************************************************************
	* @return     - 成功返回true,失败返回false
	*/
	private boolean CreateUser(String login, String password, String email
							  , String nickname){
		if (IsUserExisted(login)){
			log.warning("User [" + login + "] is already existed!");
			return false;
		}
		log.info("Create User, login=" + login + ", password=" + password);
		Entity user = new Entity("User");
		user.setProperty("login", login);
		user.setProperty("password", password);
		datastore.put(user);
		return true;
	}
	

	
	private boolean CreateTag(String tag){
		if (IsTagExisted(tag)){
			log.warning("Tag [" + tag + "] is already existed!");
			return false;
		}
		log.info("Create Tag, tag=" + tag);
		Entity t = new Entity("Tag");
		t.setProperty("tag", tag);
		t.setProperty("popular", 0);
		datastore.put(t);
		return true;
	}
	
	boolean CreateResource(String resource){
		return true;
	}
	
	private boolean IsUserExisted(String login){
		Query q = new Query("User");
		q.setFilter(FilterOperator.EQUAL.of("login", login));
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			// 有枚举,说明存在,直接返回。
			return true;
		}		
		return false;
	}	
	
	boolean IsTagExisted(String word) {
		Query q = new Query("Tag");
		q.setFilter(FilterOperator.EQUAL.of("tag", word));
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			// 有枚举,说明存在,直接返回。
			return true;
		}
		return false;
	}	
		
	private void ListUsers(HttpServletResponse resp) throws IOException{
		// 创建查询
		Query q = new Query("User");
		
		// 添加排序规则
		q.addSort("login", SortDirection.ASCENDING);
		
		// 如果需要过滤器Filter参考Google的文档
		// ...
		// addFilter(...) is deprecated. see https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Query.Filter
		// and https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Query.CompositeFilter
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			  String login = (String) result.getProperty("login");
			  resp.getWriter().println("<b>LoginName: </b>" + login + "<br>");
		}
	}
	
	private void ListTags(HttpServletResponse resp) throws IOException{
		// 创建查询
		Query q = new Query("Tag");
		
		// 添加排序规则
		q.addSort("popular", SortDirection.DESCENDING);
		
		// 如果需要过滤器Filter参考Google的文档
		// ...
		// addFilter(...) is deprecated. see https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Query.Filter
		// and https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Query.CompositeFilter
		PreparedQuery pq = datastore.prepare(q);
		for (Entity result : pq.asIterable()) {
			  String tag = (String) result.getProperty("tag");
			  resp.getWriter().println("<b>tag: </b>" + tag + "<br>");
		}
	}
	
	/**
	* 所有HTTP POST请求的入口
	*/
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
		throws IOException {
			return ; 
    }
}



参考文献:

1, 数据查询:https://developers.google.com/appengine/docs/java/datastore/queries?hl=zh-cn

2, 数据写入:https://developers.google.com/appengine/docs/java/datastore/entities?hl=zh-cn

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Google App Engine is a web application hosting service. By “web application,” we mean an application or service accessed over the Web, usually with a web browser: storefronts with shopping carts, social networking sites, multiplayer games, mobile applications, survey applications, project management, collaboration, publishing, and all the other things we’re discovering are good uses for the Web. App Engine can serve traditional website content too, such as documents and images, but the environment is especially designed for real-time dynamic applications. In particular, Google App Engine is designed to host applications with many simulta- neous users. When an application can serve many simultaneous users without degrad- ing performance, we say it scales. Applications written for App Engine scale automat- ically. As more people use the application, App Engine allocates more resources for the application and manages the use of those resources. The application itself does not need to know anything about the resources it is using. Unlike traditional web hosting or self-managed servers, with Google App Engine, you only pay for the resources you use. These resources are measured down to the gigabyte. Billed resources include CPU usage, storage per month, incoming and outgoing band- width, and several resources specific to App Engine services. To help you get started, every developer gets a certain amount of resources for free, enough for small applica- tions with low traffic. App Engine can be described as three parts: application instances, scalable data storage, and scalable services. In this chapter, we look at each of these parts at a high level. We also discuss features of App Engine for deploying and managing web applications, and for building websites integrated with other Google offerings such as Google Apps, Google Accounts, and Google Cloud Storage.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值