从零开始:学习Python3

字面常量

#整数
2

#浮点数
3.14
#科学技术法
52.3e-4
52.3e-4

#复数
(-5+4j)

#单引号字符串
'a string'

#双引号字符串
"a string"

#三引号字符串
'''multi lines string'''

#转义符,字符串行末相当于取消换行


#自然字符串
r"natural string"

#unicode 字符串
u"unicode string"

变量

  • 标识符
name ::= lc_letter (lc_letter | "_")*
lc_letter ::= "a"..."z"
  • 声明和定义
#整数
i = 2

#浮点数
d = 3.14

#科学技术法
d = 52.3E-4
d = 52.3e-4

#复数
c = (-5+4j)

#单引号字符串
s = 'a string'

#双引号字符串
s = "a string"

#三引号字符串
s = '''multi 
lines 
string'''

#自然字符串
s = r"natural string"

#unicode 字符串
s = u"Unicode string"

变量类型

语句

默认一个物理行为一个逻辑行
;为逻辑行结尾
逻辑行首的空白决定缩进层次

运算符

类型

  • str,字符串
#连接
a = 'abc'
b = 'def'
c = a + b

#字面级联
d = 'abc' 'def'
d = ("spam" "eggs")

#substring/slicing
substr = str[m:n]
  • list
# 创建
shoplist = ['apple', 'mango', 'carrot', 'banana']

# 遍历
for item in shoplist:
print item,

# 自然序排序
shoplist.sort();

# 下标访问
olditem = shoplist[0]
  • 元组
# 创建
zoo = ('wolf', 'elephant', 'penguin')
name = "axis"
age = 25
axis = (name,age)
  • 字典
# 创建
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}

# key-访问
ab['Guido'] = 'guido@python.org'

# 遍历
for name, address in ab.items():
print 'Contact %s at %s' % (name, address)

# 包含
if ab.has_key('Guido')
print "nGuido's address is %s" % ab['Guido']
  • 序列(list,元组,字符串)
# 索引
shoplist[0]
shoplist[1]
shoplist[2]
shoplist[3]
shoplist[-1]
shoplist[-2]

# 切片
shoplist[1:3]
shoplist[2:]
shoplist[1:-1]
shoplist[:]

字符串处理

String Methods
String Formatting

控制结构

# if-elseif-else
if expression :
doSomething;
elseif expression :
doSomething;
elseif :
doSomething;
# for

# while
while expression:
doSomething;

# break

# continue

函数

  • 定义
def funcName(arg1,arg2,arg3 = defaultValue):
funcBody;
  • 参数传递
funcName(1,2,3) #根据位置传参

funcName(arg1=1, arg2=2) #关键参数,通过name传参
  • return
    没有return等价return None
  • 函数注解
    参数注解
    返回值注解
    func.annotations访问注解
def func(a:int,b:float,c:'string'='a string')->int:
return 1

IO

  • 标准输入
  • 标准输出
  • 标准错误
  • 文件read line
  • 文件write line

测试

  • 测试框架
  • 测试模型
  • 测试用例创建
  • 断言
  • 测试用例执行
  • 测试结果

构建

  • 构建工具
  • 构建执行
  • 打包
  • 库的依赖
  • 库的使用
Advertisements

从零开始:学习一门新的语言Checklist

变量和类型

  • 声明
  • 定义
  • 赋值
  • 类型
  • 函数
  • 定义
  • 调用
  • 形参和实参
  • 参数传递

字符串处理

  • 字面常量
  • 连接
  • append
  • insert
  • substring
  • 正则匹配
  • 大小写转换

IO

  • 标准输入
  • 标准输出
  • 标准错误
  • 文件read line
  • 文件write line

测试

  • 测试框架
  • 测试模型
  • 测试用例创建
  • 断言
  • 测试用例执行
  • 测试结果

构建

  • 构建工具
  • 构建执行
  • 打包
  • 库的依赖
  • 库的使用

