一、导入相jar包
主要包括spring相关jar包和fastjson jar包,具体步骤略。
二、配置相关文件
1.配置web.xml文件
<?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>SpringProject</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Spring MVC配置文件的位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 表示容器在启动时立即加载dispatcherServlet --> <load-on-startup>1</load-on-startup> </servlet> <!-- 让Spring MVC控制器拦截前端所有请求 --> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
2.配置Spring MVC配置文件springmvc.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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <context:component-scan base-package="com.springmvc.controller" /> <!-- 解决访问html资源404,非常重要 --> <mvc:default-servlet-handler/> <mvc:annotation-driven> </mvc:annotation-driven> <bean name="/hello2" class="com.springmvc.controller.HelloController2"></bean> </beans>
三、编写请求控制类
通过注解配置映射请求的URL和返回内容类型等。
package com.springmvc.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;import com.alibaba.fastjson.JSON;import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; @Controller public class HelloController { @RequestMapping(value="/hello",produces = "application/json; charset=utf-8") @ResponseBody public String hello() { // TODO Auto-generated method stub Map<String, String> map = new HashMap<String, String>(); map.put("key1", "键值1"); System.out.println(JSON.toJSONString(map)); return JSON.toJSONString(map); } }
注:如果访问html页面报错404,可参考文章:spring mvc访问html页面404报错解决