SpringMVC小示例

***因为在内网环境下,依赖的jar不能从网上直接下载,所以没有采用maven,此博客只为记录Spring+jsp所依赖的最小jar包集合。***

一、配置web.xml,主要作用
1.定义了一个servlet拦截器,以及Mapping规则
2.引入spring-context配置文件
3.添加log4j配置文件
具体文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<display-name>SpringTest</display-name>
	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
		<async-supported>true</async-supported>
	</servlet>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/resources/log4j/log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>


二、DispatcherServlet Context配置文件,作用
1.激活注解配置功能
2.配置资源文件路径
3.配置视图层技术
4.引入具体组件配置文档
具体文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven>

	</annotation-driven>

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources/ directory -->
	<resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
	<!-- Imports user-defined @Controller beans that process client requests -->
	<beans:import resource="controllers.xml" />


	
</beans:beans>


三、组件配置文档,主要作用
1.配置默认页面路径
2.配置组件扫描路径
具体文件
<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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">

	<!-- Maps '/' requests to the 'home' view -->
	<mvc:view-controller path="/" view-name="views/hello.jsp"/>
	
	<context:component-scan base-package="test.springmvc"/>
	 
</beans>


四、controller代码
/**
 * 
 */
package test.springmvc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/mvc")
public class MCVController {
	private static final Log logger = LogFactory.getLog(MCVController.class);
	@RequestMapping("/hello")
	public String hello(){
		logger.info("start to maping request hello");
        return "hello";
    }
	
	@RequestMapping(value = "/test",method =RequestMethod.GET) 
	public @ResponseBody String test(){
        return "abc";
    }
	
	@RequestMapping(value = "/test2",method =RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) 
	public @ResponseBody  AbcTest test2(){
		AbcTest test = new AbcTest();
		test.setAge("20");
		test.setName("me");
        return test;
    }
}



jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'hello.jsp' starting page</title>
  
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <div style = "width: 200px;height: 100px;color: red">hello</div>
   <button id='buttontest' style = "width: 50px;height: 50px;color: blue"></button>
   <div>
        <label>test:</label>
         <span id="test"></span>
   </div>
   <div>
        <label>test2:</label>
        <span id="test2"></span>
   </div>
  </body>
</html>

<script src="resources/js/jquery-2.0.3.js"></script>
<script type="text/javascript">
$('#buttontest').click(function() {
	$.ajax({
        type: "GET",
        url: "mvc/test",
        /* headers:{
            Accept: "text/plain"
        }, */
        success: function(msg){
          console.log( "Data Saved: " + msg );
          $("#test").text(msg);
        },
        error:function(e){
            alert(e)
        }
     });
 
 $.ajax({
        type: "GET",
        url: "mvc/test2",
        success: function(msg){
          console.log( "Data Saved: " + msg );
          $("#test2").text("age:"+msg.age+",name"+msg.name);
        },
        error:function(e){
            alert(e)
        }
     });
})

</script>


最终的工程目录:


工程代码可参考附件

猜你喜欢

转载自fengyilin.iteye.com/blog/2338404