SpringMVC-XML

工具

Spring
Maven 3

Maven Dependency

<properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>
```xml

### JAXB注解Model
```java
package com.mkyong.common.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "coffee")
public class Coffee {

    String name;
    int quanlity;

    public String getName() {
        return name;
    }

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

    public int getQuanlity() {
        return quanlity;
    }

    @XmlElement
    public void setQuanlity(int quanlity) {
        this.quanlity = quanlity;
    }

    public Coffee(String name, int quanlity) {
        this.name = name;
        this.quanlity = quanlity;
    }

    public Coffee() {
    }

}

XMLController

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import com.mkyong.common.model.Coffee;

@Controller
@RequestMapping("/coffee")
public class XMLController {

    @RequestMapping(value="{name}", method = RequestMethod.GET)
    public @ResponseBody Coffee getCoffeeInXML(@PathVariable String name) {

        Coffee coffee = new Coffee(name, 100);

        return coffee;

    }

}

输出

<coffee>
    <name>arabica</name>
    <quantity>100</quantity>
</coffee>

SpringMVC-JSON

工具

Spring
Jackson 1.9.10
Maven 3

Maven Dependency

<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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong.common</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>SpringMVC Json Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.2.2.RELEASE</spring.version>
        <jackson.version>1.9.10</jackson.version>
        <jdk.version>1.6</jdk.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Jackson JSON Mapper -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>${jackson.version}</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>SpringMVC</finalName>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>false</downloadJavadocs>
                <wtpversion>2.0</wtpversion>
            </configuration>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>
          </plugin>
        </plugins>
    </build>

</project>

JSONController

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
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.bind.annotation.ResponseBody;
import com.mkyong.common.model.Shop;

@Controller
@RequestMapping("/kfc/brands")
public class JSONController {

    @RequestMapping(value="{name}", method = RequestMethod.GET)
    public @ResponseBody Shop getShopInJSON(@PathVariable String name) {

        Shop shop = new Shop();
        shop.setName(name);
        shop.setStaffName(new String[]{"mkyong1", "mkyong2"});

        return shop;

    }

}

#springmvc%ef%bc%8ctutorial

SpringMVC-View Resolver

InternalResourceViewResolver

Controller
//...
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}
InternalResourceViewResolver配置
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   &lt;bean 
   class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean id=&quot;viewResolver&quot;
              class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot; &gt;
              &lt;property name=&quot;prefix&quot;&gt;
                  &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
               &lt;/property&gt;
              &lt;property name=&quot;suffix&quot;&gt;
                 &lt;value&gt;.jsp&lt;/value&gt;
              &lt;/property&gt;
        &lt;/bean&gt;

&lt;/beans&gt;
解析结果

prefix + view name + suffix = /WEB-INF/pages/WelcomPage.jsp

XmlViewResolver

根据xml文件中配置进行解析
默认文件位置: /WEB-INF/views.xml,
自定义文件位置:

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
       &lt;property name=&quot;location&quot;&gt;
        &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
       &lt;/property&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
配置View Beans
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    &lt;bean id=&quot;WelcomePage&quot;
        class=&quot;org.springframework.web.servlet.view.JstlView&quot;&gt;
        &lt;property name=&quot;url&quot; value=&quot;/WEB-INF/pages/WelcomePage.jsp&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
配置XmlViewResolver
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   &lt;bean 
   class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
       &lt;property name=&quot;location&quot;&gt;
           &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
       &lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
完成Controller
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}

ResourceBundleViewResolver

根据xml文件中配置进行解析
默认文件位置: classpath 根目录下views.properties,
自定义文件位置:

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;
&lt;/beans&gt;
配置View Beans

spring-views.properties

