Bootstrap

在Eclipse下使用Maven创建SpringMVC样例项目

1,新建maven项目,项目名起为:MavenSpringMVC。
具体步骤参见我的上一篇博客:在eclipse下使用Maven创建Struts2项目样例
2,配置pom.xml文件,引入依赖包(当然,我也不是一开始就知道需要引入哪些包的,我一开始也只是引入了Spring的核心包,后面发现缺包了就再补上)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.yutao</groupId>
    <artifactId>MavenSpringMVC</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>MavenSpringMVC Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>
    <build>
        <finalName>MavenSpringMVC</finalName>
    </build>
</project>

3,规划一下我们的项目的访问路径及项目流程结构。
按照前人的建议,jsp、js等文件放在WEB-INF下是较为安全的、不能被外部直接访问的,因此这里采用这种建议,具体组织结构见下图:
这里写图片描述
这样组织目录结构之后,我们来考虑下项目的访问流程:
由于我们上面的目录结构限制了访问项目时是不能直接访问jsp文件的,因此我们所有的页面跳转都要通过controller实现。
首先输入localhost/MavenSpringMVC应该通过controller跳转访问到用户端首页(client/index.jsp),在该页面上点击“登录”按钮后通过controller跳转到用户登录页面(client/login.jsp),在此页面输入用户名、密码,点击“登录”按钮,提交表单至后台进行登陆验证(client/login.do),验证失败则通过controller跳转至错误展示页面(error.jsp),验证成功则通过controller跳转至首页(client/index.jsp)并展示当前登录用户的登录状态,同时需要提供一个“退出”按钮以便退出登录,点击“退出”按钮后通过controller跳转回到首页(client/index.jsp)。至此,用户端的登录、退出功能流程走完。
然后访问localhost/MavenSpringMVC/admin应该通过controller跳转至管理端登录页面(admin/login.jsp),输入用户名、密码,点击“登录”按钮,提交表单至后台进行验证登录(admin/login.do),验证失败通过controller跳转至错误展示页面(error.jsp),演出成功则通过controller跳转至(admin/index.jsp)并展示当前登录用户的登录状态,同时需要提供一个“退出”按钮以便退出登录,点击“退出”按钮后通过controller跳转至admin/index.jsp页面或者admin/login.jsp页面都行,假如跳转至admin/index.jsp页面,则同时需要在页面上提供一个“登录”按钮,点击该按钮后通过controller跳转至admin/login.jsp页面。
4,根据我们上面规划的项目结构及访问流程,我们首先需要来对项目进行配置
4.1 /MavenSpringMVC/src/main/webapp/WEB-INF/web.xml文件配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- 这里配置spring 的后台servlet -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定spring配置文件的路径 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- 拦截所有请求,可以修改 -->
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- filter 字符串过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <display-name></display-name>

</web-app>

4.2 /MavenSpringMVC/src/main/resources/applicationContext.xml文件配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  
       xmlns:mvc="http://www.springframework.org/schema/mvc"  
       xmlns:context="http://www.springframework.org/schema/context"  
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       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/mvc  
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 1,配扫描。对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
    <context:component-scan base-package="com" />

    <!-- 2,配注解。启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

    <mvc:annotation-driven />

    <!-- 视图解释类 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/pages/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 设置仅有下面路径(location)的资源可以直接访问(其他路径的资源都需要通过action访问) -->
    <mvc:resources location="/WEB-INF/js/" mapping="/js/**" />
    <mvc:resources location="/WEB-INF/css/" mapping="/css/**" />
    <mvc:resources location="/WEB-INF/images/" mapping="/images/**" />

</beans>

5,配置完成后,我们来开始写代码,首先写前端部分
5.1 用户端、管理端公用部分:
/MavenSpringMVC/src/main/webapp/WEB-INF/css/skin1/index.css:

@CHARSET "UTF-8";
.my-btn {
    height: 20px;
    background: #2196F3;
    display: inline-block;
    text-align: center;
    padding: 5px;
    cursor: pointer;
    color: gainsboro;
    font-weight: bold;
}

/MavenSpringMVC/src/main/webapp/WEB-INF/pages/error.jsp:

<%@page import="org.apache.naming.java.javaURLContextFactory"%>
<%@ page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <base href="<%=basePath%>">
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">   
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
    </head>
    <body>
        操作出错:<%=request.getAttribute("msg") %>
    </body>
</html>

5.2 用户端部分:
/MavenSpringMVC/src/main/webapp/WEB-INF/pages/client/index.jsp:

