欢迎光临散文网 会员登陆 & 注册

STRUTS2: AJAX支持,stream类型或JSON类型result的AJAX实现加载下拉框【诗书画唱】

2021-01-11 23:24 作者:诗书画唱  | 我要投稿

CTRL+F:AJAX支持,stream类型result的AJAX实现,JSON类型result的AJAX实现。

地址栏输入路径的运行action,生成下拉框的例子。jquery中赋值用的val方法。stream类型result的AJAX实现的运行jsp界面就加载下拉框的例子。测试数据库是否连上的打印语句。可将内容自动转换为JSON的JSON插件包的专用属性“map“。Ajax中取出JSON字符串中的对象属性的方法。用ajax创建option下拉框的方法。JSON类型result的AJAX实现的数据库和ajax,action,运行jsp界面就加载下拉框内容的例子。没有页面跳转的action(就是ajax实现的)。通过ajax请求来获取下拉框中的数据的例子。




AJAX支持 PPT START

stream类型result的AJAX实现:

JSON类型result的AJAX实现:




AJAX支持 PPT END



讲义 START













一、type="stream"类型结果

二、type="json"类型结果


struts2项目中的页面中加载一个下拉框:

页面跳转方式,action中拼接html字符串,然后通过调用servletAPI实现

不需要页面跳转,可以使用ajax进行下拉框的数据加载:


使用json插件包:

1、导入struts2-json-plugin-2.3.24.1.jar

2、设置package的extends属性为json-default

3、做struts配置






讲义 END


例子 START


package com.jy.action;


import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;


import org.apache.struts2.ServletActionContext;


public class GameAction {

//将需要传递到页面的html字符串放到ins中,

//就是回调函数中的data

private InputStream ins;

public InputStream getIns() {

return ins;

}


public void setIns(InputStream ins) {

this.ins = ins;

}


//http://localhost:8080/J190802/gm/toGameAc.action

    public String toGame(){

    String html = "<option>A</option><option>B</option><option>C</option>";

    ServletActionContext.getRequest().setAttribute("html", html);

    return "success";

    }

    

    public String loadData1(){

    String html = "<option>A</option><option>B</option><option>C</option>";

    ins = new ByteArrayInputStream(html.getBytes());

    return "success";

    }

    

    public String loadData2() throws UnsupportedEncodingException{

    String jsonStr = "{\"act\":\"张三\",\"pwd\":123}";   

    ins = new ByteArrayInputStream(jsonStr.getBytes("utf-8"));

    return "success";

    }

}

package com.jy.bean;


public class Userinfo {

    private Integer id;

    private String act;

    private String pwd;

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getAct() {

return act;

}

public void setAct(String act) {

this.act = act;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

}

package com.jy.dao;


import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.ArrayList;

import java.util.List;


import com.jy.bean.Userinfo;

import com.jy.util.DbUtil;


public class UserinfoDao {

    public List<Userinfo>selectAll(){

    String sql = "select * from userinfo";

   

    Connection conn = null;

    PreparedStatement pstm = null;

    ResultSet rs = null;

    List<Userinfo>list = new ArrayList<Userinfo>();

    try {

        conn = DbUtil.getConn();

pstm = conn.prepareStatement(sql);

    rs = pstm.executeQuery();

    while(rs.next()) {

    Userinfo u = new Userinfo();

    u.setId(rs.getInt("id"));

    u.setAct(rs.getString("act"));

    u.setPwd(rs.getString("pwd"));

    list.add(u);

    }

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    return list;

    }

}


package com.jy.util;


import java.io.IOException;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.Properties;


public class DbUtil {

private static String driverName;

    private static String url;

    private static String user;

    private static String pwd;

    

