• SpringMVC通过实体类返回json格式的字符串,并在前端显示


    一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包

    jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

    二.web,.xml配置

    classpath:spring-servlet.xml指定springmvc配置文件的位置
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
      
       <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value> 
        </init-param>
        <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
        </init-param>
        -->
        <load-on-startup>1</load-on-startup>
    </servlet>
     
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    
    </web-app>
    

    三.spring-servlet.xml配置

    通过此配置,将实体类自动返回为json格式的数据

    <?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:p="http://www.springframework.org/schema/p"  
        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-3.2.xsd  
           http://www.springframework.org/schema/context   
            http://www.springframework.org/schema/context/spring-context-3.2.xsd  
            http://www.springframework.org/schema/mvc      
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">  
         <!-- 启用spring mvc 注解 -->
        <context:annotation-config />
     
        <!-- 设置使用注解的类所在的jar包 -->
        <context:component-scan base-package="me.mvc,me.base"></context:component-scan>
     
        <!-- 完成请求和注解POJO的映射 -->
      <!--   <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> -->
     
        <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
       <!-- 通过实体类返回json格式数据的关键配置 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!--返回字符串格式json--> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="102400000"></property> </bean> </beans>

    四,后台java代码

    package me.mvc;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import me.mvc.service.testmvcDao;
    import net.sf.json.JSONArray;
    
    import org.apache.struts2.ServletActionContext;
    import org.springframework.http.HttpRequest;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartHttpServletRequest;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    @RequestMapping("/mvc/*")
    public class testmvc {
    
    
        @RequestMapping(method=RequestMethod.GET,value="/hello22index.do")//第一步访问hello2页面
          public String index2() {
        
          return "hello2";
      }
        @ResponseBody
        @RequestMapping(method=RequestMethod.POST,value="/hello22.do")//第二步前台发送ajax请求调用此方法并返回json数据
          public User index2post(String testname1 ,HttpServletResponse response) throws IOException {
       
            System.out.println("*************:"+testname1);
      
            User u=new User();
            u.setUsername("name");
            u.setUserpassword("pass");
            return u;
    }
    
    }

    五.前端页面

    该方法sendajax()将向后台发送请求,调用index2post()方法,返回json数据格式

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    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>
       <script type="text/javascript" src="../../js/jquery-1.12.0.js"></script>
        <base href="<%=basePath%>">
        
        <title>My JSP 'hello2.jsp' starting page</title>
        
    	<meta http-equiv="pragma" content="no-cache">
    	<meta http-equiv="cache-control" content="no-cache">
    	<meta http-equiv="expires" content="0">    
    	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    	<meta http-equiv="description" content="This is my page">
    
     <script type="text/javascript" src="<%=path%>/js/jquery-1.12.0.js"></script></head>
      
      <body>
    
          <input type="text" name="testname" id="testname1">
    
           <input type="button" value="ajax提交" onclick="sendajax()">
     
    </form>
      </body>
      <script type="text/javascript">
       function  sendajax()
       {   
    	   var testname1=$("#testname1").val();
    	   alert(testname1);
    	   $.ajax({
    	        type: "post",
    	        url: "<%=path%>/mvc/hello22.do",  
    	        data: {testname1:testname1},             
    	        dataType: "json",            
    	        success: function (data) {	
    	      	 alert(data.username);
    	     	     
    		     },
    	        error: function (XMLHttpRequest, textStatus, errorThrown) {
    	         alert("系统繁忙,请稍后重试!");                
    	  }
    	}); 
       }
      </script>
    </html>
    

      

  • 相关阅读:
    使用TransactionScope实现多数据库连接事务操作
    zabbix_agentlinux下的安装
    (转)Zabbix AgentWindows平台配置指导
    使用SpringSide 3.1.4.3开发Web项目的全过程(上)
    应用开发中数据字典项设计实现方案
    Oracle Top N 和 Oracle中的limit问题解决方案
    Struts 2.0的codebehinde插件应用简述
    PropertyUtils和MethodUtils使用
    Log4j基本使用方法
    Quartz从入门到进阶
  • 原文地址:https://www.cnblogs.com/cl1255674805/p/5486950.html
Copyright © 2020-2023  润新知