Spring:SpringMVC一例

目录结构

在这里插入图片描述

web.xml

<web-app 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_3_0.xsd"
  version="3.0">

  <!-- ContextLoaderListener实现了ServletContextListener这个接口,在启动web容器时会执行,完成spring的启动和初始化。 
    若配置了contextConfigLocation上下文参数则按照该参数指定的路径和文件名去读取spring配置文件, 否则默认会去读/WEB-INF/applicationContext.xml -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 此参数指定spring初始化时读取的配置文件,如果要读取多个xml文件,可以写在一起并一“,”号分隔。也可以采用如applicationContext-*.xml通配符的格式。 
    classpath:是类路径,此处可替换为/WEB-INF/classes/ -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>

  <!-- DispatcherServlet是SpringMVC的总调度类,我们定义了一个名为md5的servlet并将url为/的请求映射到这个servlet,这样在请求到达时就会执行此类。 
    若配置了contextConfigLocation sevlet参数则按照该参数指定的路径和文件名去读取springMVC的核心配置文件, 否则默认会去读/WEB-INF/servlet名称-servlet.xml 
    load-on-startup定义了此servlet启动优先级,1表示第一个启动,servlet一般在web容器启动时初始化 -->
  <servlet>
    <servlet-name>md5</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/servlet/md5-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>md5</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

SpringMVC核心配置文件:md5-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 
             http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd             
             http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

  <!--激活@Controller模式 -->
  <mvc:annotation-driven />
  <!--对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 -->
  <context:component-scan
    base-package="com.lwt.bigtools.controller" />

  <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
  <!-- 这个bean用于将Controller类方法的返回值映射为实际的文件,此处为加前缀后缀: /jsp/md5/***.jsp -->
  <bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
      <value>/jsp/md5/</value>
    </property>
    <property name="suffix">
      <value>.jsp</value>
    </property>
  </bean>

  <!-- 此处使得DispatcherServlet将静态资源文件交给web容器默认处理,如js,css文件等 -->
  <mvc:default-servlet-handler />
  <!-- <mvc:resources location="/skin" mapping="/resources/**" cache-period="10000" 
    /> -->
</beans>

Controller类

为一普通POJO类

@Controller
public class Md5Query {
    // url为/md5的请求会被DispatcherServlet发送到此方法执行,其中参数Md5Form携带请求提交的参数信息。最终
    @RequestMapping(value = "/md5")
    public String query(Md5Form md5Form, Model model) {
        String source = md5Form.getSource();
        String res = "";
        if (!StringUtil.isEmpty(source)) {
            res = Md5Util.query(source); // 返回字符串source的MD5字符串表示形式
        }
        model.addAttribute("source", source);
        model.addAttribute("result", res);
        return "md5_query"; // 最终视图会被viewResolver映射到 /jsp/md5/md5_query.jsp这个文件返回给浏览器
    }

    // 这是个ajax请求最终到达的方法
    @ResponseBody
    @RequestMapping(value = "/md5ajax")
    public Map<String, Object> md5Ajax(String source) {
        Map<String, Object> modelMap = new HashMap<String, Object>();
        modelMap.put("res", Md5Util.query(source));
        return modelMap;
    }
}

/jsp/md5/md5_query.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%> <%@ taglib prefix="c"
uri="http://java.sun.com/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base
	href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>md5查询</title>

<style type="text/css">
input[type="text"] {
	/*      float: left; */
	
}
</style>
<link href="<c:url value='skin/css/common.css'/>" rel="stylesheet"
	type="text/css" />
<script src="skin/js/jquery-1.11.3.min.js"></script>
<script src="skin/js/ajaxsubmit.js"></script>

<script type="text/javascript">
    $(function() {
        $("form").submit(function() {
            $.post("md5ajax", {
                "source" : $("form input[name='source']").val()
            }, function(data, status) {
                $("#res").html(data.res);
            });
            return false;
        });
    });
</script>
</head>

<body>
	<form action="" method="post">
		<input type="text" name="source"> <input type="submit"
			value="查询">
	</form>

	<div>
		<p id="res"></p>
	</div>
</body>
</html>

相关依赖:pom.xml

<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.lwt</groupId>
  <artifactId>bigtools</artifactId>
  <packaging>war</packaging>
  <version>0.0.1</version>
  <name>bigtools Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <!-- 定义相关版本号 -->
  <properties>
    <java-version>1.7</java-version>
    <org.springframework-version>3.1.4.RELEASE</org.springframework-version>
    <jackson.version>2.6.3</jackson.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <!-- 定义依赖 -->
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${org.springframework-version}</version>
    </dependency>

    <!-- 提供对ajax请求json数据形式的返回,若没有则ajax请求会返回406(Not Acceptable)错误 -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>${jackson.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>${java-version}</source>
          <target>${java-version}</target>
          <encoding>UTF-8</encoding>
        </configuration>
      </plugin>
    </plugins>
    <finalName>bigtools</finalName>
  </build>
</project>
posted @ 2019-01-16 10:48  xuejianbest  阅读(175)  评论(0编辑  收藏  举报