广告
返回顶部
首页 > 资讯 > 后端开发 > Python >实例详解SpringMVC入门使用
  • 689
分享到

实例详解SpringMVC入门使用

2024-04-02 19:04:59 689人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

mvc模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(Controller

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" rel="external nofollow" >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>

到此这篇关于实例详解springMVC入门使用的文章就介绍到这了,更多相关SpringMVC详解内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 实例详解SpringMVC入门使用

本文链接: https://www.lsjlt.com/news/159442.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 实例详解SpringMVC入门使用
    MVC模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(Controller...
    99+
    2022-11-12
  • SpringMVC注解的入门实例详解
    目录1、在 web.xml 文件中配置前端处理器2、在 springmvc.xml 文件中配置处理器映射器,处理器适配器,视图解析器3、编写 Handler4、编写 视图 index...
    99+
    2022-11-13
  • SpringMVC入门实例
    1介绍MVC框架是什么MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到...
    99+
    2023-05-30
    springmvc 入门 sprin
  • SpringMVC入门实例分析
    今天小编给大家分享一下SpringMVC入门实例分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解...
    99+
    2022-10-19
  • 基于SpringMVC入门案例及讲解
    目录一、SpringMvc概述二、入门案例 开发步骤1、创建web工程、引入依赖2、配置SpringMvc入口文件3、创建Springmvc.xml文件4、创建 业务处理器...
    99+
    2022-11-12
  • 详解SpringMVC中拦截器的概念及入门案例
    目录一、拦截器概念二、拦截器入门案例一、拦截器概念 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行 作用: 在指定的方法...
    99+
    2022-11-13
  • node.js入门实例helloworld详解
    本文实例讲述了node.js入门实例helloworld。分享给大家供大家参考,具体如下: 将下面的代码保存为:server.js存到E盘下面的node目录中。 var http = require('...
    99+
    2022-06-04
    详解 实例 入门
  • ReactJS入门实例教程详解
    目录一、ReactJS简介二、对ReactJS的认识及ReactJS的优点1、ReactJS的背景和原理2、组件化三、下载ReactJS,编写Hello,world四、Jsx语法五、...
    99+
    2022-11-13
  • hibernate4快速入门实例详解
    Hibernate是什么Hibernate是一个轻量级的ORMapping框架ORMapping原理(Object RelationalMapping)ORMapping基本对应规则:类跟表相对应类的属性跟表的字段相对应类的实例与表中具体的...
    99+
    2023-05-31
    hibernate4 入门 te
  • JCrontab简单入门实例详解
    本文实例为大家分享了JCrontab简单入门,供大家参考,具体内容如下创建一个JavaWeb项目首先要下载JCrontab的相关jar包,Jcrontab-2.0-RC0.jar。放到lib文件夹下。 在src下新建文件jcron...
    99+
    2023-05-30
    jcrontab 入门实例 实例详解
  • dubbo入门指南及demo实例详解
    目录1. Dubbo是什么?2. Dubbo能做什么?3. dubbo的架构4. dubbo使用方法。服务提供者:服务消费者:1. Dubbo是什么? Dubbo是一个分布式服务框架...
    99+
    2022-11-13
  • SpringMVC使用RESTful接口案例详解
    目录一、准备工作二、功能清单三、具体功能-访问首页一、准备工作 和传统 CRUD 一样,实现对员工信息的增删改查。 ①搭建环境 添加相关依赖 web.xml springmvc.xm...
    99+
    2022-11-13
    SpringMVC RESTful SpringMVC RESTful接口 SpringBoot RESTful
  • spring boot集成redis基础入门实例详解
    目录redisredis和spring bootspring boot集成redisredis使用redis在spring boot中存取数据set写入数据get读取数据模拟接口请求...
    99+
    2022-11-13
  • Rust入门之函数和注释实例详解
    目录写在前面函数参数语句和表达式返回值注释写在前面 今天我们来学习 Rust 中的函数,最后会捎带介绍一下如何在 Rust 中写注释。也是比较轻量级的一节,大家快速过一下即可。 函数...
    99+
    2022-11-13
  • spring boot集成redis基础入门实例详解
    目录Redisredis和spring bootspring boot集成redisredis使用redis在spring boot中存取数据set写入数据get读取数据模拟接口请求读取redis中的数据总结redis ...
    99+
    2022-10-08
  • Web Components入门教程示例详解
    目录Web Components不兼容IE困境Web Components核心技术自定义元素HTML模板(template、slot)shadow root(影子Dom)Web Co...
    99+
    2023-05-18
    Web Components入门教程 Web Components
  • Spark-Sql入门程序示例详解
    SparkSQL运行架构 Spark SQL对SQL语句的处理,首先会将SQL语句进行解析(Parse),然后形成一个Tree,在后续的如绑定、优化等处理过程都是对Tree的操作,而...
    99+
    2022-11-12
  • C++入门之vector使用详解
    目录前言创建对象迭代器数据插入数据删除容量操作总结前言 兜兜转转,我们来到了C++的vector章节,今天就讲讲怎么使用vector吧. vector的本质就是一个线性的顺序表,只不...
    99+
    2022-11-12
  • Xterm.js入门官方文档示例详解
    目录前言xterm.js是什么安装初始化使用插件API文档模块类 Terminal构造函数 constructor接口插件attach插件前后端示例结语前言 入职的新公司所在的事业部...
    99+
    2022-11-13
    Xterm.js 官方文档 Xterm.js 入门
  • Zookeeper详解(从安装—入门—使用)
    Zookeeper详解(从安装—入门—简单使用) 🍋1.zookeeper概念🍋2.zookeeper的安装🍊2.1环境准备:🍊2.2下载🍊2.3上传并...
    99+
    2023-08-18
    zookeeper 服务器 java
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作