1. 程式人生 > >純java config配置Spring MVC實例

純java config配置Spring MVC實例

enable lang version ive org 表單 級別 tro group

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">手&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;機</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">郵&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</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">密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;碼</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">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</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">性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;別</label>
    <div>   
      <label class="radio-inline">
        &nbsp;&nbsp;&nbsp;<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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <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;
    }

}
View Code

這種構造類可以被看作是一個替代 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容器調用方法。

6、:構建和部署應用程序

有一點要記住,像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實例