初始Spring MVC——练手小项目
这篇文章转载自:我的简书
初始Spring MVC
前几天开始了我的spring学习之旅,由于之前使用过MVC模式来做项目,所以我先下手的是 Spring MVC,做个练手项目,非常简单
项目介绍:
用户输入信息 -> 后台处理 -> 输出信息
开始
- 创建Spring MVC 项目(创建时下载所需文件)
2.创建完的项目目录是这样的
3. 配置Web项目结构
参考另一篇文章IDEA如何创建及配置Web项目(多图)
有变化的是: 不需要自己创建 lib 文件夹,在创建项目时已经建立,另外在 WEB-INF 建立 jsp 用于存放 .jsp 文件,其他的都没什么区别
配置完的样子(文件夹旁有箭头是因为我在做完项目才截图,具体的类以及其他文件都已在内):
- 配置Spring MVC的核心 —— dispatcher-servlet.xml
Spring MVC provides an annotation-based programming model where @Controller and @RestController components use annotations to express request mappings, request input, exception handling, and more. Annotated controllers have flexible method signatures and do not have to extend base classes nor implement specific interfaces.
如官方文档所说,我也使用了注解来定义控制器(Controller)和服务(Service).
首先需要添加的是
<context:component-scan base-package="controller"/>
<context:component-scan base-package="service"/>
这样我们就能通过注解来定义Controller以及Service.
然后,我们需要配置视图解析器,在具体操作时只要写出视图的名称(xxx),就可以采用URL拼接的方式,达到这种效果:/WEB-INF/jsp/xxx.jsp
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
- 开始进行具体的操作
首先是基本数据类:
public class Product {
private long id;
private String name;
private String price;
private String inventory;
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() { return name; }
public void setPrice(String price) {
this.price = price;
}
public String getPrice() { return price; }
public void setInventory(String inventory) {
this.inventory = inventory;
}
public String getInventory() { return inventory; }
}
接下来是收集用户输入所需要的表单类:
public class ProductForm {
private String name;
private String price;
private String inventory;
public void setName(String name) {
this.name = name;
}
public void setPrice(String price) {
this.price = price;
}
public void setInventory(String inventory) {
this.inventory = inventory;
}
public String getName() {
return name;
}
public String getPrice() {
return price;
}
public String getInventory() {
return inventory;
}
}
然后编写服务接口,以及它的实现类
import domain.Product;
public interface ProductService {
Product add(Product product);
Product get(long id);
}
ProductServiceImpl就是刚才配置的服务(Service)
import domain.Product;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
@Service
public class ProductServiceImpl implements ProductService{
private Map<Long, Product> productMap = new HashMap<>();
private AtomicLong atomicLong = new AtomicLong();
@Override
public Product add(Product product){
long id = atomicLong.incrementAndGet();
product.setId(id);
productMap.put(id, product);
return product;
}
@Override
public Product get(long id){
return productMap.get(id);
}
}
最重要的是控制器:
采用@Autowired注解的方式自动装配Service,
使用@RequestMapping注解的方式,将注解中的路径映射到控制器:
import domain.Product;
import form.ProductForm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import service.ProductService;
@Controller
public class ProductController {
//日志记录具体操作
private static final Log logger = LogFactory.getLog(ProductController.class);
@Autowired
private ProductService productService;
//method = RequestMethod.POST表示只接受POST形式的请求
@RequestMapping(value = "/product_save", method = RequestMethod.POST)
//采用POST的方式发送请求
public String saveProduct(ProductForm productForm, RedirectAttributes redirectAttributes){
logger.info("saveProduct called");
//获得用户输入
Product product = new Product();
product.setName(productForm.getName());
product.setPrice(productForm.getPrice());
product.setInventory(productForm.getInventory());
//添加有记录的产品,并且根据ID进行重定向
Product savedProduct = productService.add(product);
redirectAttributes.addFlashAttribute("message", "Add product Successfully");
return "redirect:/product_view/" + savedProduct.getId();
}
//根据ID,将用户输入展示在ProductView中
@RequestMapping(value = "product_view/{id}")
public String viewProduct(@PathVariable Long id, Model model){
//根据ID得到信息
Product product = productService.get(id);
model.addAttribute("product", product);
//ProductView.jsp
return "ProductView";
}
}
需要注意的是,在现在的Spring版本中,如果直接对Service进行注解,将会有产生警告:

