纯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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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>
UserList.jsp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ 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>
4、添加配置类
JavaSpringCon.class
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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}; } }
添加一个初始化类实现 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引用问题还没有解决所有这么丑。