实例详解Spring MVC入门使用

MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(Controller).通过分层使开发的软件结构更清晰,从而达到开发效率的提高,可维护性和扩展性得到提高.Spring提供的MVC框架是在J2EE Web开发中对MVC模式的一个实现,本文通过实例讲解一下Spring MVC 的使用.

先来看一个HTTP request在Spring的MVC框架是怎么被处理的:(图片来源于Spring in Action)


1,DispatcherServlet是Spring MVC的核心,它的本质是一个实现了J2EE标准中定义的HttpServlet,通过在web.xml配置<servlet-mapping>,来实现对request的监听.

	<servlet>
		<servlet-name>springTestServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>2</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springTestServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
** 以.do结尾的request都会由springTestServlet来处理.
2,3,当接受到request的时候,DispatcherServlet根据HandlerMapping的配置(HandlerMapping的配置文件默认根据<servlet-name>的值来决定,这里会读取springTestServlet-servlet.xml来获得HandlerMapping的配置信息),调用相应的Controller来对request进行业务处理.

	<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/login.do">loginController</prop>
			</props>
		</property>
	</bean>
	<bean id="loginController" class="com.test.spring.mvc.contoller.LoginController">
		<property name="sessionForm">
			<value>true</value>
		</property>
		<property name="commandName">
			<value>loginCommand</value>
		</property>
		<property name="commandClass">
			<value>com.test.spring.mvc.commands.LoginCommand</value>
		</property>
		<property name="authenticationService">
			<ref bean="authenticationService"/>
		</property>
		<property name="formView">
			<value>login</value>
		</property>
		<property name="successView">
			<value>loginDetail</value>
		</property>
	</bean>
** 以login.do结尾的request由loginController来处理.<property name="formView">配置的是Controller接收到HTTP GET请求的时候需要显示的逻辑视图名,本例是显示login.jsp,<property name="successView">配置的是在接收到HTTP POST请求的时候需要显示的逻辑视图名,在本例中即login.jsp提交的时候需要显示名为loginDetail的逻辑视图.

4,Controller进行业务处理之后,返回一个ModelAndView对象.

return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);
5,6,DispatcherServlet根据ViewResolver的配置(本例是在springTestServlet-servlet.xml文件中配置)将逻辑view转换到真正要显示的View,如JSP等.

	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