按住Alt + Enter 修正错误,会看见提示:
官方推荐使用构造器注入
到此为止,后台工作就结束了
- 页面
接下来是JSP的编写:
首先是用户输入的页面 (ProductForm.jsp)
<body>
<div>
<form action="product_save" method="post">
<fieldset>
<legend>Add a product</legend>
<p>
<label for="name">Product Name: </label>
<input type="text" id="name" name="name">
</p>
<p>
<label for="price">Price: </label>
<input type="text" id="price" name="price">
</p>
<p>
<label for="inventory">Inventory: </label>
<input type="text" id="inventory" name="inventory">
</p>
<p>
<input id="reset" type="reset" tabindex="4">
<input id="submit" type="submit" tabindex="5" value="Add Product">
</p>
</fieldset>
</form>
</div>
</body>
比较表单中的
和控制器中的@RequestMapping(value = "/product_save")就能够知道,通过@RequestMapping注解,任何"/product_save"开头的路径都会被映射到控制器中,并采用saveProduct()方法
然后是显示用户输入的页面 (ProductView.jsp)
<body>
<div>
<h3>${message}</h3>
<h4>Details:</h4>
Product Name: ${product.name}<br>
Price: ${product.price}<br>
Inventory: ${product.inventory}<br>
</div>
</body>
${message}就是刚才在控制器中重定向页面的属性,它会在页面头部输出"Add product Successfully"
项目构建完毕
最终的目录结构是这样:
然后我们运行, 输入:
页面难看,主要是用Spring MVC做出来的就可以了
结果是这样的:
目光移至URL,填写信息提交后,页面重定向至 product_view/{id} 处,当前id = 1
到处,我们的这个练手的小项目就结束了,有什么问题都可以私信我
初始Spring MVC——练手小项目的更多相关文章
- vue练手小项目--眼镜在线试戴
最近看到了一个眼镜在线试戴小项目使用纯js手写的,本人刚学习vue.js没多久,便试试用vue做做看了,还没完善. 其中包括初始图片加载,使用keywords查找,父子组件之间传递信息,子组件之间传递 ...
- Spring+Mybatis整合的练手小项目(一)项目部署
声明:教程是网上找的,代码是自己敲的 项目目录大致如下: 1. 首先创建Maven工程,在pom.xml中加入项目所需依赖: <?xml version="1.0" enco ...
- 前端练手小项目——网页版qq音乐仿写
qq音乐网页版仿写 一些步骤与注意事项 一开始肯定就是html+css布局和页面了,这段特别耗时间,耐心写完就好了 首先要说一下大致流程: 一定要先布局html!,所以一定要先分析页面布局情况,用不同 ...
- 简单的ssm练手联手项目
简单的ssm练手联手项目 这是一个简单的ssm整合项目 实现了汽车的品牌,价格,车型的添加 ,修改,删除,所有数据从数据库中拿取 使用到了jsp+mysql+Mybatis+spring+spring ...
- Spring mvc创建的web项目,如何获知其web的项目名称,访问具体的链接地址?
Spring mvc创建的web项目,如何获知其web的项目名称,访问具体的链接地址? 访问URL: http://localhost:8090/firstapp/login 在eclipse集成的 ...
- Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)
Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码) 备注: 之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中 ...
- 【Python】【辅助程序】练手小程序:记录外网动态IP地址
练手小程序 程序作用:对IP实时记录: 1.定时获取外网IP,存储在本地文件中: 编写思路: 1)收集获取外网的API接口 http://bbs.125.la/thread-1383897 ...
- 【Python精华】100个Python练手小程序
100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. [程序1] 题目:有1.2.3.4个数字,能组成多少个互不相同 ...
- 整理了适合新手的20个Python练手小程序
100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. 本文附带基础视频教程:私信回复[基础]就可以获取的 [程序1] ...
随机推荐
- linux服务器中毒可疑进程sfewfesfs CPU80%
我用的是wdlinux, 难免会有漏洞,不知怎么就被莫名其妙地给入侵了,而且还频繁发包.下面是我查看攻击机器的整个过程. 首先跟客户要了root密码登录看,第一个命令是就top cd /proc/25 ...
- 单例模式、简单工厂模式、XML解析
单例模式: 什么是单例模式? 针对特定问题提出的特定解决方案 为什么使用设计模式? 让程序有更好的可扩展性 在哪里使用? 一般情况下,开发中真正使用设计模式的地方,JVM(虚拟机)底层机制模式 usi ...
- [日常] NOIWC 2018爆零记
开个坑慢慢更(逃 (然而没准会坑掉?) day 0 大概 $8:30$ 就滚去雅礼了qwq 过去的时候发现并没有人...进报到处楼门的时候还被强行拍照围观了一波OwO 然后就领了HZ所有人的提包和狗牌 ...
- WHCTF-babyre
WHCTF-babyre 首先执行file命令得到如下信息 ELF 64-bit LSB executable, x86-64 尝试用IDA64打开,定位到关键函数main发现无法F5,尝试了修复无果 ...
- 简单的C语言编译器--词法分析器
1. 定义词法单元Tag 首先要将可能出现的词进行分类,可以有不同的分类方式.如多符一类:将所有逗号.分号.括号等都归为一类,或者一符一类,将一个符号归为一类.我这里采用的是一符一类的方式.C代码 ...
- bisect 二分查找
先说明的是,使用这个模块的函数前先确保操作的列表是已排序的. 先看看 insort 函数: 其插入的结果是不会影响原有的排序. 再看看 bisect 函数: 其目的在于查找该数值将会插入的位置并返 ...
- 201621123043 《Java程序设计》第6周学习总结
1.1 面向对象学习暂告一段落,请使用思维导图,以封装.继承.多态为核心概念画一张思维导图或相关笔记,对面向对象思想进行一个总结. 注1:关键词与内容不求多,但概念之间的联系要清晰,内容覆盖面向对象的 ...
- 同一个页面同时拥有collectionView和navigationBar和tabBar时可能遇到的问题
写一个页面的时候,遇到了页面加载时候collectionView的最下面少了49个像素的位置,切换去别的页面之后,再返回,又变回正常,多方求解无果后,发现原来是系统自带的适应功能导致的,加入以下代码即 ...
- SQL之Left Join 关联条件的探讨
在测试工作中,有时需要测试数据库数据经过sql计算后的结果是否满足某一功能查询得到的返回值. 针对某些需要功能需要联查多张表,此时 关联 的作用就异常重要了,而针对多表关联,其中 关联条件的重要性不言 ...
- shell中冒号 : 用途说明
我们知道,在Linux系统中,冒号(:)常用来做路径的分隔符(PATH),数据字段的分隔符(/etc/passwd)等.其实,冒号(:)在Bash中也是一个内建命令,它啥也不做,是个空命令.只起到占一 ...