ASP.NET MVC3实战系列(一):简单示例 ; SpringMVC基础入门,创建一个HelloWorld程序

综合体验了Java/.NET/PHP ,对于三者新流行的MVC框架,感觉用法很类似!

Java:struts2 -> SpringMVC  

请求 ~  Action --------------------------->mvcController/Method 

.NET: WebForm -> .NET MVC

请求 ~ Page -------------------------->mvcController/Method

PHP:   -> ThinkPHP

请求 ~ Page -------------------------->Module/mvcController/Method

 

史上最全最强SpringMVC详细示例实战教程

 https://www.cnblogs.com/sunniest/p/4555801.html

SpringMVC学习笔记----

一、SpringMVC基础入门,创建一个HelloWorld程序

1.首先,导入SpringMVC需要的jar包。

2.添加Web.xml配置文件中关于SpringMVC的配置
复制代码
  <!--configure the setting of springmvcDispatcherServlet and configure the mapping-->
  <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- <load-on-startup>1</load-on-startup> -->
  </servlet>

  <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
复制代码

3.在src下添加springmvc-servlet.xml配置文件

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">                    

    <!-- scan the package and the sub package -->
    <context:component-scan base-package="test.SpringMVC"/>

    <!-- don't handle the static resource -->
    <mvc:default-servlet-handler />

    <!-- if you use annotation you must configure following setting -->
    <mvc:annotation-driven />
    
    <!-- configure the InternalResourceViewResolver -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
复制代码

4.在WEB-INF文件夹下创建名为jsp的文件夹,用来存放jsp视图。创建一个hello.jsp,在body中添加“Hello World”。

5.建立包及Controller,如下所示

6.编写Controller代码

复制代码
@Controller
@RequestMapping("/mvc")
public class mvcController {

    @RequestMapping("/hello")
    public String hello(){        
        return "hello";
    }
}
复制代码

7.启动服务器,键入 http://localhost:8080/项目名/mvc/hello

二、配置解析

1.Dispatcherservlet

  DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标Controller来处理,是配置spring MVC的第一步。

2.InternalResourceViewResolver

  视图名称解析器

3.以上出现的注解

@Controller 负责注册一个bean 到spring 上下文中

@RequestMapping 注解为控制器指定可以处理哪些 URL 请求

三、SpringMVC常用注解

@Controller

  负责注册一个bean 到spring 上下文中
@RequestMapping

  注解为控制器指定可以处理哪些 URL 请求
@RequestBody

  该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上 ,再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上

@ResponseBody

   该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区

@ModelAttribute    

  在方法定义上使用 @ModelAttribute 注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法

  在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中 

@RequestParam 

  在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法

@PathVariable

  绑定 URL 占位符到入参
@ExceptionHandler

  注解到方法上,出现异常时会执行该方法
@ControllerAdvice

  使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常

四、自动匹配参数

复制代码
    //match automatically
    @RequestMapping("/person")
    public String toPerson(String name,double age){
        System.out.println(name+" "+age);
        return "hello";
    }
复制代码

五、自动装箱

1.编写一个Person实体类

复制代码
package test.SpringMVC.model;

public class Person {
    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;
    }
    private String name;
    private int age;
    
}
复制代码

2.在Controller里编写方法

复制代码
    //boxing automatically
    @RequestMapping("/person1")
    public String toPerson(Person p){
        System.out.println(p.getName()+" "+p.getAge());
        return "hello";
    }
复制代码

六、使用InitBinder来处理Date类型的参数

复制代码
    //the parameter was converted in initBinder
    @RequestMapping("/date")
    public String date(Date date){
        System.out.println(date);
        return "hello";
    }
    
    //At the time of initialization,convert the type "String" to type "date"
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),
                true));
    }
复制代码

七、向前台传递参数

复制代码
    //pass the parameters to front-end
    @RequestMapping("/show")
    public String showPerson(Map<String,Object> map){
        Person p =new Person();
        map.put("p", p);
        p.setAge(20);
        p.setName("jayjay");
        return "show";
    }
复制代码

前台可在Request域中取到"p"

八、使用Ajax调用

复制代码
    //pass the parameters to front-end using ajax
    @RequestMapping("/getPerson")
    public void getPerson(String name,PrintWriter pw){
        pw.write("hello,"+name);        
    }
    @RequestMapping("/name")
    public String sayHello(){
        return "name";
    }
复制代码

前台用下面的Jquery代码调用

复制代码
          $(function(){
              $("#btn").click(function(){
                  $.post("mvc/getPerson",{name:$("#name").val()},function(data){
                      alert(data);
                  });
              });
          });
复制代码

九、在Controller中使用redirect方式处理请求

    //redirect 
    @RequestMapping("/redirect")
    public String redirect(){
        return "redirect:hello";
    }

十、文件上传

。。。 。。。https://www.cnblogs.com/sunniest/p/4555801.html

 

 