WelcomePage.(class)=org.springframework.web.servlet.view.JstlView
WelcomePage.url=/WEB-INF/pages/WelcomePage.jsp
配置ResourceBundleViewResolver
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
    xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
    xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  &lt;bean 
  class=&quot;org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping&quot; &gt;&lt;/bean&gt;

    &lt;!-- Register the bean --&gt;
    &lt;bean class=&quot;com.mkyong.common.controller.WelcomeController&quot; &gt;&lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
        &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
完成Controller
public class WelcomeController extends AbstractController{

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        ModelAndView model = new ModelAndView(&quot;WelcomePage&quot;);

        return model;
    }
}

多个Resolver配置方式

&lt;beans ...&gt;
    &lt;bean class=&quot;org.springframework.web.servlet.view.XmlViewResolver&quot;&gt;
         &lt;property name=&quot;location&quot;&gt;
            &lt;value&gt;/WEB-INF/spring-views.xml&lt;/value&gt;
         &lt;/property&gt;
         &lt;property name=&quot;order&quot; value=&quot;0&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean class=&quot;org.springframework.web.servlet.view.ResourceBundleViewResolver&quot;&gt;
         &lt;property name=&quot;basename&quot; value=&quot;spring-views&quot; &gt;&lt;/property&gt;
         &lt;property name=&quot;order&quot; value=&quot;1&quot; &gt;&lt;/property&gt;
    &lt;/bean&gt;

    &lt;bean id=&quot;viewResolver&quot;
          class=&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot; &gt;
              &lt;property name=&quot;prefix&quot;&gt;
                 &lt;value&gt;/WEB-INF/pages/&lt;/value&gt;
              &lt;/property&gt;
              &lt;property name=&quot;suffix&quot;&gt;
                 &lt;value&gt;.jsp&lt;/value&gt;
              &lt;/property&gt;
          &lt;property name=&quot;order&quot; value=&quot;2&quot; &gt;&lt;/property&gt;
        &lt;/bean&gt;
&lt;/beans&gt;

优先级顺序

XmlViewResolver --&gt; ResourceBundleViewResolver --&gt; InternalResourceViewResolver

SpringMVC-Controller

Group Action

一个Controller中多个action

package com.mkyong.common.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomerController{

    @RequestMapping(&quot;/customer/add.htm&quot;)
    public ModelAndView add(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerAddView&quot;);

    }

    @RequestMapping(&quot;/customer/delete.htm&quot;)
    public ModelAndView delete(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerDeleteView&quot;);

    }

    @RequestMapping(&quot;/customer/update.htm&quot;)
    public ModelAndView update(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerUpdateView&quot;);

    }

    @RequestMapping(&quot;/customer/list.htm&quot;)
    public ModelAndView list(HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        return new ModelAndView(&quot;CustomerListView&quot;);

    }
}

Return ModelAndView

SpringMVC Mapping

BeanNameUrlHandlerMapping

spring 默认使用的HandlerMapping实现,通过bean配置实现url转发

ControllerClassNameHandlerMapping

启用这个HandlerMapping后,spring采用约定方式实现url转发

<br /> 

 

 

WelcomeController -> /welcome*
HelloGuestController -> /helloguest*
/helloGuest匹配/helloguest错误

Case sensitive
配置启用caseSensitive属性

<br /> 

 

 

WelcomeController -> /welcome*
HelloGuestController -> /helloGuest*

pathPrefix

<br /> 

 

 

WelcomeController -> /customer/welcome*
HelloGuestController -> /customer/helloGuest*

SimpleUrlHandlerMapping

通过url pattern配置转发
两种配置方式

welcomeControllerwelcomeControllerhelloGuestController

 

 
<br />/welcome.htm=welcomeController
/*/welcome.htm=welcomeController
/helloGuest.htm=helloGuestController
 

 

handler mapping priority

ControllerClassNameHandlerMapping配置所有符合约定的mapping
SimpleUrlHandlerMapping配置所有由特殊需求的mapping
然后指定order

<br />/index.htm=welcomeController
/welcome.htm=welcomeController
/main.htm=welcomeController
/home.htm=welcomeController