Commit f4b6652f by hxw

update

parents
package db;
import java.sql.Connection;
import java.sql.DriverManager;
public class DB {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://192.168.1.81:3306/chatCN";
private static String user = "root";
private static String pwd = "admin";
public static Connection getConnection(){
Connection conn = null;
try{
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}
package db;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.File;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DBCPUtils {
private static DataSource ds;//定义一个连接池对象
static{
try {
Properties pro = new Properties();
File file = new File("dbcpconfig.properties");
pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"));
ds = BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象
} catch (Exception e) {
e.printStackTrace();
//throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件!");
}
}
//从池中获取一个连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void closeAll(ResultSet rs, Statement stmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();//关闭
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
\ No newline at end of file
package db;
import entity.QuestionKeyWord;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SqlHelper {
private Connection conn = null;
/*
public SqlHelper(){
conn = DB.getConnection();
}
*/
public SqlHelper() throws SQLException {
conn = DBCPUtils.getConnection();
}
public void destroy(){
if (conn != null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
/*
public boolean insertAction(QuestionKeyWord qkw){
String sql = "insert into user_info (chat_key,action_name) values(?,?)";
boolean b = false;
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,qkw.getChatKey());
ps.setString(2,qkw.getActionName());
b = ps.execute();
return b;
} catch(Exception e){
e.printStackTrace();
}
return b;
}
public boolean updateAction(QuestionKeyWord qkw){
String sql = "update user_info set action_name=? where chat_key=?";
boolean b = false;
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,qkw.getActionName());
ps.setString(2,qkw.getChatKey());
b = ps.execute();
return b;
} catch (SQLException e) {
e.printStackTrace();
}
return b;
}
public String queryActionByKey(String chat_key){
String sql = "select * from user_info where chat_key= ?";
String pre_name = "";
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,chat_key);
ResultSet rs = ps.executeQuery();
if(rs.next())
return rs.getString("action_name");
}catch(Exception e){
e.printStackTrace();
}
return "empty";
}
*/
public String queryUsernameByKey(String chat_key){
String sql = "select * from chats where chat_key = ?";
String userName = "";
String result = "empty";
try{
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,chat_key);
ResultSet rs = ps.executeQuery();
if(rs.next())
result = rs.getString("bot");
rs.close();
ps.close();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
}
package entity;
public class AnswerNextStep {
int status = 0;
String answer;
String next;
public String getAnswer() {
return answer;
}
public int getStatus() {
return status;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public void setStatus(int status) {
this.status = status;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public AnswerNextStep(int status, String answers, String next){
this.answer = answers;
this.next = next;
this.status = status;
}
public AnswerNextStep(){}
}
package entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
public class Condition {
public int priority = 1;
public HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String,HashSet<String>> historyPremise = new HashMap<String,HashSet<String>>();
public HashMap<String,HashSet<String>> currentPremise = new HashMap<String,HashSet<String>>();
public String Answer;
public String nextStep;
public String feature;
public String indexName;
//public ArrayList<String> indexName = new ArrayList<String>();
public Condition(int priority) {
this.priority = priority;
}
public Condition() {
}
}
package entity;
public class QuestionKeyWord {
String actionName;
String chatKey;
String keyWord;
public String getActionName() {
return actionName;
}
public String getChatKey() {
return chatKey;
}
public String getKeyWord() {
return keyWord;
}
public void setActionName(String actionName) {
this.actionName = actionName;
}
public void setChatKey(String chatKey) {
this.chatKey = chatKey;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
}
package entity;
import java.util.HashMap;
import java.util.List;
public class UserInfo {
public UserInfo(String userName){
this.conditionTable = new HashMap<String, List<Condition>>();
this.configStr = "";
this.userName = userName;
}
public HashMap<String,List<Condition>> conditionTable;
public String configStr;
public String userName;
}
package processing;
import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ChatCacheController {
public static synchronized Map<String, String> getChatCache(String chatKey, ServletContext context){
Map<String, String> historyInfoPoint = null;
Map<String, Map<String, String>> chatCache = null;
if(context.getAttribute("chatCache") == null) {
chatCache = new HashMap<String, Map<String, String>>();
context.setAttribute("chatCache", chatCache);
} else{
chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
}
String chatkey;
/*
Iterator<String> it = chatCache.keySet().iterator();
while(it.hasNext()){
chatkey = it.next();
System.out.println("chatkey:"+chatkey);
}
*/
try{
historyInfoPoint = chatCache.get(chatKey);
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
}catch(Exception e){
//可整合
historyInfoPoint = null;
}
return historyInfoPoint;
}
public static synchronized void updateChatCache4Delete(ServletContext context){
String chatKey;
long lastChatTime,now;
Map<String,String> history = new HashMap<String,String>();
Map<String, Map<String, String>> chatCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
Iterator<String> it = chatCache.keySet().iterator();
while (it.hasNext()) {
chatKey = it.next();
history = chatCache.get(chatKey);
lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis();
if (now - lastChatTime > 300000) {
it.remove();
}
}
context.setAttribute("chatCache", chatCache);
}
public static synchronized void updateChatCache4Insert(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,ServletContext context){
historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis()));
Map<String,Map<String, String>> keyCache = (Map<String, Map<String, String>>) context.getAttribute("chatCache");
keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint);
context.setAttribute("chatCache",keyCache);
}
}
package processing;
import entity.AnswerNextStep;
import net.sf.json.JSONObject;
import java.io.UnsupportedEncodingException;
public class MyFunc {
public static String toJson(AnswerNextStep ans) {
JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus());
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr){
JSONObject jobj = new JSONObject();
jobj.put("returnString",returnStr);
return jobj.toString();
}
public static String convert2Utf8(String s){
if(s==null)return null;
try {
s=new String(s.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
}
package servlet;
import entity.AnswerNextStep;
import entity.Condition;
import entity.UserInfo;
import processing.ChatCacheController;
import processing.MyFunc;
import processing.ProcessQuestion;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.*;
@WebServlet(name = "GetAnswerServlet",urlPatterns = {"/test","/test/"})
public class GetAnswerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
Map<String,String[]> curInfoPoint = request.getParameterMap();
Map<String, String> historyInfoPoint = null;
AnswerNextStep bestMatch = null;
Condition ansCondition = null;
String ansJ,return_str="";
String chatKey = curInfoPoint.get("chat_key")[0];
ProcessQuestion process = new ProcessQuestion();
OutputStream out = response.getOutputStream();
ServletContext context = this.getServletContext();
UserInfo userinfo = null;
try {
//userinfo = process.userInfoQuery(chatKey,context);
userinfo = process.userInfoQuery(request.getParameter("bot_name"),context);
} catch (SQLException e) {
e.printStackTrace();
}
historyInfoPoint = ChatCacheController.getChatCache(chatKey,context);
if(historyInfoPoint == null) {
String k;
historyInfoPoint = new HashMap<String,String>();
Iterator<String> iit = curInfoPoint.keySet().iterator();
while (iit.hasNext()){
k = iit.next();
historyInfoPoint.put(k,"");
}
}
//输出所有actionName的值
Iterator<String> iit = curInfoPoint.keySet().iterator();
while(iit.hasNext()){
String k = iit.next();
System.out.print(k+": ");
String values[] = curInfoPoint.get(k);
if(values != null && !values[0].equals(" ") && !values[0].equals("") && !k.equals("chat_key") && !k.equals("action_name") && !k.equals("bot_name"))
return_str = return_str + " " + k + ":" + values[0] + " ";
for(String v:values) {
System.out.print(v + " ");
}
System.out.println();
}
/*得到答案,清楚超时chatkey_key,更新历史信息点&生成答案,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试
ansCondition = process.getAnswer(curInfoPoint,historyInfoPoint,userinfo.conditionTable);
bestMatch = process.updateInfoGetBestMatch(ansCondition,curInfoPoint,historyInfoPoint,context,userinfo);
//process.updateDB(kw);
//System.out.println("Current time:" + System.currentTimeMillis());
if(context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime",System.currentTimeMillis());
if(System.currentTimeMillis() - (long)context.getAttribute("cacheUpdateTime") > 300000) {
ChatCacheController.updateChatCache4Delete(context);
context.setAttribute("cacheUpdateTime",System.currentTimeMillis());
}
bestMatch.setAnswer(" \n"+return_str+"\n " + bestMatch.getAnswer());
ansJ = MyFunc.toJson(bestMatch);
//System.out.println(ansJ);
out.write(ansJ.getBytes());
out.flush();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("do get method");
}
}
package servlet;
import entity.UserInfo;
import processing.MyFunc;
import processing.ProcessQuestion;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@WebServlet(name = "ReloadConfig")
public class ReloadConfig extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
boolean flag = true;
UserInfo userinfo = new UserInfo(userName);
File configFile = new File(System.getProperty("user.dir")+"/config/"+userName+".txt");
ServletContext context = this.getServletContext();
if(!configFile.exists()) {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("文件不存在: "+userName);
}else{
FileReader reader = new FileReader(configFile);
BufferedReader br = new BufferedReader(reader);
try {
userinfo = ProcessQuestion.buildUserInfo(br, userinfo);
context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){
flag = false;
System.out.println(userinfo.userName + ".txt 有误");
e.printStackTrace();
}
reader.close();
br.close();
if(!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("更新失败配置文件有误:" + userName +".txt\\\n");
}
else{
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
PrintWriter out = response.getWriter();
out.println("更新成功+ “ ");
out.flush();
out.close();
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
package servlet;
import entity.Condition;
import entity.UserInfo;
import processing.MyFunc;
import processing.ProcessQuestion;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
@WebServlet(name = "UpdateServlet",urlPatterns = {"/update"})
public class UpdateServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在此处理通过页面提交的配置文件,在servletContext中更新userName指定的userinfo,并将配置文件以username.txt的命名方式保存至本地。
String actionName,feature,line,element[],pair[],next[],cur_premises[],history_premises[],premises[];
ArrayList<String> errorList = new ArrayList<String>();
ServletContext context = this.getServletContext();
String userName = request.getParameter("userName");
UserInfo userinfo = new UserInfo(userName);
userinfo.conditionTable = new HashMap<String, List<Condition>>();
List<Condition> conditionList = null;
HashSet<String> keyWordSet = null;
BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string")));
boolean flag = true;
String errorStr = "";
while((line = br.readLine()) != null){
if(line.trim().equals(""))
continue;
//line = MyFunc.convert2Utf8(line.trim());
userinfo.configStr += line+"\n";
Condition condition = new Condition();
try {
condition = ProcessQuestion.buildCondition(condition,line);
conditionList = userinfo.conditionTable.get(condition.indexName);
if(conditionList == null)
conditionList = new ArrayList<Condition>();
conditionList.add(condition);
userinfo.conditionTable.put(condition.indexName,conditionList);
/*
for(String name:condition.indexName){
userinfo.conditionTable.put()
}
*/
} catch(Exception e ){
System.out.println("配置文件有误!");
flag = false;
errorList.add(line);
}
}
br.close();
if(!flag) {
//request.setAttribute("returnMessage","更新失败,以下行有误:</br>" + errorStr +"</br>"+ "<a href=\"update.html\">返回重新输入。</a>");
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr +"\\\n");
out.println("更新失败,以下行有误: ");
for(String error:errorList)
out.println("---"+error);
out.flush();
out.close();
}
else{
response.setCharacterEncoding("utf-8");
response.setContentType( "text/plain");
PrintWriter out = response.getWriter();
out.println("更新成功+ “ ");
out.flush();
out.close();
//request.setAttribute("returnMessage","更新成功"+userinfo.configStr);
context.setAttribute(userName,userinfo);
String path = System.getProperty("user.dir")+"/config/"+userinfo.userName+".txt";
File file = new File(path);
File dir = new File(System.getProperty("user.dir")+"/config");
if(!dir.exists())
dir.mkdir();
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(userinfo.configStr);
bw.close();
fw.close();
}
//request.;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.81:3306/chatCN
username=root
password=admin
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=30
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF-8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
\ No newline at end of file
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.81:3306/chatCN
username=root
password=admin
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF-8
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
\ No newline at end of file
<%--
Created by IntelliJ IDEA.
User: hxw
Date: 18-5-8
Time: 下午1:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
$END$
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title>配置文件</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password" id="TextBox2" tabindex="2" value=""></textarea></p>
<p><input type="button" value="登录" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
if(document.getElementById("txtUserName").value == ""){
alert("用户名为必填项!");
return false;
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "update" ,//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0;i < list.length;i++){
str += '<div>'+list[i]+'</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error : function(res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title> QA </title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:500px;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password" id="TextBox2" tabindex="2" value=""></textarea></p>
<p><input type="button" value="登录" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "update" ,//url
data: $('#frm').serialize(),
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0;i < list.length;i++){
str += '<div>'+list[i]+'</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error : function(res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<!DOCTYPE HTML>
<html>
<head>
<title> 配置文件 </title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<meta charset=UTF-8>
</head>
<body>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:autopx;text-align:center;margin:50px auto;">
<form id="frm" onsubmit="return false" action="##" method="post">
<p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" value=""/></p>
<p>内 容:<br/><textarea style="width:700px;height:320px;word-break:break-all" name="config_string" type="password" id="config_string" tabindex="2" value=""></textarea></p>
<p>关键词替换:<br/><textarea style="width:700px;height:100px;word-break:break-all" name="macro" type="password" id="macro" tabindex="2" value=""></textarea></p>
<p><input type="button" value="登录" onclick="update()">&nbsp;<input type="reset" value="重置"></p>
</form>
</div>
<div style="background-color:#ccc;-moz-border-radius: 5px;-webkit-border-radius: 5px;border:1px solid #000;padding:10px;margin-top:100px;width:800px;height:auto;text-align:center;margin:50px auto;">
<div id="returnInfo"></div>
</div>
<script type="text/javascript">
function update() {
var macroStr = document.getElementById("macro").value;
var text = document.getElementById("config_string").value;
var macroMap = new Map();
if (document.getElementById("txtUserName").value == "") {
alert("用户名为必填项!");
return false;
}
if (macroStr != "") {
var macro = macroStr.split("\n");
for (var i = 0; i < macro.length; i++) {
if(macro[i] != ""){
pair = macro[i].split("|");
if (pair.length == 1) {
alert("格式有误");
}
text = text.replace(pair[0], pair[1]);
}
}
}
$.ajax({
//几个参数需要注意一下
type: "POST",//方法类型
dataType: "text",//预期服务器返回的数据类型
url: "update" ,//url
data:{
"userName":document.getElementById("txtUserName").value,
"config_string": text
},
success: function (result) {
var list = result.split("---")
var str = "";
for (var i = 0;i < list.length;i++){
str += '<div>'+list[i]+'</div>'
}
document.getElementById("returnInfo").innerHTML = str
},
error : function(res) {
// document.getElementById("returnInfo").appendChild() = res;
}
});
}
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="FacetManager">
<facet type="web" name="Web">
<configuration>
<descriptors>
<deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/web/WEB-INF/web.xml" />
</descriptors>
<webroots>
<root url="file://$MODULE_DIR$/web" relative="/" />
</webroots>
</configuration>
</facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" exported="" scope="PROVIDED" name="Tomcat 8.5.31" level="application_server_libraries" />
<orderEntry type="library" exported="" name="lib" level="project" />
</component>
</module>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment