Maven入门实战(二)——依赖添加、依赖范围和SpringMVC的结合

 上一节中我们介绍了Maven的作用以及相关的安装配置方法和一个非常简单的实例,接下来我们更近一步,为了加深对项目的影响,我们将结合SpringMVC进行Maven项目的实战。

1 Maven的依赖添加

 首先我们先创建一个Maven工程,创建方法同上一节中的方法,最后创建出来的工程目录结构如下:


 发现又有错误了,首先这是一个Maven项目,必不可少的需要web.xml文件,所以先在src/main/webapp/WEB-INF下创建web.xml文件。


 接下来在/src/main/resources/view/下新建info.jsp文件。


 发现缺少了依赖包HttpServelet,接下来就是要添加依赖包了,在前一篇的Maven入门中已经描述过了如何通过MVN_Repository的网站来搜索对应的jar包,并添加。在这里假定我们的本地仓库已经有很多Jar包了,那么就可以直接添加依赖包,可以搜索对应的包加入依赖,下面本人展示一下如何添加依赖包最为便捷。

 首先检查本地仓库是否已经建立索引,如果没有在STS中建立索引,搜索依赖包就无效了。打开STS上方工具栏中Window-->Show View-->Other,然后搜索maven,然后选择Maven Repository。


看到如下视图:


 这里可以看出本地仓库的路径是C:\Users\Vander\.m2\repository,在Local Repository处点击右键,选择“RebuildIndex”,重新建立索引即可。


接着打开Dependencies,选择add,添加依赖的jar包,输入servlet,找到javax.servletjsp-api,选中将其添加即可完成。

 

 这里同时也会观察到一旦你选中之后,相对应的Jar包的坐标都会帮你填上。添加了servlet和jsp的jar包,保存之后,发现info.jsp文件已经没有报错了。

  

 这里同时也会观察到一旦你选中之后,相对应的Jar包的坐标都会帮你填上。添加了servlet和jsp的jar包,保存之后,发现info.jsp文件已经没有报错了。

2 Maven的依赖范围

上图还观察到Scope(依赖范围)有五种:compile、provided、runtime、test、system这五种。这里主要掌握以下表格的前四行。

Scope

编译

测试

运行

打包

Compile

Provided

 

 

Test

 

 

 

Runtime

 

System(不掌握)

 

 

 

 

         依赖范围其实就是告诉Maven,哪个包是哪个阶段需要被用到的,Maven在进行相关指令操作的时候就会去执行相关的操作。

这里举几个例子,先说明一下Compile,首先SpringMVC需要用到spring core的jar包,而这个jar包如果不添加进这个工程中,编译就会报错,并且在写测试程序的时候也是需要用到的,最后进行打包部署运行的时候,也需要将这个jar包打包进这个Maven项目中。

接着是Provided,与这个对应的是servlet的jar包,因为tomcat本身就带了servlet的jar包,但是项目是没有意识到tomcat的jar包的,所以如果你不加servlet的jar包,编译的时候就会报错,但是你如果打包执行mvn:package,直接运行起来,发现程序是能运行的,因为tomcat本身就有这个jar包。

然后是Test,顾名思义,就是在测试的时候需要,到最后打包上线部署的时候是不需要在,仅仅在我们平时进行测试的时候需要用到这个jar包,典型的例子就是junit.jar,我们在上线的时候并不会将它打入到我们的工程中。

         最后一个是Runtime,这个稍微有点难理解,编译的时候不需要,编译的时候没有那eclipse不就会报错吗,但是有些时候虽然你需要用到某些jar包,但是eclipse是无感知的,例如我们在注册数据库驱动的时候会class.forName(“com.mysql.jdbc.Driver”),用到了mysql的驱动,但是eclipse本身却是无感知的。

3 与SpringMVC的结合(使用XML配置文件)

由于这里用的是SpringMVC来完成MVC模式,所以还要添加spring-webmvc的依赖,这里已添加之后打开DependencyHierarchy发现maven帮我添加了一大堆的包,这是由于spring-webmvc需要依赖spring框架,所以spring框架的相关的jar包都被引入了,这就是maven的依赖管理。


 下面完成一个简单的从页面前端输入用户名和密码,然后传到后台进行验证,最后再返回登陆结果。这里用的是配置文件的方式来进行SpringMVC的配置,目前配置文件配置Spring项目似乎已经有点过时了,但是我们在工作中还会经常接触旧的系统,所以不管是用xml文件来配置还是使用无xml的配置方式都需要进行掌握。

         首先作为一个web项目肯定需要web.xml。

在SpringMVC中web.xml配置文件需要配置以下四个部分:

Spring的上下文(context):即contextConfigLocation,用来指定SpringMVC的Spring IoC的配置文件在什么位置,这样Spring就会找到这些配置文件去加载它们,这里可以支持正则表达式。(这里如果不配置的话,会在classpath的路径下找application-*.xml作为IoC的配置文件,找不到的话启动就会报错)。

DispatchServlet:实际上就是一个拦截请求的servlet,用来拦截通过浏览器发送的URI请求,拦截给对应处理器(Handler),这里中间还有一些细节,这里就不细说了。

