How does springmvc work?
The working principle of springmvc is: 1. The browser sends a request to DispatcherServlet; 2. Find the corresponding Controller according to the request; 3. Return to ModelAndView; 4. Find the corresponding view object View and render it; 5. Return to browser.
SpringMVC working principle:
(recommended learning: java entry program)
1. The specified request sent by the browser will be handed over to DispatcherServlet, which will entrust other modules to perform real business and data processing;
2. DispatcherServlet will find HandleMapping, find the corresponding Controller according to the browser's request, and The request is handed over to the target Controller;
3. After the target Controller completes the business, it returns a ModelAndView to the DispatcherServlet;
4. The DispatcherServlet finds the corresponding view object View through the ViewResolver view parser;
4. The view object View is responsible for rendering and returning to the browser.
(Video tutorial recommendation: java video tutorial)
Let’s take a look at the code example:
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>springmvc</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- spring入口 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 项目启动时,就加载并实例化 --> <load-on-startup>1</load-on-startup> </servlet> <!-- 拦截所有不包括jsp的请求 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- springmvc注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 开启注解扫描 --> <context:component-scan base-package="cn.itcast.controller"></context:component-scan> <!-- 配置试图解析器 prefix:指定试图所在目录 suffix:指定视图的后缀名 例如:prifex="/WEB-INF/jsp/",suffix=".jsp",当viewname="test"时,跳转到/WEB-INF/jsp/test.jsp页面 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
UserControll class
@Controller @RequestMapping("user") public class UserController { @RequestMapping("findAllUsers") public ModelAndView findAllUsers() { ModelAndView mv = new ModelAndView(); ArrayList<User> users = new ArrayList<User>(); for (int i = 0; i < 5; i++) { User user = new User(); user.setUsername("zs" + i); user.setAge(20 + i); user.setIncome(16000.0+i*100); user.setIsMarry(false); user.setHobby(new String[] { "篮球"+i, "足球"+i }); users.add(user); } mv.addObject("users", users); mv.setViewName("users"); return mv; } }
Entity class
public class User implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String username; private Integer age; private Boolean isMarry; private Double income; private String[] hobby; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Boolean getIsMarry() { return isMarry; } public void setIsMarry(Boolean isMarry) { this.isMarry = isMarry; } public Double getIncome() { return income; } public void setIncome(Double income) { this.income = income; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } @Override public String toString() { return "User [username=" + username + ", age=" + age + ", isMarry=" + isMarry + ", income=" + income + ", hobby=" + Arrays.toString(hobby) + "]"; } }
jsp page
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" type="text/css" href="/css/user.css" /> </head> <body> <table id="customers"> <tr> <th>用户名</th> <th>年龄</th> <th>收入</th> <th>婚姻状态</th> <th>兴趣爱好</th> </tr> <!-- 遍历后台传递的集合数据 --> <c:forEach items="${users}" var="user"> <tr> <td>${user.username}</td> <td>${user.age}</td> <td>${user.income}</td> <!-- 判婚姻状态 --> <td><c:choose> <c:when test="${user.isMarry}">已婚</c:when> <c:otherwise>未婚</c:otherwise> </c:choose> </td> <td> <!-- 再次遍历用户爱好 --> <c:forEach items="${user.hobby}" var="hobby" varStatus="status"> ${hobby} <!-- 如果不是最后一个爱好,则加上逗号,否则就不加 --> <c:if test="${!status.last}">,</c:if> </c:forEach> </td> </tr> </c:forEach> </table> </body> </html>
The above is the detailed content of How does springmvc work?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solana Blockchain and SOL Token Solana is a blockchain platform focused on providing high performance, security and scalability for decentralized applications (dApps). As the native asset of the Solana blockchain, SOL tokens are mainly used to pay transaction fees, pledge and participate in governance decisions. Solana’s unique features are its fast transaction confirmation times and high throughput, making it a favored choice among developers and users. Through SOL tokens, users can participate in various activities of the Solana ecosystem and jointly promote the development and progress of the platform. How Solana works Solana uses an innovative consensus mechanism called Proof of History (PoH) that is capable of efficiently processing thousands of transactions.

