Phalcon vs Spring 用法对照表(持续更新)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 Tair(兼容Redis),内存型 2GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
简介:

Phalcon vs Spring

http://www.netkiller.cn/journal/phalcon.spring.html

MrNeo Chen (陈景峯)netkiller, BG7NYT


中国广东省深圳市龙华新区民治街道溪山美地
518131
+86 13113668890

版权声明

转载请与作者联系,转载时请务必标明文章原始出处和作者信息及本声明。

文档出处:
http://netkiller.github.io
http://netkiller.sourceforge.net

微信扫描二维码进入 Netkiller 微信订阅号

群:128659835 请注明“读者”

 

2015-11-25

摘要

Phalcon VS spring 用法对照表


1. Install

1.1. Phalcon

FYI https://github.com/oscm/shell/blob/master/lang/php/pecl/phalcon.sh

You need to install with compiler, make tools.

			
#!/bin/sh
cd /usr/local/src/

git clone --depth=1 git://github.com/phalcon/cphalcon.git
cd cphalcon/build
./install

cat > /srv/php/etc/conf.d/phalcon.ini <<EOF
extension=phalcon.so
EOF
			
			

1.2. Spring

You just only create a file as pom.xml, the maven will be fetch them.

			
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Spring</groupId>
	<artifactId>Spring</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.6</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
			
			

2. Project initialization

2.1. Phalcon

			
<?php
use Phalcon\Mvc\Dispatcher;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Logger;
try {


	/**
	 * Read the configuration
	 */
	$config = include(__DIR__."/../app/config/config.php");

	$loader = new \Phalcon\Loader();

	/**
	 * We're a registering a set of directories taken from the configuration file
	 */
	$loader->registerDirs(
		array(
			$config->application->controllersDir,
			$config->application->modelsDir,
            $config->application->formsDir,
            $config->application->imagesDir,
		)
	)->register();

	$loader->registerNamespaces(array(
			'Phalcon' => __DIR__.'/../../Library/Phalcon/'
	));

	$loader->register();

	/**
	 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
	 */
	$di = new \Phalcon\DI\FactoryDefault();

        $di->set('dispatcher', function() use ($di) {

                $eventsManager = new EventsManager;
                $dispatcher = new Dispatcher;
                $dispatcher->setEventsManager($eventsManager);

                return $dispatcher;
        });

	/**
	 * The URL component is used to generate all kind of urls in the application
	 */
	$di->set('url', function() use ($config) {
		$url = new \Phalcon\Mvc\Url();
		$url->setBaseUri($config->application->baseUri);
		return $url;
	});

	/**
	 * Setting up the view component
	 */
	$di->set('view', function() use ($config) {
		$view = new \Phalcon\Mvc\View();
		$view->setViewsDir($config->application->viewsDir);
		return $view;
	});

    /**
	 * 数据库加密key
	 */
	$di->set('config', function() use ($config) {
		return $config;
	});


	/**
	 * Database connection is created based in the parameters defined in the configuration file
	 */

	$di->set('db', function() use ($config) {

		return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
			"host" => $config->database->host,
			"username" => $config->database->username,
			"password" => $config->database->password,
			"dbname" => $config->database->dbname
		));
	});

	/**
	 * Start the session the first time some component request the session service
	 */
  	$di->set('session', function() {
  		$session = new \Phalcon\Session\Adapter\Files();
  		$session->start();
  		return $session;
  	});