<%@page import="com.user.bean.User"%>
<%@page import="org.springframework.web.context.request.RequestScope"%>
<%@page import="org.apache.naming.java.javaURLContextFactory"%>
<%@page import="java.util.*"%>
<%@page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <base href="<%=basePath%>">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/public/JQuery/jquery-1.12.1.js"></script>
        <script type="text/javascript" src="js/project/client/index.js"></script>
        <link rel="stylesheet" type="text/css" href="css/skin1/index.css">
        <title>用户端首页</title>
    </head>
    <body>
        <p>用户端首页</p>
        <c:choose>
            <c:when test="${sessionScope.loginUser.userName != null}">
                ${sessionScope.loginUser.userName}你好!
                <a id="clientLogoutBtn" class="my-btn">退出</a>
            </c:when>
            <c:otherwise>
                <a id="toClientLoginBtn" class="my-btn">登录</a>
                <a id="toRegisterBtn" class="my-btn">注册</a>
            </c:otherwise>
        </c:choose>
</body>
</html>

/MavenSpringMVC/src/main/webapp/WEB-INF/js/project/client/index.js:

/**
 * 用户端首页js
 */

$(function() {
    $("#toClientLoginBtn").click(function(){
        window.location = "client.do";//跳转至client/login.jsp
    });

    $("#clientLogoutBtn").click(function(){
        window.location = "client/logout.do";//退出登录,跳转至client/index.jsp
    });
});

/MavenSpringMVC/src/main/webapp/WEB-INF/pages/client/login.jsp:

<%@page import="org.apache.naming.java.javaURLContextFactory"%>
<%@ page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <base href="<%=basePath%>">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>用户登录</title>
    </head>
    <body>
        <form action="client/login.do" method="post">
            用户名:<input type="text" name="userName" value="admin" /><br>
            密    码:<input type="password" name="password" value="123456"><br>
            <input type="submit" value="登录">    
            <input type="reset" value="重置" />
        </form>
    </body>
</html>

5.3 管理端部分:
/MavenSpringMVC/src/main/webapp/WEB-INF/pages/admin/index.jsp:

<%@page import="com.user.bean.User"%>
<%@page import="org.springframework.web.context.request.RequestScope"%>
<%@page import="org.apache.naming.java.javaURLContextFactory"%>
<%@page import="java.util.*"%>
<%@page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <base href="<%=basePath%>">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="js/public/JQuery/jquery-1.12.1.js"></script>
        <script type="text/javascript" src="js/project/admin/index.js"></script>
        <link rel="stylesheet" type="text/css" href="css/skin1/index.css">
        <title>管理员端首页</title>
    </head>
    <body>
        <p>管理员端首页</p>
        <c:choose>
            <c:when test="${sessionScope.loginUser.userName != null}">
                ${sessionScope.loginUser.userName}你好!
                <a id="toInfoEditBtn" class="my-btn">个人信息维护</a>
                <a id="adminLogoutBtn" class="my-btn">退出</a>
            </c:when>
            <c:otherwise>
                <a id="toAdminLoginBtn" class="my-btn">登录</a>
            </c:otherwise>
        </c:choose>
</body>
</html>

/MavenSpringMVC/src/main/webapp/WEB-INF/js/project/admin/index.js:

/**
 * 管理端首页js
 */

$(function() {
    $("#toAdminLoginBtn").click(function(){
        window.location = "admin";//退出登录,跳转至admin/login.jsp
    });

    $("#adminLogoutBtn").click(function(){
        window.location = "admin/logout.do";//退出登录,跳转至client/index.jsp
    });
});

/MavenSpringMVC/src/main/webapp/WEB-INF/pages/admin/login.jsp:

<%@page import="org.apache.naming.java.javaURLContextFactory"%>
<%@ page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <base href="<%=basePath%>">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>管理员登录</title>
    </head>
    <body>
        <p>管理员登录</p>
        <form action="admin/login.do" method="post">
            用户名:<input type="text" name="userName" value="admin" /><br>
            密    码:<input type="password" name="password" value="123456"><br>
            <input type="submit" value="登录">    
            <input type="reset" value="重置" />
        </form>
    </body>
</html>

6,然后开始写后台代码
6.1 新建一个User类:
/MavenSpringMVC/src/main/java/com/user/bean/User.java:

package com.user.bean;

public class User {

    private String id;
    private String userName;
    private String password;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

6.2 新建一个作为项目主入口的、控制全局跳转的controller:
/MavenSpringMVC/src/main/java/com/pub/controller/MainController.java:

package com.pub.controller;

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

@Controller
public class MainController {

    /**
     * 访问客户端主页,默认进入client/index.jsp
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("/")
    public ModelAndView toClientIndex() throws Exception {
        return new ModelAndView("client/index");// 跳转至pages/client下的index.jsp
    }

    /**
     * 访问管理员端主页,默认进入admin/login.jsp
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("admin")
    public ModelAndView toAdminLogin() throws Exception {
        return new ModelAndView("admin/login");// 跳转至pages/admin/login.jsp
    }

    /**
     * 访问客户端登录界面,进入client/login.jsp
     * 
     * @return
     * @throws Exception
     */
    @RequestMapping("client.do")
    public ModelAndView toClientLogin() throws Exception {
        return new ModelAndView("client/login");// 跳转至pages/client/login.jsp
    }

}

6.3 新建一个专门用于处理与User相关的逻辑的controller

package com.user.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

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

import com.user.bean.User;

@Controller
public class UserController {