**其作用是将Controller中返回的ModleAndView解析到具体的资源(JSP文件),如上例中的return new ModelAndView(getSuccessView();按照上面ViewResolver配置,会解析成/jsp/loginDetail.jsp.规则为prefix+ModelAndView的第二个参数+suffix.

示例的完整代码如下:

1web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	prjSpring3</display-name>
	<servlet>
		<servlet-name>springTestServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>2</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springTestServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/springTest-services.xml</param-value>
	</context-param>
	<jsp-config>
		<taglib>
			<taglib-uri>/spring</taglib-uri>
			<taglib-location>/WEB-INF/spring.tld</taglib-location>
		</taglib>
	</jsp-config>
</web-app>
2,springTestServlet-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" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		<property name="mappings">
			<props>
				<prop key="/login.do">loginController</prop>
			</props>
		</property>
	</bean>
	<bean id="loginController" class="com.test.spring.mvc.contoller.LoginController">
		<property name="sessionForm">
			<value>true</value>
		</property>
		<property name="commandName">
			<value>loginCommand</value>
		</property>
		<property name="commandClass">
			<value>com.test.spring.mvc.commands.LoginCommand</value>
		</property>
		<property name="authenticationService">
			<ref bean="authenticationService"/>
		</property>
		<property name="formView">
			<value>login</value>
		</property>
		<property name="successView">
			<value>loginDetail</value>
		</property>
	</bean>
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>/jsp/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>
3,springTest-services.xml的内容:

 <bean id="authenticationService" class="com.test.spring.mvc.services.AuthenticationService"/>

4,Java代码:

public class LoginController extends SimpleFormController {
	org.springframework.web.servlet.DispatcherServlet t;
	protected ModelAndView onSubmit(Object command) throws Exception{		
		LoginCommand loginCommand = (LoginCommand) command;
		authenticationService.authenticate(loginCommand);
		LoginDetail loginDetail = authenticationService.getLoginDetail(loginCommand.getUserId());
		return new ModelAndView(getSuccessView(),"loginDetail",loginDetail);
	}	
	private AuthenticationService authenticationService;
	public AuthenticationService getAuthenticationService() {
		return authenticationService;
	}
	public void setAuthenticationService(
			AuthenticationService authenticationService) {
		this.authenticationService = authenticationService;
	}
	....
public class LoginCommand {
	private String userId;
	private String password;
	....
public class LoginDetail {
	private String userName;
public class AuthenticationService {		
	public void authenticate(LoginCommand command) throws Exception{
		if(command.getUserId()!= null && command.getUserId().equalsIgnoreCase("test") 
				&& command.getPassword()!= null && command.getPassword().equalsIgnoreCase("test")){	
		}else{
			throw new Exception("User id is not authenticated"); 
		}
	}
	public LoginDetail getLoginDetail(String userId){
		return new LoginDetail(userId);
	}
}	
	
5,JSP文件:放在web-inf的jsp文件夹内

login.jsp:
<html><head>
<title>Login to Spring Test</title></head>
<body>
<h1>Please enter your userid and password.</h1>
<form method="post" action="login.do">
<table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5">
<tr>
<td alignment="right" width="20%">User id:</td>
<td width="20%"><input type="text" name="userId" value="test"></td>
<td width="60%">
</tr>
<tr>
<td alignment="right" width="20%">Password:</td>
<td width="20%"><input type="password" name="password" value="test"></td>
<td width="60%">
</tr>
</table>
<br>
<input type="submit" alignment="center" value="login">
</form>
</body>
</html>

loginDetail.jsp:
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%> 
<html><head>
<title>Login to Spring Test</title></head>
<body>
<h1>Login Details:</h1>
<br/>
Login as: <c:out value ="${loginDetail.userName}"/>
<br/>
<a href="/S3/login.do">logout</a>
</body>
</html>
在浏览器的地址栏输入http://localhost:8080/XXX/login.do进入login.jsp页面.

对配置的一些扩充点:

1为HandlerMapping和Controller的配置指定文件名称.

<servlet>  
    <servlet-name>springTestServlet</servlet-name>  
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    <init-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:/xxx.xml</param-value>  
    </init-param>  
    <load-on-startup>1</load-on-startup>  
</servlet>  

2,加入对MVC注解的支持:

<?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-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">
	<context:annotation-config />
	<context:component-scan base-package="com.test.spring.mvc.contoller" />
	<mvc:annotation-driven />

@Controller
public class AnnotationController {
    @RequestMapping("annotation.do")
    protected void test(HttpServletRequest request,
            HttpServletResponse response) throws Exception{        
        response.getWriter().println("test Spring MVC annotation");
    }
3,注解和SimpleFormController同时使用需要在DispatcherServlet对应的servlet配置文件(本例是springTestServlet-servlet.xml)里面配置:
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

否则会发生下面的异常:
javax.servlet.ServletException: No adapter for handler [com.test.spring.mvc.contoller.LoginController@6ac615]: Does your handler implement a supported interface like Controller?
	org.springframework.web.servlet.DispatcherServlet.getHandlerAdapter(DispatcherServlet.java:982)
	org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:770)
	org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
	org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
	org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
	javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
在WEB应用中的context配置文件通过下面的方式load,ContextLoaderListener是一个实现了ServletContextListener的listener,
它能够访问<context-param>而得到配置文件的路径,加载后初始化了一个WebApplicationContext,并且将其作为Attribute放在了servletContext中,
所有可以访问servletContext的地方则可以访问WebApplicationContext.
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/springTest-services.xml,
			classpath:conf/jndiDSAppcontext.xml
		</param-value>
	</context-param>
分享一个关于Spring MVC不错的链接 http://www.iteye.com/topic/1119598
  • 22
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring MVC(Model-View-Controller)是一种基于Java的Web应用程序开发框架,它将应用程序分为模型、视图和控制器三个部分,以实现松耦合的设计。下面我将为您介绍一些Spring MVC入门实例编程。 1. 搭建Spring MVC环境 首先,您需要搭建一个Spring MVC环境。您可以使用Maven或Gradle构建工具来创建一个新的Spring项目,然后在pom.xml或build.gradle文件中添加Spring MVC依赖项。您还需要配置一个Servlet容器,如Tomcat或Jetty,以运行您的应用程序。完成这些步骤后,您就可以开始编写Spring MVC应用程序。 2. 编写控制器 控制器是Spring MVC应用程序的核心部分,它负责处理请求并生成响应。要创建一个控制器,请创建一个Java类并注释它为@Controller。然后,您可以使用@RequestMapping注释来定义处理请求的方法。例如,以下代码定义了一个处理GET请求的方法: ``` @Controller @RequestMapping("/hello") public class HelloWorldController { @RequestMapping(method = RequestMethod.GET) public String sayHello(ModelMap model) { model.addAttribute("message", "Hello World!"); return "hello"; } } ``` 在上面的代码中,我们使用@RequestMapping注释将控制器映射到/hello路径。当GET请求发送到该路径时,Spring MVC将调用sayHello()方法。该方法将一个名为“message”的属性添加到模型中,并返回一个名为“hello”的视图名称。 3. 创建视图 视图是控制器生成的响应的一部分,它定义了在浏览器中显示的内容。要创建一个视图,请创建一个JSP文件并将其放在WEB-INF/views目录下。然后,您可以使用Spring标签库来访问模型中的属性。例如,以下代码显示了如何在JSP文件中访问名为“message”的属性: ``` <html> <head> <title>Hello World</title> </head> <body> <h1>${message}</h1> </body> </html> ``` 在上面的代码中,我们使用JSTL表达式${message}来显示模型中的“message”属性。 4. 运行应用程序 完成上述步骤后,您可以使用Servlet容器启动您的应用程序,并在浏览器中访问/hello路径。如果一切顺利,您应该会看到“Hello World”消息显示在浏览器中。 这些是Spring MVC入门实例编程的基本步骤。您可以深入学习Spring MVC,并使用更复杂的功能来构建更高级的Web应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值