纯java config配置Spring MVC实例
1、首先创建一个Maven工程,项目结构如下:
pom.xml添加Spring和servlet依赖,配置如下
<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.smart.springmvc</groupId>
<artifactId>JavaSpringMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>JavaSpringMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>4.0.6.RELEASE</springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> </dependencies> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>JavaSpringMVC</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<finalName>JavaSpringMVC</finalName>
</build>
</project>
首先要注意这里maven-war-plugin 插件的声明。正如我们将完全删除web.xml ,我们需要配置这个插件,以避免Maven构建war包失败。第二个变化是加入了JSP/Servlet/Jstl 的依赖关系,这些我们可能需要,因为我们将要使用 servlet API和JSTL视图在我们的代码中。在一般情况下,容器已经包含这些库,从而在pom.xml中为他们提供了,我们可以设置作用范围。
2、添加控制器
UserController.class
package com.smart.springmvc.controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap; @Controller
public class UserController { @RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("user", "command", new User());
} @RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
System.out.println(user.getSex());
System.out.println(user.getName());
model.addAttribute("phone", user.getPhone());
model.addAttribute("email", user.getEmail());
model.addAttribute("password", user.getPassword());
model.addAttribute("name", user.getName());
model.addAttribute("repassword", user.getRepassword());
model.addAttribute("sex", user.getSex()); return "UserList";
}
}
在类名@Controller注解声明这个类的Spring bean 以及 @RequestMapping注解声明了这个类是默认处理程序键入“/”的所有请求。第一种方法没有声明因此任何映射,它将继承映射的映射声明是在类级别上,默认处理GET请求。方法二(由于额外的映射声明使用value属性)形式 /user 将再次请求。属性方法说哪种类型的HTTP请求这种方法可以服务。
方法说哪种类型的HTTP请求这种方法可以服务。 ModelMap是一个Map实现,在这里作为替代[request.getAttribute()/request.setAttribute()] 设定值作为请求属性。请注意,我们从这个方法返回“UserList”字符串。此字符串将后缀和前缀后缀,在视图解析器定义的前缀,形成真正的视图文件名。
3、添加视图
user.jsp
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>register</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/jquery.validate.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet"> <script type="text/javascript">
$().ready(function() {
// 在键盘按下并释放及提交后验证提交表单
$("#vForm").validate({ rules: {
phone:{required:true,isMobile:true},
email:{required:true,email:true}, password: {
required: true,
minlength: 5,
maxlength: 12
},
repassword: {
required: true,
minlength: 5,
maxlength: 12,
equalTo: "#password"
},
name: {required: true,maxlength:32},
}, messages: {
phone: {
required: "请输入手机号<br/>",
minlength: "请输入11位的有效手机号码<br/>"
},
email: {
required: "请输入邮箱<br/>",
minlength: "请输入正确的邮箱<br/>"
},
password: {
required: "请输入密码<br/>",
minlength: "密码长度不能小于 5 个字母<br/>",
maxlength: "密码长度不能大于 12 个字母<br/>"
},
repassword: {
required: "请再次输入密码<br/>",
minlength: "密码长度不能小于 5 个字母<br/>",
maxlength: "密码长度不能大于 12 个字母<br/>",
equalTo: "两次密码输入不一致<br/>"
},
name: {
required: "请输入用户名<br/>",
minlength: "用户名长度不得大于32个字符<br/>"
},
}
});
});
</script> <style>
.error{
color:red;
}
</style> </head>
<body>
<div class="container" style="margin-top: 30px">
<div class="well" style="margin-left: 10%;margin-right: 10%">
<div class="row" style="margin-top: 35px">
<form class="form-horizontal" role="form" id="vForm" method="POST" action="addUser"> <div class="form-group">
<label for="phone" class="col-sm-4 control-label">手 机</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="phone" name="phone" placeholder="请输入手机号">
</div>
</div> <div class="form-group">
<label for="email" class="col-sm-4 control-label">邮 箱</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱">
</div>
</div> <div class="form-group">
<label for="passowrd" class="col-sm-4 control-label">密 码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="password" name="password" placeholder="请输入密码">
</div>
</div>
<div class="form-group ">
<label for="name" class="col-sm-4 control-label">姓 名</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
</div>
</div>
<div class="form-group">
<label for="repassowrd" class="col-sm-4 control-label">重复密码</label>
<div class="col-sm-4">
<input type="password" class="form-control" id="repassword" name="repassword" placeholder="请再次输入密码">
</div>
</div> <div class="form-group">
<label for="sex" class="col-sm-4 control-label">性 别</label>
<div>
<label class="radio-inline">
<input type="radio" name="sex" id="boy" value="男" checked> 男
</label>
<label class="radio-inline">
<input type="radio" name="sex" id="girl" value="女"> 女
</label>
</div>
</div> <div class="form-group">
<div class="col-sm-4 col-sm-offset-3 control-label ">
<button type="submit" class="btn btn-info">提交</button>
<a href="Login.jsp" class="btn btn-info">登录</a>
</div>
</div> </form>
</div>
</div>
</div> </body>
</html>
User.jsp
UserList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>
<!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=UTF-8">
<title>用户列表</title>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jqPaginator.min.js"></script>
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container" style="margin-top: 30px">
<div class="well" style="margin-left: 10%;margin-right: 10%">
<div class="row" style="margin-top: 35px">
<table class="table table-striped" >
<caption>用户列表</caption>
<thead>
<tr>
<th>电话</th>
<th>邮箱</th>
<th>密码</th>
<th>重复密码</th>
<th>名字</th>
<th>性别</th>
</tr>
</thead>
<tbody> <tr>
<td>${phone}</td>
<td>${email}</td>
<td>${password}</td>
<td>${repassword}</td>
<td>${name}</td>
<td>${sex}</td> </tr> </tbody>
</table> </body>
</html>
UserList.jsp
4、添加配置类
JavaSpringCon.class
package com.smart.springmvc.configuration; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView; @Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.smart.springmvc")
public class JavaSpringCon { @Bean(name="HelloWorld")
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp"); return viewResolver;
} }
这种构造类可以被看作是一个替代 spring-servlet.xml,因为它包含了所有必需的组件的扫描和视图解析器的信息。
@Configuration指明该类包含注解为@Bean 生产 bean管理是由Spring容器的一个或多个bean方法。 以上配置类对应等同于以下XML:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-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"> <context:component-scan base-package="com.yiibai.springmvc" /> <mvc:annotation-driven /> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean> </beans>
@EnableWebMvc 等同于 mvc:annotation-driven 在XML中. 它能够为使用@RequestMapping向特定的方法传入的请求映射@Controller-annotated 类。
@ComponentScan 等同于 context:component-scan base-package="..." 提供 spring 在哪里寻找 管理 beans/classes.
5、添加初始化类
JavaSpringIn.class
package com.smart.springmvc.configuration; import javax.servlet.Filter; import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class JavaSpringIn extends AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { JavaSpringCon.class };
} @Override
protected Class<?>[] getServletConfigClasses() {
return null;
} @Override
protected String[] getServletMappings() {
return new String[] { "/" };
} @Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[] {characterEncodingFilter};
} }
JavaSpringIn.class
添加一个初始化类实现 WebApplicationInitializer 在src/main/java 中使用如下图所示指定包(在这种情况下,作为替代在 web.xml 中定义的任何 Spring 配置)。在Servlet 3.0的容器启动时,这个类将被加载并初始化,并在启动由servlet容器调用方法。
有一点要记住,像WebApplicationInitializer,Spring 是基于Java 的配置API依赖于 Servlet3.0容器。确保你没有使用Servlet声明任何小于3.0。对于我们的情况,我们将从应用程序中删除 web.xml 文件。
现在构建war (无论是作为Eclipse中提到的最后一个教程)或通过Maven的命令行(mvn clean install)。部署war 到Servlet3.0容器。由于我在这里使用Tomcat,我就干脆把这个 war 文件放到 Tomcat 的 webapps 文件夹,然后在 tomcat 的bin 目录里面点击 start.bat 运行。
或者 右键工程 =>Run As => Maven install 完成后,再次 右键工程 =>Run As => Maven build,弹出选择:
Goals:org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run-war
点击运行访问http://localhost:8080/JavaSpringMVC/user 即可出现如下,我因为css引用问题还没有解决所有这么丑。
纯java config配置Spring MVC实例的更多相关文章
- Java方式配置Spring MVC
概述 使用Java方式配置Spring MVC,以及回顾一下Spring MVC的各种用法. Spring MVC简述 关于Spring MVC的介绍网上有很多,这里就不再赘述了,只是要说一下,Spr ...
- 如何用Java类配置Spring MVC(不通过web.xml和XML方式)
DispatcherServlet是Spring MVC的核心,按照传统方式, 需要把它配置到web.xml中. 我个人比较不喜欢XML配置方式, XML看起来太累, 冗长繁琐. 还好借助于Servl ...
- 基于纯Java代码的Spring容器和Web容器零配置的思考和实现(3) - 使用配置
经过<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(1) - 数据源与事务管理>和<基于纯Java代码的Spring容器和Web容器零配置的思考和实现(2) - ...
- Spring 4 官方文档学习(十一)Web MVC 框架之配置Spring MVC
内容列表: 启用MVC Java config 或 MVC XML namespace 修改已提供的配置 类型转换和格式化 校验 拦截器 内容协商 View Controllers View Reso ...
- maven配置spring mvc+hibernate+spring框架
作为一名刚出茅草屋的新手小白写的框架,仅适合新手小白借鉴,大神勿喷,谢谢...... 前天刚知道spring mvc这个框架现在也很流行,决定用它代替struts2来写我的毕业设计. ...作为一名新 ...
- java企业架构 spring mvc +mybatis + KafKa+Flume+Zookeeper
声明:该框架面向企业,是大型互联网分布式企业架构,后期会介绍linux上部署高可用集群项目. 项目基础功能截图(自提供了最小部分) 平台简介 Jeesz是一个分布式的框架,提供 ...
- 第63节:Java中的Spring MVC简介笔记
前言 感谢! 承蒙关照~ Java中的Spring MVC简介笔记 MVC简介 Spring MVC 基本概念 Spring MVC 项目搭建 maven 使用Spring MVC进行开发 实现数据绑 ...
- 如何在Web项目中配置Spring MVC
要使用Spring MVC需要在Web项目配置文件中web.xml中配置Spring MVC的前端控制器DispatchServlet <servlet> <servlet-name ...
- [Java] Maven 建立 Spring MVC 工程
GIT: https://github.com/yangyxd/Maven.SpringMVC.Web 1. 建立 WebApp 工程 下一步: 下一步: 选择 maven-archetype-web ...
随机推荐
- eclipse从svn检出项目
在eclipse的project explorer 右键->import->svn->从svn检出项目,然后填写资源库的位置,完成,然后一直next. 直到项目检出完成后,选择项目, ...
- mysql 存储引擎 InnoDB 与 MyISAM 的区别和选择
http://www.blogjava.net/jiangshachina/archive/2009/05/31/279288.html 酷壳 - MySQL: InnoDB 还是 MyISA ...
- Jenkins Robot framework 持续集成环境搭建
为什么我们要引入RF?其实最初我们引入RF是为了能够快速的开展自动化验收测试,为敏捷保驾护航.这其中有个重要的工具Jenkins,同时也是应群里朋友们的要求,这次就来介绍一下RF如何快速便捷的结合Je ...
- Oracle 索引 简单介绍
1 索引的创建语法: CREATE UNIUQE | BITMAP INDEX <schema>.<index_name> ON <schema>.&l ...
- FFmpeg编码详细流程
FFmpeg在编码一个视频的时候的函数调用流程.为了保证结构清晰,其中仅列出了最关键的函数,剔除了其它不是特别重要的函数. 函数背景色 函数在图中以方框的形式表现出来.不同的背景色标志了该函数不同的作 ...
- 搭建React Native开发环境
搭建React Native开发环境 本文档是Mac下搭建的环境,针对的目标平台不同,以及开发 iOS 和 Android 的不同,环境搭建也有差异. Github地址:https://github. ...
- The threads in the thread pool will process the requests on the connections concurrently.
https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html Most of the executor implem ...
- Linux环境编程之同步(三):读写锁
概述 相互排斥锁把试图进入我们称之为临界区的全部其它线程都堵塞住.该临界区通常涉及对由这些线程共享一个或多个数据的訪问或更新.读写锁在获取读写锁用于读某个数据和获取读写锁用于写直接作差别. 读写锁的分 ...
- appium():PageObject&PageFactory
Appium Java client has facilities which components to Page Object design pattern and Selenium PageFa ...
- 【Advanced Windows Phone Programming】在windows phone 8中解码mp3 和编码pcm
转眼间不做wp开发,投身于php事业已然一年了,转身看到8.1的发布,俨然一片欣欣向荣的景象,但是开发社区却没比一年前有过多大的提高,这并不是一个好现象,遂在git上开源了之前音频处理库,希望能对社区 ...