最基本springMVC,响应页面请求

        前几天整个最基本的MVC配置都弄了小半天,基础仍是很弱,仍是花时间整理一下。javascript

        逻辑:页面经过一个点击事件访问后台接口,后台返回一个数据给jsp,jsp弹出便可。css

        1.首先是在pom.xml中导入须要的依赖,spring的几个基础包加一个servlet和一个fastjson包html

        

 1     <dependency>
 2       <groupId>junit</groupId>
 3       <artifactId>junit</artifactId>
 4       <version>4.12</version>
 5       <scope>test</scope>
 6     </dependency>
 7 
 8     <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
 9     <dependency>
10       <groupId>org.springframework</groupId>
11       <artifactId>spring-core</artifactId>
12       <version>5.0.8.RELEASE</version>
13     </dependency>
14     <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
15     <dependency>
16       <groupId>org.springframework</groupId>
17       <artifactId>spring-context</artifactId>
18       <version>5.0.8.RELEASE</version>
19     </dependency>
20     <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
21     <dependency>
22       <groupId>org.springframework</groupId>
23       <artifactId>spring-webmvc</artifactId>
24       <version>5.0.8.RELEASE</version>
25     </dependency>
26     <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
27     <dependency>
28       <groupId>javax.servlet</groupId>
29       <artifactId>javax.servlet-api</artifactId>
30       <version>3.1.0</version>
31       <scope>provided</scope>
32     </dependency>
33 
34     <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
35     <dependency>
36       <groupId>com.alibaba</groupId>
37       <artifactId>fastjson</artifactId>
38       <version>1.2.47</version>
39     </dependency>

2.配置文件spring-context.xml,demo比较简单,直接用一个xml,不分什么spring-MVC.xml了java

  

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context-4.3.xsd
10        http://www.springframework.org/schema/mvc
11        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
12 
13 
14     <!-- 表示支持Spring的注解-->
15     <context:annotation-config/>
16     <!-- 表示支持MVC的注解-->
17     <mvc:annotation-driven/>
18     <!-- 表示放行静态资源-->
19     <mvc:default-servlet-handler/>
20     <context:component-scan base-package="cn.test.controller"/>
21 
22     <!-- jsp页面解析器,当Controller返回XXX字符串时,先经过拦截器,而后该类就会在/webapp/目录下,查找XXX.jsp文件 -->
23     <bean
24     class="org.springframework.web.servlet.view.InternalResourceViewResolver">
25     <property name="prefix" value="/"/>
26     <property name="suffix" value=".jsp"/>
27     </bean>
28 
29     <!-- 在向页面返回一个json格式的数据时,会报 No converter found for return value of type: class com.alibaba.fastjson.JSONObject-->
30     <!-- 这里转换一下-->
31     <mvc:annotation-driven>
32         <mvc:message-converters register-defaults="false">
33             <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
34             <bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
35                 <property name="supportedMediaTypes">
36                     <list>
37                         <!-- 这里顺序不能反,必定先写text/html,否则ie下出现下载提示 -->
38                         <value>text/html;charset=UTF-8</value>
39                         <value>application/json;charset=UTF-8</value>
40                     </list>
41                 </property>
42             </bean>
43         </mvc:message-converters>
44     </mvc:annotation-driven>
45 
46 </beans>
<!-- 表示支持Spring的注解-->
    <context:annotation-config/>
    <!-- 表示支持MVC的注解-->
    <mvc:annotation-driven/>
    <!-- 表示放行静态资源-->
    <mvc:default-servlet-handler/>
由于在web.xml的DispatcherServlet中拦截的为"/",也就是全部的请求都会被拦截,这样会致使项目里的一些静态资源css,js,img等出现404的状况,能够在这里配置,也能够在
web.xml中配置,以放行静态资源,在DispatcherServlet的mapping中加一个default
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.map</url-pattern>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
下面是须要扫描的controller,也就是将该包下的全部类交给spring进行管理,在对应的controller类上加上@controller注解,表示它是一个接口
<context:component-scan base-package="cn.test.controller"/>

最下面那段配置,是由于向页面响应数据的时候报No converter found for return value of type: class com.alibaba.fastjson.JSONObject,fastjson转springMVC报
转换错误,加上那段配置解决。