/*
	$di->set('session', function() use ($config) {
		$session = new Phalcon\Session\Adapter\Redis(array(
				'path' => sprintf("tcp://%s:%s?weight=1",$config->redis->host, $config->redis->port)
		));
		$session->start();
		return $session;
	});
*/
	/**
	 * If the configuration specify the use of metadata adapter use it or use memory otherwise
	 */
	$di->set('modelsMetadata', function() use ($config) {
		if (isset($config->models->metadata)) {
			$metadataAdapter = 'Phalcon\Mvc\Model\Metadata\\'.$config->models->metadata->adapter;
			return new $metadataAdapter();
		} else {
			return new \Phalcon\Mvc\Model\Metadata\Memory();
		}
	});

	/**
	 * If the configuration specify the use of metadata adapter use it or use memory otherwise
	 */
	$di->set('modelsManager', function() {
		return new Phalcon\Mvc\Model\Manager();
	});


	/**
	 * Handle the request
	 */
	$application = new \Phalcon\Mvc\Application();
	$application->setDI($di);
	echo $application->handle()->getContent();

} catch (Phalcon\Exception $e) {
	echo $e->getMessage();
} catch (PDOException $e){
	echo $e->getMessage();
}
			
			

2.2. Spring

WebContent\WEB-INF

			
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Spring</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <servlet>
        <servlet-name>netkiller</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>netkiller</servlet-name>
        <url-pattern>/welcome.jsp</url-pattern>
        <url-pattern>/welcome.html</url-pattern>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

</web-app>
			
			

netkiller-servlet.xml

			
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

	<context:component-scan base-package="cn.netkiller.controller" />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>
			
			
			

			
			

3. Controller

3.1. welcome

3.1.1. Phalcon

				
<?php

class IndexController extends ControllerBase
{

    public function indexAction()
    {

    }
    public function welcomeAction()
    {
    	$message = "Helloworld!!!";
		$this->view->setVar('message',$message);
    }

}
				
				

3.1.2. Spring

				
package cn.netkiller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Welcome {

	@RequestMapping("/welcome")
	public ModelAndView helloWorld() {

		String message = "Helloworld!!!";
		return new ModelAndView("welcome", "message", message);
	}
}
				
				

3.2. pathinfo

http://www.netkiller.cn/news/list/100.html

http://www.netkiller.cn/news/detail/100/1000.html

3.2.1. Phalcon

				
<?php

class NewsController extends \Phalcon\Mvc\Controller
{


    public function listAction($category_id)
    {
		$this->view->setVar('category_id',$category_id);
    }
    public function detailAction($category_id, $article_id)
    {
		$this->view->setVar('category_id',$category_id);
		$this->view->setVar('article_id',$article_id);
    }

}
				
				

3.2.2. Spring

				
package cn.netkiller.controller;

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.servlet.ModelAndView;

@Controller
public class Pathinfo {
	@RequestMapping("/news/list/{category_id}")
	public ModelAndView urlTestId(@PathVariable String category_id) {

		return new ModelAndView("news/list", "category_id", category_id);
	}

	@RequestMapping("/news/detail/{category_id}/{article_id}")
	public ModelAndView urlTestId(@PathVariable String category_id, @PathVariable String article_id) {

		ModelMap model = new ModelMap();

		model.addAttribute("category_id", category_id);
		model.addAttribute("article_id", article_id);

		return new ModelAndView("news/detail", model);
	}
}
				
				

3.3. HTTP Get

http://www.netkiller.cn/member/login?email=netkiller@msn.com

3.3.1. Phalcon

				
<?php

class MemberController extends ControllerBase
{

    public function loginAction()
    {
		echo "email=" . $request->get("email");
    }

}
				
				

3.3.2. Spring

				
package cn.netkiller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Welcome {

	@RequestMapping("/member/login")
	@ResponseBody
	public String getEmailWithRequestParam(@RequestParam("email") String email) {
	    return "email=" + email;
	}

}
				
				

如果参数很多写起来就非常辛苦

				
package cn.netkiller.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class Welcome {

	@RequestMapping("/member/login")
	@ResponseBody
	public String getEmailWithRequestParam(
		@RequestParam("email") String email
		@RequestParam("password") String password
		...
		...
		@RequestParam("ext") String ext
	) {
	    ...
	    ...
	    ...
	}

}
				
				

3.4. HTTP Post

3.4.1. Phalcon

				
<?php

class MemberController extends ControllerBase
{

