spring mvc 入门案例

本文详细介绍了如何使用Spring MVC框架创建并运行一个简单的Web应用,包括创建Web容器、视图创建、执行类以及运行实例的过程。通过Spring MVC,开发者能够更方便地构建和管理Web应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

去学习了下spring MVC的官网例子,使用起来真方便了许多,主要步骤如下:

1,首先要,创建一个Web容器:

package hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

//controller注解指明该类是一个web容器类
//是可以被ComponentScan 扫描到的,是一种Component类型
//这个类就相当servlet
@Controller
public class GreetingController {
//接收的url映射地址
@RequestMapping("/greeting")
//@RequestParam 需要传递的参数'name',但是非必须,默认情况下值为world
//跳转到'greeting'的视图,就是greeting.html
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
 

 
如果想指定接受http action类型,可以设置@RequestMapping(method=GET)

2,视图创建src/main/resources/templates/greeting.html
官网说明视图类型可以有很多种,
http://spring.io/understanding/view-templates
而这里使用的是Thymeleaf模板,具体模板用法可以参考http://www.thymeleaf.org/

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>

 

3,执行类src/main/java/hello/Application.java

package hello;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;

//让spring递归的去扫描package hello下面所有的class文件,如果被标记@Componnet则被spring管理
@ComponentScan
//spring会做一些默认的操作,比如Application类会依赖嵌入式的tomcat,则tomcat会启动和配置
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        //spring会去管理该类,并且去读取application中的注解的内容
        SpringApplication.run(Application.class, args);
    }
}

 

4,运行
在gs-serving-web-content-master/complete/路径下运行  gradlew build
java -jar build/libs/gs-serving-web-content-0.1.0.jar

在浏览器中输入http://localhost:8080/greeting
或者http://localhost:8080/greeting?name=User 可以看到效果。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值