ExtJS与后台Java交互

时间:2023-03-08 15:49:32
ExtJS与后台Java交互

参考博客:http://blog.csdn.net/wanghuan203/article/details/8125970

开发环境:Eclipse + Tomcat + ExtJS6.0

工程目录结构

ExtJS与后台Java交互

运行效果:

ExtJS与后台Java交互ExtJS与后台Java交互

后台获取的数据

ExtJS与后台Java交互

源代码如下:

1.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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>ExtJSDemo</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>TestServlet</servlet-name>
    <servlet-class>com.scd.servlet.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>TestServlet</servlet-name>
      <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>

</web-app>

2.ExtJava.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ExtJS And Java</title>
<link rel="icon" href="img/tomcat.ico" type="image/x-icon" ></link>
<link rel="stylesheet" type="text/css" href="neptune/theme-neptune/resources/theme-neptune-all.css"></link>
<script type="text/javascript" src="neptune/ext-all.js"></script>
<!--extjs本地化文件,会将extjs中的提示信息等自动转换为简体中文-->
<script type ="text/javascript" src="neptune/locale/locale-zh_CN.js"></script>
<script type ="text/javascript">
Ext.onReady(
        function() {
            Ext.create('Ext.container.Viewport',
                {
                    scrollable : true,
                    items : [
                        {
                            xtype : 'container',
                            layout : {
                                type : 'hbox',
                                align : 'center',
                                pack : 'center'
                            },
                            items : [
                                {
                                    xtype : 'form',
                                    bodyPadding : 20,
                                    maxWidth : 700,
                                    fieldDefaults : {
                                        msgTarget : 'under'
                                    },
                                    flex : 1,
                                    title : 'Customer Register',
                                    items : [
                                      {
                                        xtype : 'fieldcontainer',
                                        layout : 'hbox',
                                        fieldLabel : 'Name',
                                        defaultType : 'textfield',
                                        defaults : {
                                            allowBlank : false,
                                            flex : 1
                                        },
                                        items : [
                                            {
                                                name : 'Name',
                                                emptyText : 'Name'

                                            }
                                        ]
                                      },
                                      {
                                         xtype : 'datefield',
                                         fieldLabel : 'Date of Birth',
                                         name : 'dob',
                                         maxValue : new Date()
                                      },
                                      {
                                         xtype : 'textfield',
                                         vtype : 'email',
                                         fieldLabel : 'Email Address',
                                         name : 'email',
                                         allowBlank : false,
                                         //emptyText : 'user@example.com'
                                      },
                                      {
                                         xtype : 'textfield',
                                         fieldLabel : 'Phone Number',
                                         labelWidth : 100,
                                         name : 'phone',
                                         width : 200,
                                         emptyText : 'xxx-xxx-xxxx',
                                         maskRe : /[\d\-]/,
                                         regex : /^\d{3}-\d{3}-\d{4}$/
                                      },
                                      {
                                          xtype : 'button',
                                          href : 'http://www.baidu.com',
                                          width : 100,
                                          height : 60,
                                          text : 'Baidu'
                                      }
                                    ],
                                    //form提交数据部分,通过按钮提交事件
                                    buttons : [
                                        {
                                            text : 'Submit',
                                            handler : function() {
                                                var form = this.up('form').getForm();
                                                if (form.isValid()) {
                                                    form.submit(
                                                      {
                                                          url : './TestServlet',
                                                          //重点: success块
                                                          success : function(form, action) {
                                                            //showmessage是从后台传过来
                                                            Ext.MessageBox.alert("提示", action.result.showmessage);
                                                          },
                                                          failure : function(form, action) {
                                                            Ext.Msg.alert("提示", "失败");
                                                          }
                                                      }
                                                    );
                                                } else {
                                                    Ext.Msg.alert('Error', 'Fix the errors in the form');
                                                }
                                            }
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                }
            );
        }
    );
</script>
</head>
<body>

</body>
</html>

3.TestServlet.java

package com.scd.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends  HttpServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    /**
     *
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, IOException {
                 System.out.println("===doPost==========");try{
                       //调用action等后台方法
                       //有个返回值,返回给界面的内容
                       String showMessage = "你好";
                       //设置response格式
                       response.setCharacterEncoding("UTF-8");
                       response.setContentType("application/json");
                       response.getWriter().write(
                            "{'success':true,'showmessage':'"+ showMessage +"'}");

                 } catch (Exception e) {
                       //失败时返回的信息
                       response.setCharacterEncoding("UTF-8");
                       response.setContentType("text/html");
                       response.getWriter().write(
                                          "{'success':false,'showmessage':'出现异常,操作失败'}");
                       response.setStatus(500);
              }

    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                       throws ServletException, IOException {
              System.out.println("====I am doGet======");
              doPost(request,response);
    }
}

存在一个很大的疑惑就是当把代码里面的response.setContentType("text/html"); 设置为"text/html"之后,获取到的是表但数据

package com.scd.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("===doPost==========");
System.out.println("获取前端form组件中的数据");
String Name = request.getParameter("Name");
String bob = request.getParameter("dob");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
System.out.println(Name+bob+email+phone);
try{
//调用action等后台方法
//有个返回值,返回给界面的内容
String showMessage = "你好";
//设置response格式
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.getWriter().write(
"{'success':true,'showmessage':'"+ showMessage +"'}");

} catch (Exception e) {
//失败时返回的信息
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
response.getWriter().write(
"{'success':false,'showmessage':'出现异常,操作失败'}");
response.setStatus(500);
}

}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("====I am doGet======");
doPost(request,response);
}
}

终端输出的数据为

-----------------------------------

===doPost==========
获取前端form组件中的数据
chengdu17年01月18日1809542645@qq.com123-345-2341

ExtJS与后台Java交互

和之前传输数据不一样啊????