H5+ 移动app学习之四 遇到问题及解决方法
1.登录状态的判断
用localStorage设置一个item,登录及未登录时是不同值
2.返回刷新页面
mui.init({ beforeback: function() { //获得返回界面的webview var webview= plus.webview.getWebviewById('要返回页面的id'); webview.reload(true); //返回true,继续页面关闭逻辑 return true; } });
3.ajax post 在服务器端取值问题为空
url为jsp
前台js:
/** 登录验证*/ //封装好发送数据的函数 function postData(url, data, callback, waitingDialog) { mui.ajax(url,{ data: {"data" : data}, dataType: 'text',//服务器返回数据的格式 contentType: "application/x-www-form-urlencoded; charset=utf-8", type: 'post',//HTTP请求类型 timeout: 10000,//超过时间设置为10秒 success: callback, //服务器返回响应,根据响应结果,分析是否登录成功 error: function(xhr, type, errorThrown) { //异常处理 console.log(type); waitingDialog.close(); mui.alert("<网络连接失败,请重新尝试一下>", "错误", "OK", null); } }); } // 登录处理 document.getElementById('loginBtn').addEventListener('tap', function() { // 显示一个等待的对话框 var wd = plus.nativeUI.showWaiting(); var username = document.getElementById('username').value; //用户名 var password = document.getElementById('password').value; //密码 //构造json数据 var users = { "userName": username, "userPassword": password }; //构造url var url = "http://192.168.191.1:8080/OnlineMusicWebsite/loginUser.jsp"; if(username == "" || password == "") { mui.alert("用户名或密码为空!"); wd.close(); } else { //调用ajax postData( url, JSON.stringify(users), function(data) { wd.close(); // 调用成功,先关闭等待的对话框 //取回的数据后面带有空格 data = data.trim(); //data = data.replace(/^/s*/, "").replace(//s*$/, ""); if(data == "NON") { mui.alert("用户不存在!"); return; } else if(data == "NO"){ mui.alert("用户名或密码错误!"); return; }else { localStorage.setItem("login", 1); localStorage.setItem("userName",document.getElementById('username').value); // 清空用户名,密码 document.getElementById('username').value = ""; document.getElementById('password').value = ""; // 打开下一个画面 mui.openWindow({ url: '../../index.html', id: 'index', }); } }, wd ); } });
后台javascript
UserData.java
package com.recommendation.management;
public class UserData {
private String userName;
private String userPassword;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
DBBean.java
package com.recommendation.db; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; /** * @autor hongye */ public class DBBean { private String driverString = "com.microsoft.sqlserver.jdbc.SQLServerDriver";//加载jdbc驱动 private String connString = "jdbc:sqlserver://localhost:1433; DatabaseName=MusicDatabase";//连接服务器和数据库 private String dbName = "sa";//默认用户名 private String dbPassword = "sql";//密码 private Connection conn = null; private Statement stmt = null; private PreparedStatement ps = null; public DBBean() { try { Class.forName(driverString); conn = DriverManager.getConnection(connString, dbName, dbPassword); stmt = conn.createStatement(); } catch (Exception ex) { System.out.println("无法同数据库建立连接!"); } } // 字符串更新 public int executeUpdate(String s) { int result = 0; try { result = stmt.executeUpdate(s); } catch (Exception ex) { System.out.println("执行更新错误!"); System.out.println(ex); } return result; } // 参数更新str public int executeUpdate_Pre(String s, String str) { int result = 0; try { ps = conn.prepareStatement(s); ps.setString(1, str); ; result = ps.executeUpdate(); } catch (Exception ex) { System.out.println("1个参数执行更新错误"); } return result; } // 字符串查询 public ResultSet executeQuery(String s) { ResultSet rs = null; try { rs = stmt.executeQuery(s); } catch (Exception ex) { System.out.println("执行查询错误!"); System.out.println(ex); } return rs; } // 参数查询str public ResultSet executeQuery_Pr(String sql, String str) { ResultSet rs = null; try { ps = conn.prepareStatement(sql); ps.setString(1, str); rs = ps.executeQuery(); } catch (Exception ex) { System.out.println("执行查询错误!"); } return rs; } // 参数模糊查询str public ResultSet executeQuery_Pre(String s, String str) { ResultSet rs = null; try { ps = conn.prepareStatement(s); ps.setString(1, "%" + str + "%"); rs = ps.executeQuery(); } catch (Exception ex) { System.out.println("执行查询错误!"); } return rs; } public void close() { try { stmt.close(); conn.close(); } catch (Exception ex) { } } }
loginUser.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ page import="java.util.*,java.sql.*"%> <%@ page import="java.io.PrintWriter"%> <%@ page import="com.fasterxml.jackson.databind.ObjectMapper"%> <%@ page import="java.io.IOException"%> <%@ page import="com.recommendation.db.DBBean"%> <%@ page import="com.recommendation.management.UserData"%> <% //得到客户端的数据 String users = request.getParameter("data"); System.out.println("users: " + users); //解析json ObjectMapper mapper = new ObjectMapper(); UserData userData = mapper.readValue(users, UserData.class); //用户名,密码 String userName = "" + userData.getUserName(); String userPassword = userData.getUserPassword(); //连接数据库 DBBean db = new DBBean(); String sql = " select uPassword from users Where uName =" + userName; ResultSet rs = db.executeQuery(sql); System.out.println("userName: " + userName); System.out.println("users: " + rs); //判断用户是否存在 if (rs.next()) { String uPassword = rs.getString("uPassword"); //用户名,密码是否错误 if (uPassword.equals(userPassword)) { //data.setResult("OK"); //data.setToken(userName + Math.random()); out.println("OK"); } else { //data.setResult("NO"); out.println("NO"); } } else { //data.setResult("NON"); out.println("NON"); } %>
url为servlet
//构造url var url = "http://192.168.191.1:8080/OnlineMusicWebsite/servlet/loginServlet.do?time=" + new Date();
loginServlet.do
package com.recommendation.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.sql.ResultSet; import java.sql.SQLException; import com.fasterxml.jackson.databind.ObjectMapper; import com.recommendation.db.DBBean; import com.recommendation.management.UserData; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class loginServlet extends HttpServlet { public loginServlet() { super(); } // 读取客户端传过来的json数据,在这里没有用到 private String readJSONStringFromRequestBody(HttpServletRequest request) { StringBuffer json = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { json.append(line); } } catch (Exception e) { System.out.println("Error reading JSON string: " + e.toString()); } return json.toString(); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String json = readJSONStringFromRequestBody(request); // 得到客户端的数据 String users = request.getParameter("data"); System.out.println("users: " + users); // 解析json ObjectMapper mapper = new ObjectMapper(); UserData userData = mapper.readValue(users, UserData.class); // 用户名,密码 String userName = userData.getUserName(); String userPassword = userData.getUserPassword(); response.addHeader("Access-Control-Allow-Origin", "*"); // ajax跨域 response.setContentType("json;charset=UTF-8"); PrintWriter out = response.getWriter(); try { response.setContentType("json"); response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); // 连接数据库 DBBean db = new DBBean(); String sql = "select uPassword from users Where uName = '"+ userName +"' "; System.out.println(sql); ResultSet rs = db.executeQuery(sql); try { // 判断用户是否存在 if(rs.next()){ String uPassword = rs.getString("uPassword"); // 用户名,密码是否错误 if (uPassword.equals(userPassword)) { // data.setResult("OK"); // data.setToken(userName + Math.random()); out.println("OK"); } else { // data.setResult("NO"); out.println("NO"); } } else { // data.setResult("NON"); out.println("NON"); } } catch (SQLException e) { out.println("NON"); e.printStackTrace(); } } finally { out.flush(); out.close(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
4.跳转页面传参及中文乱码问题
String result = "{sName:'"+ sName +"', sSex:'"+ sSex +"', sAge:"+ sAge +", sRegion:'"+ sRegion +"', sFun:" + sFun +"}";
a页面:
self.location=encodeURI("singerSingle.jsp?data="+JSON.stringify(result)+" ");
b页面:
$(function(){ var result = <%=new String(request.getParameter("data").getBytes("ISO8859-1"), "UTF-8")%>; var dataJson = eval( "("+ result + ")" ); var sName = dataJson.sName; var sSex = dataJson.sSex; var sAge = dataJson.sAge; var sRegion = dataJson.sRegion; var sFun = dataJson.sFun; });
5.上传文件
http://www.cnblogs.com/xing901022/p/3855613.html
使用fileupload组件上传文件,需要的jar包:commom-fileupload.jar和commom-io.jar。
form需要添加 enctype="multipart/form-data"。enctype设置表单的MIME编码,默认情况这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,(type="file")才能完整的传递文件数据,上传的是二进制数据。当提交表单里包含文件上传的时候,即Form的enctype属性值multipart/form-data时,后台是无法像普通表单那样通过request.getParameter来获取用户提交的数据的,取到的value值为空。
http://blog.csdn.net/lian_zhihui1984/article/details/6822201#
这时候,当然可以通过解析提交到服务器的数据流来得到数据了,但是这样不但麻烦而且容易出错。
最好的方式是使用第三方的jar包获取数据,这方面有很多现成的成熟优秀的jar包。最常用的时以下三个:
apache的commons-fileupload : http://commons.apache.org/fileupload/
O'Reilly的cos: http://www.servlets.com/cos/index.html
jspsmart的SmartUpload:官方不提供下载了,google搜吧。
其中,据评测效率最高的是COS,最慢的是SmartUpload;最常用的是common-upload;文件太大时SmartUpland会崩溃。
1. common-upload示例代码:
// 判断enctype属性是否为multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // 当上传文件太大时,因为虚拟机能使用的内存是有限的,所以此时要通过临时文件来实现上传文件的保存 // 此方法是设置是否使用临时文件的临界值(单位:字节) factory.setSizeThreshold(yourMaxMemorySize); // 与上一个结合使用,设置临时文件的路径(绝对路径) factory.setRepository(yourTempDirectory); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // 设置上传内容的大小限制(单位:字节) upload.setSizeMax(yourMaxRequestSize); // Parse the request List<?> items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { //如果是普通表单字段 String name = item.getFieldName(); String value = item.getString(); ... } else { //如果是文件字段 String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); ... // Process a file upload if (writeToFile) { File uploadedFile = new File(...); item.write(uploadedFile); } else { InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close(); } } }
2. cos示例代码:
// 设置大小限制(单位:字节) final int permitedSize = 314572800; try { String type = ""; String name = ""; String originalFilename = ""; String extension1 = ""; String extension2 = ""; String filename = ""; //上传目录 String strDirectory = "files"; String uploadPath = request.getRealPath("//WEB-INF//"+strDirectory+"//"); // 获取句柄 MultipartRequest multipartRequest = new MultipartRequest(request, uploadPath, permitedSize, "ISO-8859-1", new DefaultFileRenamePolicy()); // 取得文件 Enumeration files = multipartRequest.getFileNames(); // 取得文件详细信息 while (files.hasMoreElements()) { name = (String)files.nextElement(); type = multipartRequest.getContentType(name); filename = multipartRequest.getFilesystemName(name); originalFilename = multipartRequest.getOriginalFileName(name); File currentFile = multipartRequest.getFile(name); ... } // 取得其它非文件字段 Enumeration params = multipartRequest.getParameterNames(); while (params.hasMoreElements()) { String name = (String)params.nextElement(); String value = multi.getParameter(name); ... } } catch (Exception exception) { response.sendError(response.SC_METHOD_NOT_ALLOWED); } finally { if (out != null) {out.close();} }
3. SmartUpload示例代码:
smartupload mysmartupload = new smartupload(); mysmartupload.initialize(this.getServletConfig(), request, response); // 设置文件大小限制(单位:字节) mysmartupload.setMaxFileSize(10000000); // 设置总上传数据总大小(单位:字节) mysmartupload.setTotalMaxFileSize(20000000); // 设置允许的文件扩展名 mysmartupload.setAllowedFilesList("jpg,png,gif,bmp,jpeg"); // 设置不允许的文件扩展名 mysmartupload.setDeniedFilesList("exe,bat,jsp,htm,html,,"); try { mysmartupload.upload(); } catch (smartuploadException e1) { e1.printStackTrace(); } // 读取其它非文件上传字段 com.jspsmart.upload.Request req = mysmartupload.getRequest(); String title = req.getParameter("dest"); // 保存文件 for (int i = 0; i < mysmartupload.getFiles().getCount(); i++) { com.jspsmart.upload.File file = mysmartupload.getFiles().getFile(i); if (file.isMissing()) continue; try { file.saveAs("yourSavePath" + file.getFileName()); } catch (smartuploadException e) { e.printStackTrace(); } }
http://www.cnblogs.com/2050/p/3191744.html
7. h5 audio
https://segmentfault.com/a/1190000007332028
http://www.open-open.com/lib/view/open1407401112973.html
http://zhaomenghuan.github.io/#!/blog/20160529
https://segmentfault.com/a/1190000004263182
9.使用HTML5中audio标签时,在播放音频文件时无法播放,请求音乐路径中包含中文字符,而且由于是在tomcat服务器,通过get方式请求到的播放页面,中文到了服务器后台就变成了乱码。解决
打开tomcat服务器的conf文件夹,打开server.xml文件,在Connector中加入URIEncoding参数,如下:
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
然后保存,重启服务器。
10.
document.form1.action="servlet/singerEditImageServlet.do?sNumber="+<%=sNumber%>+" ";
这里不能这样写(加个空格) sNumber= " ,传过去的数据就会是这样的" 2"。
11.
url中参数有Json数据
<% netMusicData music = new netMusicData(); JSONObject json = JsonHelper.toJSON(music); %> <a id="detail" href="pages/MusicManagement/netmusicSingleDetail.html?netmusicData=<%=json.toString() %>" style="width:70px;">查看详情</a>
会发现到netmusicSingleDetail.html页面得到的netmusicData值是{,因为json数据是:{"mNumber":"2","uName":"dfds","uNumber":"8","mCredit":"55","mPlayNum":"0","mCoverPath":"upload/net/8/1c80b1a3372057f9_mh1473955715103.jpg","mIntroduction":"gh","mCollectNum":"0","mName":"gh","mDate":"Mon Jan 02 2017 15:49:52 GMT 0800 (CST)","mPath":"upload/net/8/innocence 艾薇儿.mp3"}
引号的问题导致取到的只有 {
解决办法:将所有的""替换为''
<% JSONObject json = JsonHelper.toJSON(music); String str = json.toString().replaceAll( "\"", "\'");; %> <a id="detail" href="pages/MusicManagement/netmusicSingleDetail.html?netmusicData=<%=str %>" style="width:70px;">查看详情</a>