    public function loginAction()
    {
		echo "email=" . $request->getPost("email");
		echo "password=" . $request->getPost("password");
		echo "phone=" . $request->getPost("phone");
    }

}
				
				

3.4.2. Spring

				
package cn.netkiller.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

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

@Controller
public class Member {

	@RequestMapping("/http/form")
	public ModelAndView createCustomer(){
		ModelMap model = new ModelMap();

		model.addAttribute("email", "netkiller@msn.com");
		model.addAttribute("phone", "13113668890");
		
	    return new ModelAndView("http/form", model);
	}	
	
	@RequestMapping(value= "/http/post", method = RequestMethod.POST)
	public ModelAndView saveCustomer(HttpServletRequest request, 
	        @RequestParam(value="Email", required=false) String email, 
	        @RequestParam(value="Password", required=false) String password, 
	        @RequestParam(value="Phone", required=false) String phone){

		ModelMap model = new ModelMap();

		model.addAttribute("email", email);
		model.addAttribute("password", password);
		model.addAttribute("phone", phone);
		
	    return new ModelAndView("http/post", model);
	}
	
}
				
				

4. View

4.1. Variable

4.1.1. Phalcon

				
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<?php echo ${message} ?>
</body>
</html>
				
				

4.1.2. Spring

				
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	${message}
</body>
</html>
				
				

4.2. Array

4.2.1. Phalcon

				
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<?php foreach($books as $book) {?>
		<?php echo $book ?> <br>
	<?php } ?>

</body>
</html>
				
				

4.2.2. Spring

				
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<c:forEach items="${books}" var="book">
		<c:out value="${book}"></c:out><br>
	</c:forEach>

</body>
</html>
				
				

4.3. Map or Hashmap

4.3.1. Phalcon

				
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

	<?php foreach($books as $key=>$value) {?>
		<?php echo $key ?> : <?php echo $value ?> <br>
	<?php } ?>

</body>
</html>
				
				

4.3.2. Spring

				
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<c:forEach items="${books}" var="book">
		<c:out value="${book.key}"></c:out> : <c:out value="${book.value}"></c:out> <br>
	</c:forEach>
</body>
</html>
				
				

4.4. From

4.4.1. Phalcon

				
<?php

use Phalcon\Tag;

$this->tag->setDoctype(Tag::HTML401_STRICT);

?>
<html>
<head>
<title>Registration Page</title>
</head>
<body>
<?php = $this->tag->form("products/search") ?>
	<?php= $this->tag->textField("name") ?>
	<?php echo $this->tag->passwordField(array("password", "size" => 30)) ?>
	<?php echo $this->tag->select(array("status", array("A" => "Active","I" => "Inactive")));?>
	<?php echo $this->tag->textArea(array("aboutYou","","cols" => "6","rows" => 20)) ?>
	<?php echo $this->tag->hiddenField(array("parent_id","value"=> "5")) ?>
	<?= $this->tag->submitButton("Register"); ?>

<?php = $this->tag->endForm() ?>
</body>
</html>
				
				

4.4.2. Spring

				
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Registration Page</title>
</head>
<body>

<form:form method="POST" commandName="user">

	<form:input path="name" />
	<form:password path="password" />

    <form:radiobutton path="gender" value="M" label="M" />
    <form:radiobutton path="gender" value="F" label="F" />

    <form:select path="country">
	    <form:option value="0" label="Select" />
	    <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName" />
    </form:select>

    <form:textarea path="aboutYou" />
    <form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
    <form:checkbox path="mailingList" label="Would you like to join our mailinglist?" />

    <input type="submit" value="Register">

</form:form>

</body>
</html>
				
				

5. Model

5.1. Phalcon

模型定义

			
<?php

class User extends \Phalcon\Mvc\Model
{
	public function initialize()
	{

	}
}
			
			

在控制器重调用查询数据

			
<?php
$user = User::find();
print_r($user);			
			
			

5.2. MyBatis

