带有数据存储区低级API的Google App Engine + Spring MVC,CRUD示例

GAE数据存储
请参阅此官方“ 使用datstore指南 ”以了解什么是GAE数据存储。

请参阅以下代码段,以使用低级API对Google App Engine数据存储区Java执行CRUD。

以“名称”为关键字将客户存储到数据存储中。

Key customerKey = KeyFactory.createKey("Customer", "your name");
    Entity customer = new Entity("Customer", customerKey);
    customer.setProperty("name", "your name");
    customer.setProperty("email", "your email");

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(customer); //save it

搜索

返回10个客户作为列表。

DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	Query query = new Query("Customer").addSort("date", Query.SortDirection.DESCENDING);
	List<Entity> customers = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));

查找并返回具有匹配过滤条件的客户。

Query query = new Query("Customer");
	query.addFilter("name", FilterOperator.EQUAL, "your name");
	PreparedQuery pq = datastore.prepare(query);
	Entity customer = pq.asSingleEntity();

过滤器运算符
播放此过滤器,它几乎没有条件选项,例如小于,大于和等等。

更新资料

要进行更新,只需修改现有实体并再次保存即可。

Query query = new Query("Customer");
	query.addFilter("name", FilterOperator.EQUAL, "your name");
	PreparedQuery pq = datastore.prepare(query);
	Entity customer = pq.asSingleEntity();
		
	customer.setProperty("name", name);
	customer.setProperty("email", email);
	
	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(customer); //GAE will know save or update

删除

要删除,需要实体密钥。

Query query = new Query("Customer");
    query.addFilter("name", FilterOperator.EQUAL, name);
    PreparedQuery pq = datastore.prepare(query);
    Entity customer = pq.asSingleEntity();
		
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.delete(customer.getKey()); //delete it

GAE + Spring MVC + CRUD示例

好的,现在我们将向您展示一个使用REST风格使用Spring MVC开发的简单Web应用程序,并使用上面的低级API处理Google App Engine数据存储区中的数据。

  1. Google App Engine Java SDK 1.6.3.1
  2. 春天3.1.1
  3. JDK 1.6
  4. Eclipse 3.7 + Eclipse的Google插件

注意
此示例尽可能简单,以向您展示如何仅执行CRUD,不执行DAO或BO等层,不执行成功或失败操作的验证或消息通知。

1.弹簧控制器

REST风格的Spring控制器,用于显示网页并执行CRUD。 该代码应该是不言自明的。

文件:CustomerController.java

package com.mkyong.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

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.FetchOptions;
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.FilterOperator;

@Controller
@RequestMapping("/customer")
public class CustomerController {
	
	@RequestMapping(value="/addCustomerPage", method = RequestMethod.GET)
	public String getAddCustomerPage(ModelMap model) {

		return "add";

	}
	
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public ModelAndView add(HttpServletRequest request, ModelMap model) {

		String name = request.getParameter("name");
		String email = request.getParameter("email");
		
	        Key customerKey = KeyFactory.createKey("Customer", name);
	        
		Date date = new Date();
                Entity customer = new Entity("Customer", customerKey);
                customer.setProperty("name", name);
                customer.setProperty("email", email);
                customer.setProperty("date", date);

                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
                datastore.put(customer);
        
                return new ModelAndView("redirect:list");
        
	}
		
	@RequestMapping(value="/update/{name}", method = RequestMethod.GET)
	public String getUpdateCustomerPage(@PathVariable String name, 
			HttpServletRequest request, ModelMap model) {

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("Customer");
		query.addFilter("name", FilterOperator.EQUAL, name);
		PreparedQuery pq = datastore.prepare(query);
		
		Entity e = pq.asSingleEntity();
		model.addAttribute("customer",  e);
		
		return "update";

	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public ModelAndView update(HttpServletRequest request, ModelMap model) {

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		 
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String originalName =  request.getParameter("originalName");
		
		Query query = new Query("Customer");
		query.addFilter("name", FilterOperator.EQUAL, originalName);
		PreparedQuery pq = datastore.prepare(query);
		Entity customer = pq.asSingleEntity();
		
		customer.setProperty("name", name);
		customer.setProperty("email", email);
		customer.setProperty("date", new Date());

                datastore.put(customer);
        
               //return to list
               return new ModelAndView("redirect:list");
        
	}
		
	@RequestMapping(value="/delete/{name}", method = RequestMethod.GET)
	public ModelAndView delete(@PathVariable String name,
			HttpServletRequest request, ModelMap model) {

                DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        
                Query query = new Query("Customer");
		query.addFilter("name", FilterOperator.EQUAL, name);
		PreparedQuery pq = datastore.prepare(query);
		Entity customer = pq.asSingleEntity();
		
                datastore.delete(customer.getKey());
        
                //return to list
                return new ModelAndView("redirect:../list");
        
	}

	//get all customers
	@RequestMapping(value="/list", method = RequestMethod.GET)
	public String listCustomer(ModelMap model) {

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		Query query = 
                      new Query("Customer").addSort("date", Query.SortDirection.DESCENDING);
	        List<Entity> customers = 
                      datastore.prepare(query).asList(FetchOptions.Builder.withLimit(10));
	    
	        model.addAttribute("customerList",  customers);
	    
		return "list";

	}
	
}

2. JSP页面

3个JSP页面可显示客户并执行添加和更新。

文件:list.jsp

<%@ page import="java.util.List" %>
<%@ page import="com.google.appengine.api.datastore.Entity" %>
<html>
<body>
	<h1>GAE + Spring 3 MVC REST + CRUD Example</h1>