    static {

    //读取properties文件

    Properties prop = new Properties();

    //将db.properties文件读取到内存中去

    InputStream is = DbUtil.class.getClassLoader()

    .getResourceAsStream("db.properties");

    //加载内容

    try {

prop.load(is);

//读取内容

driverName = prop.getProperty("drivername");

url = prop.getProperty("url");

user = prop.getProperty("username");

pwd = prop.getProperty("password");

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

    }

    

    //获取数据库连接对象的方法

    public static Connection getConn(){

    Connection conn = null;

    try {

Class.forName(driverName);

conn = DriverManager.getConnection(url,user,pwd);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   

    return conn;

    }

    

    public static void close(ResultSet rs,PreparedStatement pstm

    ,Connection conn){

        try {

        if(rs != null) {

            rs.close();

            }

            if(pstm != null) {

            pstm.close();

            }

            if(conn != null) {

            conn.close();

            }

        } catch(Exception e) {

        e.printStackTrace();

        }

    }

}




drivername=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&amp;characterEncoding=GBK2312

username=root

password=root

<?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>J190802</display-name>

  <!-- struts2框架的配置 -->

  <filter>

      <filter-name>struts2</filter-name>

      <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>

  </filter>

  <filter-mapping>

      <filter-name>struts2</filter-name>

      <url-pattern>/*</url-pattern>

  </filter-mapping>

  <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>

</web-app>


<%@ page language="java" contentType="text/html; charset=UTF-8" 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>

        <base hreff="<%=basePath%>">

        <title></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" srcc="js/jquery-1.11.0.js"></script>

        <script type="text/javascript">

            $(function(){

            $.ajax({

            url: 'us/getAllNameAc.action',

            type: 'POST',

            dataType: 'JSON',

            success: function(data){

            //方法一html字符串

            //$('#nameSel').html(data);

            //方法二json字符串

            for(var i = 0;i < data.length;i ++){

            var act = data[i].act;

            //创建一个Option标签

            var opt = new Option(act,act);

            $('#nameSel').get(0).add(opt);

            }

            }

            });

            })

        </script>

    </head>

    <body>

        <select id="nameSel"></select>

    </body>

</html>




<%@ page language="java" contentType="text/html; charset=UTF-8" 

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>

        <base hreff="<%=basePath%>">

        <title></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">

    </head>

    <body>

        <select id="game">${html }</select>

    </body>

</html>

<%@ page language="java" contentType="text/html; 

charset=UTF-8" 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>

        <base hreff="<%=basePath%>">

        <title></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" srcc="js/jquery-1.11.0.js"></script>

        <script type="text/javascript">

            $(document).ready(function(){

            //通过ajax请求来获取下拉框中的数据

            $.ajax({

            url: 'gm/ld1Ac.action',

            type: 'POST',

            data: {},

            success: function(data){

            $('#sel').html(data);

            }

            });

            });

        </script>

    </head>

    <body>

        <select id="sel"></select>

    </body>

</html>

<%@ page language="java" contentType="text/html; charset=UTF-8"

 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>

        <base hreff="<%=basePath%>">

        <title></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" srcc="js/jquery-1.11.0.js"></script>

        <script type="text/javascript">

            $(document).ready(function(){

            $.ajax({

            url: 'gm/ld2Ac.action',

                type: 'POST',

                dataType: 'json',

                success: function(data){

                //将json字符串转换成js对象

                //var obj = JSON.parse(data);

                $('#act').val(data.act);

                $('#pwd').val(data.pwd);

                }

            });

            });

        </script>

    </head>

    <body>

        <label>账号:</label><input type="text" id="act" />

        <br>

        <label>密码:</label><input type="text" id="pwd"/>

    </body>

</html>













例子 END



视频笔记 START

地址栏输入路径的运行action,生成下拉框的例子 START

(代码前面的“例子”中的内容)





启动eclipse中的服务器后浏览器输入http://localhost:8080/J190802/gm/toGameAc.action,按回车后:





地址栏输入路径的运行action,生成下拉框的例子 END    

jquery中赋值用的val方法:

stream类型result的AJAX实现的运行jsp界面就加载下拉框的例子 START






stream类型result的AJAX实现的运行jsp界面就加载下拉框的例子 END


测试数据库是否连上的打印语句:

可将内容自动转换为JSON的JSON插件包的专用属性“map”:


Ajax中取出JSON字符串中的对象属性的方法:

用ajax创建option下拉框的方法:

JSON类型result的AJAX实现的数据库和ajax,action,运行jsp界面就加载下拉框内容的例子 START


create table Userinfo(

id int primary key auto_increment,


act  varchar(100),

pwd  varchar(100)

);


insert into  Userinfo(


act,

pwd ) values("1","1");

insert into  Userinfo(


act,

pwd ) values("三连关注","22222");

insert into  Userinfo(


act,

pwd ) values("诗书画唱","33333");


select *   from Userinfo

drop table Userinfo



drivername=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/firstjsp?useUnicode=true&amp;characterEncoding=GBK2312

username=root

password=root


——


——




JSON类型result的AJAX实现的数据库和ajax,action,运行jsp界面就加载下拉框内容的例子 END



通过ajax请求来获取下拉框中的数据的例子 START

没有页面跳转的action(就是ajax实现的):





通过ajax请求来获取下拉框中的数据的例子 END


视频笔记 END


STRUTS2: AJAX支持,stream类型或JSON类型result的AJAX实现加载下拉框【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律