Maven 增加mybatis与MySQL依赖设置

			
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>MyBatis</groupId>
	<artifactId>MyBatis</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.3.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.37</version>
		</dependency>
	</dependencies>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
			
			

mybatis.xml

			
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<!-- 配置数据库连接信息 -->
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://192.168.6.1:3306/mybatis" />
				<property name="username" value="mybatis" />
				<property name="password" value="mybatis" />
			</dataSource>
		</environment>
	</environments>
	<mappers>

		<mapper resource="cn/netkiller/mapping/userMapping.xml" />
	</mappers>
</configuration>
			
			

cn/netkiller/mapping/userMapping.xml

			
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.netkiller.mapping.UserMapping">
	<select id="getUser" parameterType="String" resultType="cn.netkiller.model.User">
		select * from user where id=#{id}
	</select>
</mapper>
			
			

数据类型映射

			
package cn.netkiller.model;

public class User {
	private String id;
	private String name;
	private int age;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

			
			

测试程序

			
package cn.netkiller.test;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import cn.netkiller.model.*;

public class Test {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String resource = "mybatis.xml";

		InputStream is = Tests.class.getClassLoader().getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();

		String statement = "cn.netkiller.mapping.UserMapping.getUser";// 映射sql的标识字符串

		User user = session.selectOne(statement, "2");
		System.out.println(user.toString());
	}

}
			
			

6. Session

6.1. Phalcon

				
<?php

use Phalcon\Mvc\Controller;

class SessionController extends Controller
{
    public function setAction()
    {
        // Set a session variable
        $this->session->set("username", "netkiller");
    }

    public function getAction()
    {
        // Check if the variable is defined
        if ($this->session->has("username")) {

            // Retrieve its value
            echo $this->session->get("username");
        }
    }
    
    public function removeAction()
    {
        // Remove a session variable
        $this->session->remove("username");
    }

    public function destroyAction()
    {
        // Destroy the whole session
        $this->session->destroy();
    }    

}
				
				

传统方式

				
$_SESSION['username'] = "netkiller";

unset($_SESSION['username']);
				
				

6.2. Spring

				
<dependencies>
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.0.2.RELEASE</version>
    </dependency>
</dependencies>
				
				
				
package cn.netkiller.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import cn.netkiller.*;

@Controller
public class Http {

	@RequestMapping("/session")
	@ResponseBody
	public String home(HttpServletRequest request) {
		return "" + request.getSession().getCreationTime();
	}

	@RequestMapping("/session/set")
	@ResponseBody
	public String setSession(HttpSession session) {
		String username = "netkiller";
		session.setAttribute("username", username);
		return username;
	}

	@RequestMapping("/session/get")
	@ResponseBody
	public String getSession(HttpSession session) {
		String username = (String) session.getAttribute("username");
		return username;
	}
	
	@RequestMapping("/session/remove")
	@ResponseBody
	public String removeSession(HttpSession session) {
		session.removeAttribute("username");
		String username = (String) session.getAttribute("username");
		return username;
	}
	
	@RequestMapping("/session/invalidate")
	@ResponseBody
	public String invalidateSession(HttpSession session) {
		session.invalidate();
		return "invalidate";
	}

}

				
				

Servlet 传统方式

				
	@RequestMapping("/session/Servlet")
	@ResponseBody
	public String servletSession(HttpServletRequest request) {
		String username = "neo";
		request.getSession().setAttribute("username", username);
		return username;
	}
				
				

7. Cache

7.1. Redis

7.1.1. Phalcon

				
//Cache arbitrary data
 $this->cache->save('my-key', array(1, 2, 3, 4, 5));

 //Get data
 $data = $this->cache->get('my-key');
				
				

7.1.2. Spring

pom.xml

				
<dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.6.1.RELEASE</version>
    </dependency>
</dependencies>				
				
				

Configure RedisTemplate....

				
<bean id="jedisConnFactory" 
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 
    p:use-pool="true"/>