    Map<String, String> model = new HashMap<String, String>();

    /**
     * 客户端登录验证,登录成功后跳转至client/index.jsp
     * 
     * @param user
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("client/login.do")
    public ModelAndView clientLogin(User user, HttpSession session)
            throws Exception {
        if (user == null || user.getUserName() == null
                || user.getPassword() == null || user.getUserName().equals("")
                || user.getPassword().equals("")) {
            model.put("msg", "用户名或者密码为空");
            return new ModelAndView("error", model);
        } else if (!user.getUserName().equals("admin")
                || !user.getPassword().equals("123456")) {
            model.put("msg", "用户名或密码错误!");
            return new ModelAndView("error", model);
        } else {
            model.put("msg", "登录成功");
            session.setAttribute("loginUser", user);// 这里注意要把userId也设置到user中,以方便在前台取用
            return new ModelAndView("client/index", model);// 登录成功后跳转至client/index.jsp
        }
    }

    /**
     * 客户端退出登录,退出后跳转至client/index.jsp
     * 
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("client/logout.do")
    public ModelAndView clientLogout(HttpSession session) throws Exception {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            session.removeAttribute("loginUser");
        }
        model.put("msg", "已退出登录!");
        return new ModelAndView("client/index", model);// 退出后跳转至client/index.jsp
    }

    /**
     * 管理员端登录验证,登录成功后跳转至admin/index.jsp
     * 
     * @param user
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("admin/login.do")
    public ModelAndView adminLogin(User user, HttpSession session)
            throws Exception {
        if (user == null || user.getUserName() == null
                || user.getPassword() == null || user.getUserName().equals("")
                || user.getPassword().equals("")) {
            model.put("msg", "用户名或者密码为空");
            return new ModelAndView("error", model);
        } else if (!user.getUserName().equals("admin")
                || !user.getPassword().equals("123456")) {
            model.put("msg", "用户名或密码错误!");
            return new ModelAndView("error", model);
        } else {
            model.put("msg", "登录成功");
            session.setAttribute("loginUser", user);// 这里注意要把userId也设置到user中,以方便在前台取用
            return new ModelAndView("admin/index", model);
        }
    }

    /**
     * 管理端退出登录,退出后跳转至admin/index.jsp
     * 
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("admin/logout.do")
    public ModelAndView adminLogout(HttpSession session) throws Exception {
        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser != null) {
            session.removeAttribute("loginUser");
        }
        model.put("msg", "已退出登录!");
        return new ModelAndView("admin/index", model);// 退出后跳转至client/index.jsp
    }

}

7,代码编写完毕,部署到tomcat,访问测试一下,看看效果:
7.1 用户端访问
首先访问localhost/MavenSpringMVC:
这里写图片描述
点击”登录“按钮:
这里写图片描述
输入用户名、密码后点击”登录“:
这里写图片描述
点击”退出“按钮:
这里写图片描述
点击”登录“按钮:
这里写图片描述
OK,用户端测试完毕!
7.2 管理端访问
首先访问localhost/MavenSpringMVC/admin:
这里写图片描述
输入用户名、密码后点”登录“:
这里写图片描述
点击”退出“按钮:
这里写图片描述
点击”登录“按钮:
这里写图片描述
OK,管理端也测试完毕!
8,关于跳转的配置及映射关系:
8.1 首先以localhost/MavenSpringMVC这个URL的访问为例说下:
这里写图片描述
localhost/MavenSpringMVC这个路径会映射到哪个controller呢?这得去*Controller.java里去找,匹配@RequestMapping后面配置的路径名,这个路径当然很容易就能看出来是匹配一个”/”,即匹配到toClientIndex这个controller方法,这个方法执行完毕之后返回一个字符串”client/index”,再结合applicationContext.xml里的配置,得出实际要访问到的页面路径是prefix+”client/index”+suffix=”/WEB-INF/pages/client/index.jsp”。
8.2 再以用户端登录按钮的跳转来说下:
这里写图片描述
在访问localhost/MavenSpringMVC后进入到client/index.jsp页面,在页面上点击“登录”按钮,该按钮绑定的事件是window.location = “client.do”,即访问client.do这个controller,在后台*Controller.java里去匹配,会发现匹配到MainController的toClientLogin这个方法,该方法返回一个字符串”client/login”,即对应为”/WEB-INF/pages/client/login.jsp”页面,于是跳转至该页面。

;