3.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"
         version="3.0">
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring-context.xml
    </param-value>
  </context-param>
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:spring-context.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>  
1)监听web容器启动
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


在web.xml配置监听器ContextLoaderListener(listener-class) 
ContextLoaderListener的做用就是启动Web容器时,自动装配ApplicationContext的配置信息。
由于它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。
在ContextLoaderListener中关联了
ContextLoader这个类,因此整个加载配置过程由ContextLoader来完成.它的API说明:

第一段说明ContextLoader能够由 ContextLoaderListener和ContextLoaderServlet生成。若是查看ContextLoaderServlet的API,
能够看到它也关联了ContextLoader这个类并且它实现了HttpServlet这个接口 ,第二段,ContextLoader建立的是 XmlWebApplicationContext这样一个类,
它实现的接口是WebApplicationContext->ConfigurableWebApplicationContext->ApplicationContext->
BeanFactory这样一来spring中的全部bean都由这个类来建立
2)  装载配置信息
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring-context.xml </param-value> </context-param>


<!--若是在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml,  
在WEB-INF目录下建立的xml文件的名称必须是applicationContext.xml。  
若是是要自定义文件名能够在web.xml里加入contextConfigLocation这个context参数:  
在<param-value> </param-value>里指定相应的xml文件名,若是有多个xml文件,能够写在一块儿并以“,”号分隔。  
也能够这样applicationContext-*.xml采用通配符,好比这那个目录下有applicationContext-ibatis-base.xml,  
applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。  
在ContextLoaderListener中关联了ContextLoader这个类,因此整个加载配置过程由ContextLoader来完成。-->
这里导入配置文件spring-context.xml
3)字符编码过滤器
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

字符编码过滤器,这个过滤器是针对于浏览器每次请求进行过滤的
4)DispatcherServlet
  <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
        classpath:spring-context.xml
      </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
程序的入口,全部的请求都会通过dispatchServlet进行处理,若是与后台controller能匹配则经过,不然不经过。<load-on-startup>1</load-on-startup>表示
让dispatchServlet与Tomcat容器一块儿启动。

4.后台接口controller
 1 package cn.test.controller;
 2 
 3 
 4 import com.alibaba.fastjson.JSONObject;
 5 import org.springframework.stereotype.Controller;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.ResponseBody;
 8 
 9 import javax.servlet.http.HttpServletRequest;
10 
11 @Controller
12 @RequestMapping("/test")
13 public class SpringController {
14     @RequestMapping("/index")
15     @ResponseBody
16     public JSONObject index(HttpServletRequest request){
17         String username = request.getParameter("username");
18         String password ="123456";
19         JSONObject jsonObject = new JSONObject();
20         jsonObject.put("password",password);
21         return jsonObject;
22     }
23 }

加上@ResponseBody注解,向页面返回json格式的响应数据jquery

5.jspweb

 1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 2 <html>
 3 <body>
 4 <h2>Hello World!</h2>
 5 <%--<form action="/test/index">--%>
 6     <%--<input type="text" value="username" name="username">--%>
 7     <button id="bird">你个傻鸟!!!</button>
 8 <%--</form>--%>
 9 
10 <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
11 <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.11.1.min.js"></script>
12 <script>
13      $("#bird").click(function () {
14          $.ajax({
15              url:"/test/index",
16              data:{
17                  username:"yang",
18              },
19              dataType:"json",
20              success:function (data) {
21                  alert(data.password);
22              }
23             })
24      })
25 </script>
26 </body>
27 </html>

到此就结束了,点击你个傻鸟按钮,页面将弹出"123456"。ajax

由于用的ajax请求,ajax是不支持重定向的,若是请求成功后要跳转到一个页面,能够在ajax的success函数里进行跳转。spring

或者使用表单提交数据,访问<form>标签中的action,再这后台进行跳转页面,去掉@responseBody注解,返回视图名字,通过spring.xml中配置的视图解析器便可。json

项目打包时,默认是项目名+版本号,要去除版本号的话能够在pom.xml中加上api

<finalName>customAct</finalName>在build标签中加入便可。有不对的地方,欢迎你们批评指着,谢谢。文章web.xml中配置的一些讲解,参考这篇博客,写的比较详细,感兴趣的能够去看https://www.cnblogs.com/wkrbky/p/5929943.html
相关文章
相关标签/搜索