	Function : <a href="addCustomerPage">Add Customer</a>
	<hr />

	<h2>All Customers</h2>
	<table border="1">
		<thead>
			<tr>
				<td>Name</td>
				<td>Email</td>
				<td>Created Date</td>
				<td>Action</td>
			</tr>
		</thead>
		<%
		
		    List<Entity> customers = (List<Entity>)request.getAttribute("customerList");
		    for(Entity e : customers){
		     
		%>
			<tr>
			  <td><%=e.getProperty("name") %></td>
			  <td><%=e.getProperty("email") %></td>
			  <td><%=e.getProperty("date") %></td>
			  <td><a href="update/<%=e.getProperty("name")%>">Update</a> 
                             | <a href="delete/<%=e.getProperty("name")%>">Delete</a></td>
			</tr>
		<%
			}
		%>
	</table>

</body>
</html>

文件:add.jsp

<html>
<body>
	<h1>Add Customer</h1>
	
	<form method="post" action="add" >
		<table>
			<tr>
				<td>
					UserName :
				</td>
				<td>
					<input type="text" style="width: 185px;" 
                                              maxlength="30" name="name" id="name" />
				</td>
			</tr>
			<tr>
				<td>
					Email :
				</td>
				<td>
					<input type="text" style="width: 185px;" 
                                            maxlength="30" name="email" id="email" />
				</td>
			</tr>
		</table>
		<input type="submit" class="save" title="Save" value="Save" />
	</form>
	
</body>
</html>

文件:update.jsp

<%@ page import="com.google.appengine.api.datastore.Entity" %>
<html>
<body>
	<h1>Update Customer</h1>
	
	<%
		Entity customer = (Entity)request.getAttribute("customer");
	%>
	
	<form method="post" action="../update" >
		<input type="hidden" name="originalName" id="originalName" 
			value="<%=customer.getProperty("name") %>" /> 
		
		<table>
			<tr>
				<td>
					UserName :
				</td>
				<td>
					<input type="text" style="width: 185px;" 
                                             maxlength="30" name="name" id="name" 
						value="<%=customer.getProperty("name") %>" />
				</td>
			</tr>
			<tr>
				<td>
					Email :
				</td>
				<td>
					<input type="text" style="width: 185px;" 
                                            maxlength="30" name="email" id="email" 
						value="<%=customer.getProperty("email") %>" />
				</td>
			</tr>
		</table>
		<input type="submit" class="update" title="Update" value="Update" />
	</form>
	
</body>
</html>

3. Spring配置

扫描Spring控制器并配置视图解析器,以便它可以将视图重定向到jsp页面。

文件:mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.mkyong.controller" />
	<mvc:annotation-driven />

	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>

4.整合弹簧

将Spring集成到Web应用程序中。

档案:web.xml

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
	
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>
                      org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
	</context-param>

	<listener>
		<listener-class>
                   org.springframework.web.context.ContextLoaderListener
                </listener-class>
	</listener>
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

5.演示

完成,查看演示并向您展示Web应用程序的工作流程。

1.列表页面,显示现有客户列表。

网址:http:// localhost:8888 / customer / list

gae spring mvc crud example - list

2.在列表页面中,单击“添加客户”链接以显示“添加客户”页面,填写新客户,然后单击“添加”按钮。

网址:http:// localhost:8888 / customer / addCustomerPage

gae spring mvc crud example - add

3.保存客户后,它将返回到列表页面。

网址:http:// localhost:8888 / customer / list

gae spring mvc crud example - list

4.尝试更新链接,它将显示所选客户的数据,更新电子邮件地址,然后单击更新按钮。

网址:http:// localhost:8888 / customer / update / mkyong

gae spring mvc crud example - update

5.电子邮件已更新,并重定向回到列表页面。

网址:http:// localhost:8888 / customer / list

gae spring mvc crud example - list

6.要删除客户,只需单击“删除”链接。

下载源代码

由于文件大,所有Spring MVC和GAE jar均被排除。

下载– GoogleAppEngine-SpringMVC-datastore.zip (17 KB)

参考文献

  1. GAE:使用数据存储区
  2. GAE:实体
  3. GAE:数据存储区低级API
  4. GAE:使用JDO和Spring MVC进行CRUD操作
  5. 使用Google App Engine,Spring MVC和Flex的经验

翻译自: https://mkyong.com/google-app-engine/google-app-engine-spring-mvc-crud-example-with-datastore-low-level-api/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值