spring(三).搭建Spring MVC项目(基于注解)

前面我们搭建了一个基于xml配置的简单的Spring MVC项目实现了用户登录,特别麻烦,今天来给大家介绍一个简单点方式,是基于注解。

话不多说,开始实战:

1.创建一个web项目,项目名称是:springmvctest,同样也是实现一个简单的登录

2.引入相关jar包,这里我用的是spring5.0.8.release包

3.在src目录下编写applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"  
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" 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.2.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	
</beans>

4.在web.xml中配置DispatchServlet

5.在applicationContext.xml配置组件自动扫描、注册SpringMVC的相关bean、配置ViewResolver

6.在/WEB-INF目录下,编写login.jsp、ok.jsp页面

位置如下

login.jsp页面内容:

ok.jsp页面内容如下

7.现在来写LoginController,(注意:这个Controller所在包,被包含到刚才在applicationContext.xml文件里配置自动扫描组件设置的包中,即,这个Controller要能被扫描到spring容器中)

到现在为止,要编写的代码,都编写完了。

这个项目实现的业务也是登录:

(1).从前端页面先发请求toLogin.do,调到LoginContrller的方法togin()上,关键是因为该方法上打了@RequestMapping("/toLogin.do")注解,该注解里参数和请求相对应,即,要一致。

(2).该方法返回”login“,经过ViewResolver解析后就是/WEB-INF/login.jsp页面,然后将该页面展示到浏览器上。

(3).在该页面上输入用户名:root和密码:1234,点击登录按钮,前端页面发出请求login.do,该请求调到LoginController的login()方法,同样是因为该方法打上了@RequestMapping("/login.do")注解。

(4).login()方法校验用户名和密码是否正确,若正确则返回ok,经过ViewResolver解析为/WEB-INF/ok.jsp,将该页面展示到浏览上;若不正确则返回login.经过ViewResolver解析后就是/WEB-INF/login.jsp页面,展示到前端页面,让用户重新输入。

接下来我们实际访问写看看是不是这个情况,先把项目放进tomcat中启动起来。

a.在浏览器地址栏输入:localhost:8080/springmvctest/toLogin.do

b.接下来响应页面为

c.在该页面输入用户名和密码,分别是:root和1234

d.点击登录

到这里我们基于注解搭建spirng MVC项目实现简单登录,就完成了。是不是比基于xml配置要简单多了。当然美中不足的是没有访问数据库的操作,笔者会在后续的文章中提到的。请持续关注,和笔者一起学习spring!

当然了,若有不足和错误之处,也请大家不吝赐教,有任何问题都可以给我留言,我们一起探讨进步!

猜你喜欢

转载自blog.csdn.net/weixin_41968788/article/details/82532374
今日推荐