<!-- redis template definition -->
<bean id="redisTemplate" 
    class="org.springframework.data.redis.core.RedisTemplate" 
    p:connection-factory-ref="jedisConnFactory"/>
				
				
				

Testing

				
public class Example {

    // inject the actual template
    @Autowired
    private RedisTemplate<String, String> template;

    // inject the template as ListOperations
    // can also inject as Value, Set, ZSet, and HashOperations
    @Resource(name="redisTemplate")
    private ListOperations<String, String> listOps;

    public void addLink(String userId, URL url) {
        listOps.leftPush(userId, url.toExternalForm());
        // or use template directly
        redisTemplate.boundListOps(userId).leftPush(url.toExternalForm());
    }
}				
				
				

7.2. Model + Cache

7.2.1. Phalcon

				
   	$articles = Article::find(array(
   			"cache" => array("service"=> 'redis', "key" => $key, "lifetime" => 60)
   	));
				
				

7.2.2. MyBatis

MyBatis Redis Cache adapter http://mybatis.github.io/redis-cache

pom.xml

				
  <dependencies>
    <!--
     | Provided dependencies
    -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
      <scope>provided</scope>
    </dependency>

    <!--
     | compile dependencies
    -->
	<dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.3</version>
      <scope>compile</scope>
	</dependency>
  </dependencies>
				
				
				
				
				
				
				
				
				
				
				
				
				
				

7.3. Phalcon vs Ehcache

7.3.1. 

				
				
				

7.3.2. 

				
				
				

8. JSON Data

8.1. Phalcon

Encode

			
<?php

$json = array(
	'contact' => array(
		'name' 		=> 'Neo',
		'website' 	=> 'http://www.netkiller.cn',
		'nickname' 	=> 'netkiller' 
	) 
); 
print(json_encode($json));
			
			

Output

{"contact":{"name":"Neo","website":"http:\/\/www.netkiller.cn","nickname":"netkiller"}}
			

Decode

			
<?php
$string = '{"contact":{"name":"Neo","website":"http:\/\/www.netkiller.cn","nickname":"netkiller"}}';
print_r(json_decode($string));
			
			

输出

			
stdClass Object
(
    [contact] => stdClass Object
        (
            [name] => Neo
            [website] => http://www.netkiller.cn
            [nickname] => netkiller
        )

)
			
			

8.2. Spring

JSON 编码

			
package netkiller.json;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.json.*;

public final class Writer {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		JsonObjectBuilder jsonBuilder = Json.createObjectBuilder();
		JsonObjectBuilder addressBuilder = Json.createObjectBuilder();
		JsonArrayBuilder phoneNumBuilder = Json.createArrayBuilder();

		phoneNumBuilder.add("12355566688").add("0755-2222-3333");

		addressBuilder.add("street", "Longhua").add("city", "Shenzhen").add("zipcode", 518000);

		jsonBuilder.add("nickname", "netkiller").add("name", "Neo").add("department", "IT").add("role", "Admin");

		jsonBuilder.add("phone", phoneNumBuilder);
		jsonBuilder.add("address", addressBuilder);

		JsonObject jsonObject = jsonBuilder.build();

		System.out.println(jsonObject);

