zoukankan      html  css  js  c++  java
  • 【转】spring MVC入门示例(hello world demo)

    部分内容来自网络:《第二章 Spring MVC入门 —— 跟开涛学SpringMVC 》

    1. Spring MVC介绍

    Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,基于请求驱动指的就是使用请求-响应模型,框架的目的就是帮助我们简化开发,Spring Web MVC也是要简化我们日常Web开发的。

    Spring Web MVC也是服务到工作者模式的实现,但进行可优化。前端控制器是DispatcherServlet;应用控制器其实拆为处理器映射器(Handler Mapping)进行处理器管理和视图解析器(View Resolver)进行视图管理;页面控制器/动作/处理器为Controller接口(仅包含ModelAndView handleRequest(request, response) 方法)的实现(也可以是任何的POJO类);支持本地化(Locale)解析、主题(Theme)解析及文件上传等;提供了非常灵活的数据验证、格式化和数据绑定机制;提供了强大的约定大于配置(惯例优先原则)的契约式编程支持。

    2. Spring MVC的优点

    • 让我们能非常简单的设计出干净的Web层和薄薄的Web层;
    • 进行更简洁的Web层的开发;
    • 天生与Spring框架集成(如IoC容器、AOP等);
    • 提供强大的约定大于配置的契约式编程支持;
    • 能简单的进行Web层的单元测试;
    • 支持灵活的URL到页面控制器的映射;
    • 非常容易与其他视图技术集成,如Velocity、FreeMarker等等,因为模型数据不放在特定的API里,而是放在一个Model里(Map数据结构实现,因此很容易被其他框架使用);
    • 非常灵活的数据验证、格式化和数据绑定机制,能使用任何对象进行数据绑定,不必实现特定框架的API;
    • 提供一套强大的JSP标签库,简化JSP开发;
    • 支持灵活的本地化、主题等解析;
    • 更加简单的异常处理;
    • 对静态资源的支持;
    • 支持Restful风格。

    2. 环境配置

    新建一个web工程,file->new->web project,取名为SpringMVC。将spring中的jar中复制到SpringMVC/WEB-INF/lib下。spring中有些与struts相关的包可以不复制,因为这里用不到。除此之外,还需要

    commons-logging.jar/jstl.jar/standard.jar这三个依赖包。配置完后,lib下的jar包如下所示:

    3. 入门示例

    3.1 我们首先从web.xml开始配置。

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
      <display-name>SpringMVC</display-name>	
      
    	<servlet>  
        	<servlet-name>SpringMVC</servlet-name>  
        	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        	<load-on-startup>1</load-on-startup>  
           	</servlet>  
    	<servlet-mapping>  
        	<servlet-name>SpringMVC</servlet-name>  
        	<url-pattern>/</url-pattern>  
    	</servlet-mapping>
    	
    	<welcome-file-list>
    		<welcome-file>MyJsp.jsp</welcome-file>
    	</welcome-file-list>
    </web-app>

    load-on-startup表示启动容器时初始化该Servlet;

    url-pattern表示哪些请求交给Spring Web MVC处理, “/” 是用来定义默认servlet映射的。也可以如“*.html”表示拦截所有以html为扩展名的请求。

    自此请求已交给Spring Web MVC框架处理,因此我们需要配置Spring的配置文件,默认DispatcherServlet会加载WEB-INF/[DispatcherServlet的Servlet名字]-servlet.xml配置文件。本示例为WEB-INF/ SpringMVC-servlet.xml。

    3.2 再来配置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:p="http://www.springframework.org/schema/p"     
        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-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">  
        
     	<bean name="/test1/helloWorld" class="com.SpringMVC.web.controller.HelloWorldController" />  
        
    	<!-- ViewResolver -->  
    	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        	<property name="prefix" value="/WEB-INF"/>  
        	<property name="suffix" value=".jsp"/>  
    	</bean>
    	
    </beans>  

    InternalResourceViewResolver:用于支持Servlet、JSP视图解析;

    prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀),比如传进来的逻辑视图名为hello,则该jsp视图页面应该存放在“WEB-INF/hello.jsp”;

    <bean name="test1/helloWorld" ... />这里表示传来的url与代码中的controller的对应关系。

    3.3 下面我们来写controller类代码

    package com.SpringMVC.web.controller;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    
    public class HelloWorldController implements Controller{
    
    	public ModelAndView handleRequest(HttpServletRequest arg0,
    			HttpServletResponse arg1) throws Exception {
    		// TODO Auto-generated method stub
    		System.out.println("--------------hello world! 世界你好!--------------------");
    		return new ModelAndView("/helloWorld");
    	}
    }
    

    这里实现了一个接口,重写了其中的handleRequest函数。函数中,在后台打印一段文件,并将helloWorld.jsp页面返回给浏览器。因为在-servlet.xml中进行了配置,所以helloWorld.jsp文件应在WEB-INF文件夹下,且此处返回时仅写helloWorld即可,无需加后缀.jsp。

    3.4 jsp页面

    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>Hello World!</title>
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    	<!--
    	<link rel="stylesheet" type="text/css" href="styles.css">
    	-->
      </head>
      
      <body>
        -----------------Hello World! ----------------------<br>
      </body>
    </html>
    

    3.5 完成后的目录结构

    SpringMVC
      src
        com.SpringMVC.web.controller
          HelloWorldController.java
      WebRoot
        WEB-INF
          lib
          helloWorld.jsp
          SpringMVC-servlet.xml
          web.xml

    5. 运行、访问页面

    将SpringMVC部署到tomcat服务器上,运行。在浏览器中输入访问地址:http://localhost:8080/SpringMVC/test1/helloWorld。应该就可以看到前台显示helloWorld.jsp页面,后台打印“--------------hello world! 世界你好!--------------------”字符串了。

    6. 遇到的小问题

    我最先开始配置-servlet.xml文件时,将<property name="prefix" value="/WEB-INF"/> 配置为 <property name="prefix" value="/"/>,即返回SpringMVC根目录,即WebRoot的jsp页面。结果,后台可以打印出预期的字符串,而jsp页面却提示找不到资源,404错误,可是事实上我已经将helloWorld.jsp页面放置在SpringMVC的根目录下了。不知道这是为什么……

  • 相关阅读:
    权限和分组
    验证与授权
    CSRF、XSS、clickjacking、SQL 的攻击与防御
    上下文处理器及中间件
    类和实例
    偏函数
    生成器
    迭代 复习
    函数调用 复习
    复习 条件判断,循环
  • 原文地址:https://www.cnblogs.com/sunada2005/p/3576431.html
Copyright © 2011-2022 走看看