Spring MVC 体系概述
配置 DispatcherServlet
<?xml version="1.0" encoding="UTF-8"?>
<web-app .....>
<!--加载 Spring WebApplicationContext: Service 层和 Dao 层的配置文件加载到 Spring 容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--启动 Spring 容器监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--以下部分为 DispatcherServlet 的配置-->
<!--声明 DispatcherServlet-->
<servlet>
<servlet-name>assad</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置 DispatcherServlet 的匹配 URL 模式-->
<servlet-mapping>
<servlet-name>assad</servlet-name>
<url-pattern>/</url-pattern> <!--匹配任何url请求,像 *.html 匹配 html 页面请求-->
</servlet-mapping>
</web-app>
namespace | DispatcherServlet 的命名空间,默认为 <servlet-name>-servlet(即:WEB-INF/<servlet-name>-servlet.xml ), |
contextConifgLocation | 如果 DispatcherServlet 对应的上下文配置文件有多个,可以用该属性指定这些配置文件的路径,如: |
publishContext | 指定 DispatcherServlet 是否将 WevApplicationContext 分布到 ServletContext 的属性列表中(通过 DispatcherServlet#getServletContextAttributeName() 方法可以从ServletContext 中获取 WebApplicationContex 的实例), |
publishEvents | 指定 DispatcherServlet 处理完一个请求后,是否需要向容器发布一个 ServletRequesthandledEvent 事件, |
一个简单的示例
<?xml version="1.0" encoding="UTF-8"?>
<web-app ...>
<!--加载 Spring WebApplicationContext: Service 层和 Dao 层的配置文件加载到 Spring 容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--启动 Spring 容器监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--声明 DispatcherServlet-->
<servlet>
<servlet-name>assad</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!--配置 DispatcherServlet 的匹配 URL 模式-->
<servlet-mapping>
<servlet-name>assad</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置请求编码过滤器,解决HttpRequest传输时中文乱码的问题-->
<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>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
package site.assad.web;
@RestController //标记为一个 Spring MVC 的Controller
public class LoginController {
@Autowired
private UserService userService;
//响应 index.html 请求,并将其转发到 login/login 逻辑视图
@RequestMapping(value="/login")
public String loginPage(){
return "login/login";
}
//响应 loginCheck.html 请求
@RequestMapping(value="/loginCheck",method = RequestMethod.POST)
public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand ) throws UnsupportedEncodingException {
//验证登陆用户密码
boolean isValidUser = userService.checkUser(loginCommand.getUserName(),loginCommand.getPassword());
//验证结果处理逻辑
if(!isValidUser){
//验证失败,返回 login/login 物理视图,并携带错误信息
return new ModelAndView("login/login","error", new String("用户名或密码错误".getBytes(),"UTF-8"));
}else{
User user = userService.findUserByName(loginCommand.getUserName());
user.setLastIp(request.getLocalAddr());
user.setLastVisit(new Date());
userService.loginSuccess(user); //执行验证成功的业务操作
request.getSession().setAttribute("user",user); //设置 session
//验证成功,转发到 login/login_success 逻辑视图
return new ModelAndView("login/login_success");
}
}
}
3)编写 View 视图文件
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<p>
<c:if test="${!empty error}">
<c:out value="${error}" />
</c:if>
</p>
<form action="<c:url value="/loginCheck" />" method="post">
<label>用户名</label><input type="text" name="userName" /><br />
<label>密码</label><input type="password" name="password"/><br />
<input type="submit" value="登陆" />
<input type="reset" value="重置信息" />
</form>
</body>
</html>
login/login_success.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login Success Page</title>
</head>
<body>
<h1>登陆成功!${user.name}, 您当前的积分为 ${user.credits} </h1>
</body>
</html>
4)编写 Spring-mvc 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<!--自动注入 site.assad.web 包的 bean-->
<context:component-scan base-package="site.assad.web" />
<!--配置视图解析器,映射逻辑视图名的解析-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp" />
</beans>
group 'site.assad'
version '1.0'
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'org.akhikhl.gretty'
sourceCompatibility = 1.8
//导入 gretty 调试插件
buildscript{
repositories{
jcenter()
}
dependencies{
classpath 'org.akhikhl.gretty:gretty:1.2.4'
}
}
repositories {
mavenCentral()
}
ext{
servlet_api_version = '3.0-alpha-1'
jstl_version = '1.2'
jsp_api_version = '2.0'
spring_version = '4.3.11.RELEASE'
log4j_core_version = '2.9.0'
log4j_api_version = '2.9.0'
junit_version = '4.12'
commons_dbcp_version = '1.4'
mysql_connector_java_version = '5.1.44'
hibernate_version = '5.2.12.Final'
}
dependencies {
//log4j 依赖
testCompile "org.apache.logging.log4j:log4j-core:${log4j_core_version}"
testCompile "org.apache.logging.log4j:log4j-api:${log4j_api_version}"
compile "org.apache.logging.log4j:log4j-core:${log4j_core_version}"
compile "org.apache.logging.log4j:log4j-api:${log4j_api_version}"
//servlet 依赖
compile "javax.servlet:servlet-api:${servlet_api_version}"
compile "javax.servlet:jstl:${jstl_version}"
compile "javax.servlet.jsp:jsp-api:${jsp_api_version}"
//spring core 依赖
compile "org.springframework:spring-beans:${spring_version}"
compile "org.springframework:spring-core:${spring_version}"
compile "org.springframework:spring-context:${spring_version}"
compile "org.springframework:spring-context-support:${spring_version}"
//spring dao 依赖
compile "org.springframework:spring-jdbc:${spring_version}"
compile "org.springframework:spring-tx:${spring_version}"
//数据源和数据库驱动:使用 Mysql,DBCP数据源
compile "commons-dbcp:commons-dbcp:${commons_dbcp_version}"
compile "mysql:mysql-connector-java:${mysql_connector_java_version}"
//spring test 依赖,使用 Junit
compile "org.springframework:spring-test:${spring_version}"
testCompile "junit:junit:${junit_version}"
//spring mvc 框架
compile "org.springframework:spring-webmvc:${spring_version}"
}
//设置 gretty 参数
gretty {
port = 8080
servletContainer = 'tomcat8'
contextPath = "/"
}