		try {
			// write to file
			File file = new File("json.txt");
			if (!file.exists()) {
				file.createNewFile();
			}
			OutputStream os = null;
			os = new FileOutputStream(file);
			JsonWriter jsonWriter = Json.createWriter(os);
			jsonWriter.writeObject(jsonObject);
			jsonWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
		
运行后输出

{"nickname":"netkiller","name":"Neo","department":"IT","role":"Admin","phone":["12355566688","0755-2222-3333"],"address":{"street":"Longhua","city":"Shenzhen","zipcode":"518000"}}
			
			

JSON 解码

			
package netkiller.json;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
 
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
 
public final class Reader {
 
    public static final String JSON_FILE="json.txt";
     
    public static void main(String[] args) throws IOException {
        InputStream fis = new FileInputStream(JSON_FILE);
        //create JsonReader object
        JsonReader jsonReader = Json.createReader(fis);

        //get JsonObject from JsonReader
        JsonObject jsonObject = jsonReader.readObject();
         
        //we can close IO resource and JsonReader now
        jsonReader.close();
        fis.close();
         
        System.out.printf("nickname: %s \n", jsonObject.getString("nickname"));
        System.out.printf("name: %s \n", jsonObject.getString("name"));
        System.out.printf("department: %s \n", jsonObject.getString("department"));
        System.out.printf("role: %s \n", jsonObject.getString("role"));
        JsonArray jsonArray = jsonObject.getJsonArray("phone");
        
        //long[] numbers = new long[jsonArray.size()];
        int index = 0;
        for(JsonValue value : jsonArray){
            //numbers[index++] = Long.parseLong(value.toString());
        	System.out.printf("phone[%d]: %s \n", index++, value.toString());
        }

        //reading inner object from json object
        JsonObject innerJsonObject = jsonObject.getJsonObject("address");
        
        System.out.printf("address: %s, %s, %d \n", innerJsonObject.getString("street"), innerJsonObject.getString("city"), innerJsonObject.getInt("zipcode"));
         
    }
 
}		
		
运行结果

nickname: netkiller 
name: Neo 
department: IT 
role: Admin 
phone[0]: +8612355566688 
phone[1]: 0755-2222-3333 
address: Longhua, Shenzhen, 518000
			
			

9. Message Queue

9.1. Phalcon

			
			
			

9.2. Spring

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
相关文章
|
7月前
|
设计模式 监控 Java
深入浅出 Spring:核心概念和基本用法详解
深入浅出 Spring:核心概念和基本用法详解
147 0
|
Java Spring
【注解】Spring AOP 面向切面编程之@Around的详细用法
【注解】Spring AOP 面向切面编程之@Around的详细用法
1516 0
|
Java Spring
【Java用法】Spring之@Nullable和@NotNull注释的使用
【Java用法】Spring之@Nullable和@NotNull注释的使用
320 0
|
2月前
|
前端开发 Java C++
RSocket vs WebSocket:Spring Boot 3.3 中的两大实时通信利器
本文介绍了在 Spring Boot 3.3 中使用 RSocket 和 WebSocket 实现实时通信的方法。RSocket 是一种高效的网络通信协议,支持多种通信模式,适用于微服务和流式数据传输。WebSocket 则是一种标准协议,支持全双工通信,适合实时数据更新场景。文章通过一个完整的示例,展示了如何配置项目、实现前后端交互和消息传递,并提供了详细的代码示例。通过这些技术,可以大幅提升系统的响应速度和处理效率。
|
6月前
|
JSON Java 数据格式
Spring Boot 中的 @DateTimeFormat 和 @JsonFormat 的用法及作用
【6月更文挑战第11天】在开发 Spring Boot 应用时,处理日期和时间数据是一个常见的需求。Spring Boot 提供了两个注解 @DateTimeFormat 和 @JsonFormat 来帮助我们处理这些问题。
498 4
|
6月前
|
前端开发 Java 开发者
深入理解 Spring Boot 注解:核心功能与高级用法详解
深入理解 Spring Boot 注解:核心功能与高级用法详解
354 1
|
6月前
|
存储 Java C++
理解SpringIOC和DI第一课(Spring的特点),IOC对应五大注解,ApplicationContext vs BeanFactory
理解SpringIOC和DI第一课(Spring的特点),IOC对应五大注解,ApplicationContext vs BeanFactory
|
7月前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
97 0
【Spring系列】Sping VS Sping Boot区别与联系
|
7月前
|
设计模式 监控 Java
深入浅出 Spring:核心概念和基本用法详解
深入浅出 Spring:核心概念和基本用法详解
44 1
|
7月前
|
前端开发 Java Maven
spring boot3参数校验基本用法
spring boot3参数校验基本用法
230 2