SpringDataJPA is based on the JPA architecture and interacts with the database through mapping, ORM and transaction management. Its repository provides CRUD operations, and derived queries simplify database access. Additionally, it uses lazy loading to only retrieve data when necessary, thus improving performance.

VET Coin: Blockchain-based IoT ecosystem VeChainThor (VET) is a platform based on blockchain technology that aims to enhance the Internet of Things (IoT) field by ensuring the credibility of data and enabling safe transfer of value. supply chain management and business processes. VET coin is the native token of the VeChainThor blockchain and has the following functions: Pay transaction fees: VET coins are used to pay transaction fees on the VeChainThor network, including data storage, smart contract execution and identity verification. Governance: VET token holders can participate in the governance of VeChainThor, including voting on platform upgrades and proposals. Incentives: VET coins are used to incentivize validators in the network to ensure the

ShibaInu Coin: Dog-Inspired Cryptocurrency ShibaInu Coin (SHIB) is a decentralized cryptocurrency inspired by the iconic Shiba Inu emoji. The cryptocurrency was launched in August 2020 and aims to be an alternative to Dogecoin on the Ethereum network. Working Principle SHIB coin is a digital currency built on the Ethereum blockchain and complies with the ERC-20 token standard. It utilizes a decentralized consensus mechanism, Proof of Stake (PoS), which allows holders to stake their SHIB tokens to verify transactions and earn rewards for doing so. Key Features Huge supply: The initial supply of SHIB coins is 1,000 trillion coins, making it one of the largest cryptocurrencies in circulation. Low price: S

Polygon: A multifunctional blockchain that builds the Ethereum ecosystem Polygon is a multifunctional blockchain platform built on Ethereum, formerly known as MaticNetwork. Its goal is to solve the scalability, high fees, and complexity issues in the Ethereum network. Polygon provides developers and users with a faster, cheaper, and simpler blockchain experience by providing scalability solutions. Here’s how Polygon works: Sidechain Network: Polygon creates a network of multiple sidechains. These sidechains run in parallel with the main Ethereum chain and can handle large volumes of transactions, thereby increasing overall network throughput. Plasma framework: Polygon utilizes the Plasma framework, which

Beam Coin: Privacy-Focused Cryptocurrency Beam Coin is a privacy-focused cryptocurrency designed to provide secure and anonymous transactions. It uses the MimbleWimble protocol, a blockchain technology that enhances user privacy by merging transactions and hiding the addresses of senders and receivers. The design concept of Beam Coin is to provide users with a digital currency option that ensures the confidentiality of transaction information. By adopting this protocol, users can conduct transactions with greater confidence without worrying about their personal privacy information being leaked. This privacy-preserving feature makes Beam Coin work. MimbleWimble protocol enhances privacy by: Transaction merging: It combines multiple transactions into

AR Coin: Digital currency based on augmented reality technology AR Coin is a digital currency that uses augmented reality technology to provide users with the experience of interacting with digital content, allowing them to create immersive experiences in the real world. How it works AR Coin works based on the following key concepts: Augmented Reality (AR): AR technology overlays digital information on the real world, allowing users to interact with virtual objects. Blockchain: Blockchain is a distributed ledger technology used to record and verify transactions. It provides security and transparency to AR coins. Smart Contracts: Smart contracts are codes stored on the blockchain that are used to automate specific operations. They play a vital role in the creation and management of AR coins. The workflow of AR coins is as follows: Create AR body

Algorand: A blockchain platform based on pure Byzantine consensus protocol Algorand is a blockchain platform built on pure Byzantine consensus protocol and aims to provide efficient, secure and scalable blockchain solutions. The platform was founded in 2017 by MIT professor Silvio Micali. Working Principle The core of Algorand lies in its unique pure Byzantine consensus protocol, the Algorand consensus. This protocol allows nodes to achieve consensus in a trustless environment, even if there are malicious nodes in the network. Algorand consensus achieves this goal through a series of steps. Key generation: Each node generates a pair of public and private keys. Proposal phase: A randomly selected node proposes a new zone