ASP.NET MVC3实战系列(一):简单示例

https://www.cnblogs.com/cnblogsfans/archive/2011/09/01/2162227.html

2011-09-01 17:07 by 敏捷的水, 30849 阅读, 19 评论, 收藏编辑

ASP.NET MVC已经推出时间不短了,已经有很多项目在使用这个优秀的WEB开发框架。因为我们项目每次加人的时候,对MVC都不是特别熟悉,有一些人认为这个非常简单,导致写出来的程序完全不是MVC的,所以我就想写个系列总结一下实战中的经验和一些学习的笔记。我们先不谈论MVC的好处,等我们写过一些程序和示例后,再回来谈。

首先,我们先用MVC写一个简单的ASP.NET MVC3的程序来简单的了解一下。

 

环境:

VS2010

ASP.NET MVC3

http://www.microsoft.com/web/downloads/platform.aspx 下载Microsoft Web Platform Installer 3.0,在Microsoft Web Platform Installer 3.0上可以在线下载到需要的软件。

image

 

示例程序

1. 显示一个简单的字符串“Hello World”

新建ASP.NET MVC3 Web Application

image

选择Razor视图引擎

image

image

按F5启动应用程序

image

我们看到出错了,这是因为在MVC里,请求被Controller处理,现在还没有任何Controller,下面我们添加一个Controller, 右键Controller添加一个HomeController

image

image

修改HomeController里的Index方法为如下

image

F5运行后如下所示

image

为什么可以运行成功,这要归功于ASP.NET MVC的路由机制,我们看一下Global.asax.cs里的如下代码

image

从这行代码里可以看到系统默认请求被路由到HomeController和Index这个Action(MVC里把Controller里公有方法称之为Action,两者之间是有区别的)。

2. 显示一个视图:

如果都像刚才那样直接写字符串到客户端,那开发人员肯定疯了,现在我们显示一个视图。先把HomeController里的Action改为如下代码,按F5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
namespace HelloWorld.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
 
        public ActionResult Index()
        {
            return View();
        }
 
    }
}

 

image

根据提示,我们在错误提示的任何一个位置添加对应的文件就可以了,这里我们在Views/Home文件夹下添加Index.aspx, 在HomeController里右键点击Index方法名,选择Add View

image

image

点击确定,修改index.aspx为如下内容

image

F5运行,我们看到显示和之前相同的结果

image

 

3. 添加动态内容

添加如下代码

image

修改Index.aspx视图为如下

image

F5运行

image

ViewBag是Controller定义的一个动态类型的属性,意味着你可以给他添加任何属性,在编译时动态类型的属性是不检查的。

image

 

4. 强类型视图

动态类型编译时不能检查,开发时没有只能提示是意见很不爽的时,下面我们来定义一个强类型的视图。先定义一个Person类

image

删除Index.aspx, Ctrl+Shift+B 编译一下,右键Action—>Add View

image

修改Index.aspx

image

我们可以看到强类型的智能提示

image

F5运行

我们可以看到生成的HTML和页面

image

在Controller里添加如下方法

image

提交表单显示如下,

image

之所以能够显示出名字,是因为ASP.NET MVC通过Binder机制把表单Post的数据赋给参数对象对应的属性,我们可以通过Firebug看一下表单Post的数据

image

 

5. 添加验证

修改Person 这个Modal为如下,记得引用红色标注的命名空间

image

视图里添加如下红色标注的内容

image

修改Action里的代码如下

image

F5运行,不输入任何代码提交表单

image

 

至此,我们完成了一个简单的MVC3的程序,里面演示的MVC3的一些基本特性。

 

最后,打个小广告:西安分公司急聘如下人员,有意者直接联系我,左边侧栏有我的联系方式,博客园招聘频道有详细描述 http://job.cnblogs.com/offer/13800/

基本要求: 
4年以上C#开发经验, .Net基础扎实,熟练使用.Net3.5新特性。 
精通ASP.NET Web开发。 
熟练使用WCF. 
熟练使用ORM,LINQ TO SQL /Entity Framework或者NHibernate. 
熟练使用JavaScript, JQuery. 
熟悉Web标准,熟悉HTML&CSS. 
熟悉SQL Server, 熟练掌握T-SQL,存储过程。 
英语读写熟练,可以看懂英文需求,可以和客户流畅的用英语文字沟通(MSN/Skype) 
良好的编码习惯。


熟悉下面任意一项优先: 
熟悉敏捷开发者优先 
英语听说熟练者优先 
熟悉ASP.NET MVC者优先。 
熟悉WPF者优先 
熟悉Silverlight优先 
有系统架构经验者优先,有单元测试或者TDD经验者优先。

 

作者: 王德水
出处:http://www.cnblogs.com/cnblogsfans
版权:本文版权归作者所有,转载需经作者同意。
 
posted @ 2018-01-09 09:51  sky20080101  阅读(134)  评论(0)    收藏  举报