spring3.1 mvc入门讲解

来源:互联网 发布:淘宝的试用中心在哪 编辑:程序博客网 时间:2024/05/21 17:33

java wb MVC框架最早是struts,struts1.x版本有1.1,1.2,1.3,后来struts与webwork合并成Struts2版,所以说struts影响力比较大.当然现在框架还有JSF,Tapestry等,随着后来的spring的流行,作为一位程序猿,当然除了掌握struts,还有必要学一下spring mvc.


一、开发环境

二、web配置

三、spring配置

四、jsp代码

五、Controller实现

六、运行效果



一、开发环境

eclipse4.3+spring3.1.2,由于只是演示mvc,本例没有使用数据库,只是单纯mvc演示,所以没有用到hiberate相关的框架。

项目最终的结构如下图1,请自行导入相应的包,由于spring依赖commons-logging-1.0.4.jar,也自行导入



图1


二、web.xml配置


    <servlet>        <servlet-name>spring</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>spring</servlet-name>        <url-pattern>*.do</url-pattern>    </servlet-mapping>



在上面的例子里,所有以.do结尾的请求都会由名为spring的DispatcherServlet处理。这只是配置Spring Web MVC 的第一步。

DispatcherServlet的初始化过程中,框架会在web应用的 WEB-INF文件夹下寻找名为[servlet-name]-servlet.xml 的配置文件,生成文件中定义的bean。这些bean会覆盖在全局范围(global cope)中定义的同名的bean。

[servlet-name]-servlet.xml 的配置文件,本例就是spring-servlet.xml


三、spring配置

在第二步配置了web.xml文件,现在就来配置spring-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"    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">    <!-- 启用spring mvc 注解 -->    <context:annotation-config />    <!-- spring在包com.spring.mvc.action寻找相应的类 -->    <context:component-scan base-package="com.spring.mvc.action"></context:component-scan>    <!-- 完成请求和注解POJO的映射 -->    <bean        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver"        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /></beans>


<bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

对于   p:prefix="/WEB-INF/jsp/" p:suffix=".jsp",你也可以这样写

<property name="prefix" value="/WEB-INF/jsp/"/>

<property name="suffix" value=".jsp"/>

SpringWeb框架的所有控制器都返回一个ModelAndView实例。 Sprnig中的视图以名字为标识,视图解析器通过名字来解析视图。

当返回的视图名为test时, 这个视图解析器将请求传递给RequestDispatcherRequestDispatcher再将请求传递给/WEB-INF/jsp/test.jsp


Spring提供了多种视图解析器

视图解析器

ViewResolver描述AbstractCachingViewResolver抽象视图解析器实现了对视图的缓存。在视图被使用之前,通常需要进行一些准备工作。 从它继承的视图解析器将对要解析的视图进行缓存。XmlViewResolverXmlViewResolver实现ViewResolver,支持XML格式的配置文件。 该配置文件必须采用与Spring XML Bean Factory相同的DTD。默认的配置文件是/WEB-INF/views.xmlResourceBundleViewResolverResourceBundleViewResolver实现ViewResolver, 在一个ResourceBundle中寻找所需bean的定义。 这个bundle通常定义在一个位于classpath中的属性文件中。默认的属性文件是views.propertiesUrlBasedViewResolverUrlBasedViewResolver实现ViewResolver, 将视图名直接解析成对应的URL,不需要显式的映射定义。 如果你的视图名和视图资源的名字是一致的,就可使用该解析器,而无需进行映射。InternalResourceViewResolver作为UrlBasedViewResolver的子类, 它支持InternalResourceView(对Servlet和JSP的包装), 以及其子类JstlViewTilesView。 通过setViewClass方法,可以指定用于该解析器生成视图使用的视图类。 更多信息请参考UrlBasedViewResolver的Javadoc。VelocityViewResolver / FreeMarkerViewResolver作为UrlBasedViewResolver的子类, 它能支持VelocityView(对Velocity模版的包装)和FreeMarkerView以及它们的子类。


四、开发代码

上面都是基本的配置文件,下面到了写代码演示mvc的时候了

这里有三个jsp三个文件 ,第一个是登录页面,输入test用户名,123456为密码,将会跳转到success.jsp文件,否则将跳转到error.jsp文件

login.jsp文件

<%@page pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Login Form</title></head><body><center><h1>登入表单</h1><hr width="50%">请输入使用者名称与密码:<p></center><form name="loginform" action="loginForm.do"><table width="500" border="1" align="center" cellpadding="1"cellspacing="1" bordercolor="#999999"><tr><td width="30%" align="right">名称</td><td width="70%"><input type="text" name="userName" value="" /></td></tr><tr><td align="right">密码</td><td><input type="password" name="password" value="" /></td></tr><tr><td colspan="2" align="center"><input type="submit"value=" 确 定 " /></td></tr></table></form></body></html>


success.jsp文件

<%@page pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <title>登入成功</title>    </head>    <body>    <center>        <H1>            哈哈, ${userName},欢迎您!        </H1>        我是不是好厉害呀!^o^        <a href="login.do">退出登录</a>        </center>    </body></html>


error.jsp文件

<%@page pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml">    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <title>登入失败</title>    </head>    <body>        <center>            <H1>                唉! 登入失败!            </H1>            我还会再回来的!^_^        </center>    </body></html>

五、Controller实现

package com.spring.mvc.action;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controllerpublic class LoginAction {@RequestMapping("loginForm.do")public String loginForm(String userName, String password,HttpServletRequest request) {if ("test".equals(userName) && "123456".equals(password)) {request.setAttribute("userName", userName);return "success";}return "error";}@RequestMapping("login.do")public String login(){return "login";}}



LoginAction.java只有两个方法,这两个方法和我们平时写的方法没有什么两样

@RequestMapping("login.do")    public String login(){        return "login";    }

login()方法直接返回一个字符串,也没有参数

@RequestMapping("login.do")表示当我们访问http://localhost:8081/springMVC/login.do时,

将调用login()方法,该方法返回“login”字符串,表示将访问http://localhost:8081/springMVC/WEB-INF/jsp/login.jsp

还记得配置spring-servlet.xml文件吗,配置文件出现的p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"

表示前缀+login()方法返回的字符串+后缀


@RequestMapping("loginForm.do")public String loginForm(String userName, String password,HttpServletRequest request) {if ("test".equals(userName) && "123456".equals(password)) {request.setAttribute("userName", userName);return "success";}return "error";}


@RequestMapping("loginForm.do")表示我们访问http://localhost:8081/springMVC/loginForm.do时,

将调用loginForm()方法,将用户名为test,密码为123456时,该方法返回“success”字符串,表示将访问http://localhost:8081/springMVC/WEB-INF/jsp/success.jsp

否则将跳转到http://localhost:8081/springMVC/WEB-INF/jsp/error.jsp

该方法还带一个HttpServletRequest request参数,这个参数不是必须的,这里用户名和密码都正确了,成功总得显示一个用户名吧,所以加了这个参数


六、运行效果

做了这么多,该到了显摆的时候了

http://localhost:8081/springMVC/login.do





good luck


源码下载




原创粉丝点击