(一)配置Java后台
这里为了简单,我直接用SpringMvc配置后台(这个配置网上一搜一大把)。
1.导包
接下来向lib中,导入如下图所示的jar。这里有几个Jar除了commons-logging我没标记。剩下三个都是用来返回Json格式的数据。
- jackson-core.jar下载链接
- jackson-databind.jar下载链接
- jackson-annotations.jar下载链接
2.配置web.xml配置文件
web.xml文件路径:/WebContent/WEB-INF/web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MineTest</display-name>
<!-- 配置SpringMvc前端控制器 -->
<servlet>
<servlet-name>springMvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring_mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 设置欢迎页面 -->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
3.创建并配置spring_mvc.xml配置文件
在/src目录下创建spring_mvc.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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 设置要扫描的包 -->
<context:component-scan base-package="com.lyan.web.controller"/>
<!-- 这里用于与JackJson返回Json数据 -->
<mvc:annotation-driven/>
</beans>
4.创建Controller用于接收请求
创建Controller要将他放在指定的扫描包中(对应着spring_mvc.xml中的【context:component-scan base-package=”com.lyan.web.controller”】)。
@Controller
public class TestController {
@ResponseBody
@RequestMapping(value = "/first",method = RequestMethod.GET)
public Person firstRequest(){
System.out.println(TimeUtils.getYearDate(System.currentTimeMillis()));
Person person = new Person();
person.setName("美女");
person.setAge(20);
person.setSex('女');
return person;
}
}
5.运行项目查看结果
运行项目,在浏览器中的请求地址后加上“first.do”,然后回车。测试一下get请求的结果是否显示到界面中。请求成功的结果如下图所示:
到这里后台的准备工作基本完成!接下来将使用。原生JS实现Ajax异步请求