最基本springMVC,响应页面请求

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

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

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

        

 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了

  

 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格式的响应数据

5.jsp

 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的success函数里进行跳转。

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

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

<finalName>customAct</finalName>
在build标签中加入即可。

有不对的地方,欢迎大家批评指着,谢谢。文章web.xml中配置的一些讲解,参考这篇博客,写的比较详细,感兴趣的可以去看
https://www.cnblogs.com/wkrbky/p/5929943.html
 
 
 

转载于:https://www.cnblogs.com/Yang777/p/9506067.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值