这篇文章转载自:我的简书

初始Spring MVC

前几天开始了我的spring学习之旅,由于之前使用过MVC模式来做项目,所以我先下手的是 Spring MVC,做个练手项目,非常简单

项目介绍:

用户输入信息 -> 后台处理 -> 输出信息

开始
  1. 创建Spring MVC 项目(创建时下载所需文件)





2.创建完的项目目录是这样的





3. 配置Web项目结构

参考另一篇文章IDEA如何创建及配置Web项目(多图)

有变化的是: 不需要自己创建 lib 文件夹,在创建项目时已经建立,另外在 WEB-INF 建立 jsp 用于存放 .jsp 文件,其他的都没什么区别

配置完的样子(文件夹旁有箭头是因为我在做完项目才截图,具体的类以及其他文件都已在内):

  1. 配置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>
  1. 开始进行具体的操作

首先是基本数据类:

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进行注解,将会有产生警告:
![](https://upload-images.jianshu.io/upload_images/3426615-5c63d619a6d6712e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

按住Alt + Enter 修正错误,会看见提示:

官方推荐使用构造器注入

到此为止,后台工作就结束了

  1. 页面

接下来是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——练手小项目的更多相关文章

  1. vue练手小项目--眼镜在线试戴

    最近看到了一个眼镜在线试戴小项目使用纯js手写的,本人刚学习vue.js没多久,便试试用vue做做看了,还没完善. 其中包括初始图片加载,使用keywords查找,父子组件之间传递信息,子组件之间传递 ...

  2. Spring+Mybatis整合的练手小项目(一)项目部署

    声明:教程是网上找的,代码是自己敲的 项目目录大致如下: 1. 首先创建Maven工程,在pom.xml中加入项目所需依赖: <?xml version="1.0" enco ...

  3. 前端练手小项目——网页版qq音乐仿写

    qq音乐网页版仿写 一些步骤与注意事项 一开始肯定就是html+css布局和页面了,这段特别耗时间,耐心写完就好了 首先要说一下大致流程: 一定要先布局html!,所以一定要先分析页面布局情况,用不同 ...

  4. 简单的ssm练手联手项目

    简单的ssm练手联手项目 这是一个简单的ssm整合项目 实现了汽车的品牌,价格,车型的添加 ,修改,删除,所有数据从数据库中拿取 使用到了jsp+mysql+Mybatis+spring+spring ...

  5. Spring mvc创建的web项目,如何获知其web的项目名称,访问具体的链接地址?

    Spring mvc创建的web项目,如何获知其web的项目名称,访问具体的链接地址? 访问URL:  http://localhost:8090/firstapp/login 在eclipse集成的 ...

  6. Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码)

    Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合(注解及源码) 备注: 之前在Spring3 + Spring MVC+ Mybatis 3+Mysql 项目整合中 ...

  7. 【Python】【辅助程序】练手小程序:记录外网动态IP地址

    练手小程序 程序作用:对IP实时记录: 1.定时获取外网IP,存储在本地文件中: 编写思路: 1)收集获取外网的API接口       http://bbs.125.la/thread-1383897 ...

  8. 【Python精华】100个Python练手小程序

    100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. [程序1] 题目:有1.2.3.4个数字,能组成多少个互不相同 ...

  9. 整理了适合新手的20个Python练手小程序

    100个Python练手小程序,学习python的很好的资料,覆盖了python中的每一部分,可以边学习边练习,更容易掌握python. 本文附带基础视频教程:私信回复[基础]就可以获取的 [程序1] ...

随机推荐

  1. 面试长谈的String,StringBuffer,StringBuilder三兄弟有啥区别

    1.String: /** Strings are constant; their values cannot be changed after they * are created. String ...

  2. Loadrunner使用时IE浏览器打不开怎么办

    1.ie浏览器去掉启用第三方浏览器扩展 2.loadrunner11 键盘F4,在browser Emulation点击change,在弹出的提示框中Browser version 选择8.0,pla ...

  3. /var/spool/clientmqueue目录下存在大量文件的原因及解决方法

    问题现象:linux操作系统中的/var/spool/clientmqueue/目录下存在大量文件.原因分析: 系统中有用户开启了cron,而cron中执行的程序有输出内容,输出内容会以邮件形式发给c ...

  4. mysql的存储过程,函数,事件,权限,触发器,事务,锁,视图,导入导出

    1.创建过程 1.1 简单创建 -- 创建员工表 DROP TABLE IF EXISTS employee; CREATE TABLE employee( id int auto_increment ...

  5. Elasticsearch安装详解

    本文只介绍在windows上的安装和配置,其他安装和配置请参见官方文档 ES在windows上安装需下载zip安装包,解压后bin目录下有个 elasticsearch-service.bat 文件. ...

  6. RTMP消息详细介绍

    本文继上篇简单分析了RTMP协议如何进行通信进一步详细分析RTMP的消息都有哪些,以及这些消息有什么作用. 一.RMTP消息 由上一篇文章可知RTMP 消息有分成两个部分,一个是头部,一个是有效负载. ...

  7. 测试与发布(Beta版本)

    评分基准: 按时交 - 有分(测试报告-10分,发布说明-10分,展示博客-10分),检查的项目包括后文的两个方面 测试报告(基本完成5分,根据完成质量加分,原则上不超过满分10分) 发布说明(基本完 ...

  8. Ubuntu登陆密码忘记

    在VMware中安装了Ubuntu 10.04,经过了一段时间,再次登录的时候居然进不去了, 一开始不知道怎样在虚拟机中进入到Grub启动界面,网上搜索了一番,按照以下步骤重新为用户设定了新密码. 重 ...

  9. python API的安全认证

    我们根据pid加客户端的时间戳进行加密md5(pid|时间戳)得到的单向加密串,与时间戳,或者其它字段的串的url给服务端. 服务端接收到请求的url进行分析 客户端时间与服务端的时间戳之差如果大于规 ...

  10. 200行Python代码实现2048

    200行Python代码实现2048 一.实验说明 1. 环境登录 无需密码自动登录,系统用户名shiyanlou 2. 环境介绍 本实验环境采用带桌面的Ubuntu Linux环境,实验中会用到桌面 ...