ContextLoaderListener:实现了接口ServletContextListener,配置这个的目的是在web项目初始化之前,先进行SpringIoC容器的初始化,再最后web项目关闭之时,完成Spring IoC容器的资源进行释放。

以下是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_3_0.xsd" id="WebApp_ID" version="3.0">
                        
  <display-name>mvn-spring</display-name>
  <welcome-file-list>
  	<welcome-file>login.jsp</welcome-file>
    <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 context-->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/spring/spring-*.xml</param-value>
	</context-param>

	<!-- 配置SpringMVC -->
	<servlet>
		<servlet-name>mvn-spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/spring/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvn-spring</servlet-name>
		<!-- 所有的请求都进入springMVC -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 配置监听器加载spring -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 配置过滤器,解决post的乱码问题 -->
	<filter>
		<filter-name>encoding</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<async-supported>true</async-supported>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

4 简单的页面登录验证

         下面我将css文件、jQuery等资源放在了webapp目录下的static里面,写了一个简单的jsp页面,进行简单的登录验证。以下是login.jsp的内容:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Sign in</title>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
	System.out.println(basePath);//http://127.0.0.1:8080/mvn-spring/
%>
<link href="<%=basePath%>static/css/login.css" rel="stylesheet">
<script type="text/javascript" src="<%=basePath%>static/js/login.js"></script>
</head>
<body background="<%=basePath%>static/images/background-2.jpg">
	<form action="<%=basePath%>login" method="post" class="w">     
		
		<div class="form-header">
			<div>
       			<h1>Sign in</h1>
     		</div>
     	</div>

		<div class="form-body">
			<div class="email">
				<span>Username or email address</span>
			</div>
			
			<div class="emailtext">
				<input type="text" name="userName"  id="userName" value="username"></input>
			</div>
			
			<div class="password">
				<span class="password-left">Password</span>
				<a href="#" class="password-right fr">Forgot password?</a>
			</div>
			
			<div class="passwordtext">
				<input type="text" name="password" id="password" value="password"></input>
			</div>
	
			<div class="submit" >
				<button type="submit" class="SignIn">Sign in</button>
			</div>   
		</div>     
	</form>
	

</body>
</html>

 项目的目录结构如下:

 大致的顺序是首先tomcat会去读取web.xml,加载spring context的相关配置文件,在这里spring ioc的配置文件是classpath*:config/spring/spring-*.xml,这里对应的是spring-mvc.xml这个文件,以下是spring-mvc.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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<!-- 扫描所有的类到spring容器 -->
	<context:component-scan base-package="szu.vander.*" />
	
	<!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
	<bean  
	    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">  
	</bean>  
	<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">  
	    <property name="messageConverters">  
	        <list>  
	            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />  
	        </list>  
	    </property>  
	</bean>
	
	<!-- 配置注解驱动 -->
	<mvc:annotation-driven />
	<!-- 默认的Sevelet来响应静态文件 -->
	<mvc:default-servlet-handler/>
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 前缀 -->
		<property name="prefix" value="WEB-INF/classes/view/" />
		<!-- 后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
	<!-- **三大组件配置完毕** -->

接下来是写控制器部分,代码如下:

package szu.vander.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController {

	@RequestMapping(value = "login")
	public ModelAndView login(String userName, String password){
		ModelAndView mv = new ModelAndView();
		if(userName.equals("Vander") && password.equals("199407")) {
			mv.addObject("loginResult", "登录成功");
		} else {
			mv.addObject("loginResult", "登录失败");
		}
		mv.setViewName("jsp/login_result");
		return mv;
	}
	
}

 将项目部署到tomcat中,在浏览器中输入http://localhost:8080/mvn-spring/,即可访问登录界面。


 输入用户名和密码,返回登录结果。

以下是登录结果页面的源码:

<!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=ISO-8859-1">
        <title>参数</title>
        <!-- 加载Query文件-->
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.0.js"></script>
</head>
    <body>
    	<div id="result">${loginResult}</div>
    </body>
</html>

 最后稍微解释一下这个过程,在项目启动的起来的时候,SpringMVC会根据配置,获取配置信息,获得URI和Handler(也可以理解成Controller)之间的映射关系,点击“Sign”按钮之后,会向http://127.0.0.1:8080/mvn-spring/login这个地址发送请求,经过dispatchServlet解析之后,截取url中的login,找到对应的Controller,然后再找到对应的方法,这里会执行LoginController中的login方法,jsp页面中的userName和password就会传到后台,这两个值会传递到login方法中,作为login方法中的两个参数,这两个参数经过验证之后就会将登录结果写入loginResult这个变量中,然后使用modelAndView设定要返回的视图,在Controller返回模型和视图给DispatchServlet之后,DispatchServlet会把对应的视图信息传递给ViewResolver(视图解析器),由ViewReslover将model渲染到视图中去,最后响应给用户。









猜你喜欢

转载自blog.csdn.net/Vander1991/article/details/79200574