本文目錄一覽:
- 1、jsp,java串口通信的問題
- 2、jsp和Java後台數據如何交互
- 3、java開發的信息系統里,jsp與java文件是怎麼傳遞數據的啊?
- 4、spring 中如何實現jsp與java的交互
- 5、jsp與java文件怎麼傳遞數據?
jsp,java串口通信的問題
可以,使用comm,jar
class SerialExample {
public static void main(String[] args) {
//TO DO: Add your JAVA codes here
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
SerialBean SB = new SerialBean(2);//設置端口號2
String Msg = “AD 01 0D”;//發送命令
SB.Initialize(9600);//設置波率
SB.WritePort(Msg);//發送命令
/* for (int i = 5; i 10; i++) {
System.out.println( SB.ReadPort(3));//設置讀取個數
}
*/
String readdata = SB.ReadPort(“0D”,4000);//讀取以OD結束的數據,4000ms沒有數據就返回空
if (readdata.length() 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() 1 state) {//如果沒有讀到數據
readdata = SB.ReadPort(“0D”,4000);
System.out.println(readdata);
if (System.currentTimeMillis() – curTime serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println(“readdaa:” + state);
System.out.println(System.currentTimeMillis() – curTime);
}
if (!state) {
System.out.println(“數據讀取超時”);
}
SB.ClosePort();//關閉連接
}
}
public class SerialBuffer {
Convents cv = new Convents();
private String Content = “”;
private String CurrentMsg, TempContent;
private boolean available = false;
private int LengthNeeded = 1;
String str = “”;
byte b;
/**
*
* This function returns a string with a certain length from the incoming
* messages.
*
* @param Length The length of the string to be returned.
*
*/
public synchronized String GetMsg(int Length) {
LengthNeeded = Length;
long timeout=2000;
long curtime=System.currentTimeMillis();
notifyAll();
if (LengthNeeded Content.length()) {
available = false;
while (available == false) {
try {
if(System.currentTimeMillis()-curtimetimeout) wait();
} catch (InterruptedException e) {
}
}
}
CurrentMsg = Content.substring(0, LengthNeeded);
TempContent = Content.substring(LengthNeeded);
Content = TempContent;
LengthNeeded = 1;
notifyAll();
return CurrentMsg;
}
public synchronized String GetMsg(String endstring,long timeout) {
LengthNeeded =Content.indexOf(endstring);
notifyAll();
if (LengthNeeded 0) {
available = false;
while (available == false) {
try {
wait(timeout);
available=true;
} catch (InterruptedException e) {
}
}
return “”;
}
if (LengthNeeded 0) {
CurrentMsg = Content.substring(0, LengthNeeded+endstring.length());
TempContent = Content.substring(LengthNeeded+endstring.length());
Content = TempContent;
}
LengthNeeded = -1;
notifyAll();
return CurrentMsg;
}
public synchronized void PutChar(int c) {
Content = Content.concat(cv.byteToHexString(c));
if (LengthNeeded Content.length() Content.length() 0) {
available = true;
}
notifyAll();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;
/**
*
* @author Jason
*/
import java.io.*;
import java.util.*;
import javax.comm.*;
import common.code.Convents;
public class SerialBean {
Convents cv=new Convents();
String PortName = “”;
CommPortIdentifier portId = null;
SerialPort serialPort = null;
OutputStream out;
InputStream in;
SerialBuffer SB;
ReadSerial RT;
int rate=9600;
String endstring =””;
long timeout=2000;
public SerialBean(int PortID) {
PortName = “COM” + PortID;
}
public int Initialize(int rate) {
int InitSuccess = 1;
int InitFail = -1;
try {
portId = CommPortIdentifier.getPortIdentifier(PortName);
try {
serialPort = (SerialPort) portId.open(“Serial_Communication”, 2000);
} catch (PortInUseException e) {
return InitFail;
}
//Use InputStream in to read from the serial port, and OutputStream
//out to write to the serial port.
try {
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} catch (IOException e) {
return InitFail;
}
//Initialize the communication parameters to 9600, 8, 1, none.
try {
serialPort.setSerialPortParams(rate,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {
return InitFail;
}
} catch (NoSuchPortException e) {
return InitFail;
}
SB = new SerialBuffer();
RT = new ReadSerial(SB, in);
RT.start();
return InitSuccess;
}
public String ReadPort(int Length) {
String Msg;
Msg = SB.GetMsg(Length);
return Msg;
}
public String ReadPort(String endstring,long timeout) {
String Msg;
Msg = SB.GetMsg(endstring,timeout);
return Msg;
}
public void WritePort(String Msg) {
try {
out.write(cv.hexStringToByte(Msg));
} catch (IOException e) {
}
}
public void ClosePort() {
serialPort.close();
}
}
package common.serial;
import java.io.*;
public class ReadSerial extends Thread {
private SerialBuffer ComBuffer;
private InputStream ComPort;
char[] ch;
public ReadSerial(SerialBuffer SB, InputStream Port) {
ComBuffer = SB;
ComPort = Port;
}
@Override
public void run() {
int c;
try {
while (true) {
c=ComPort.read();
ComBuffer.PutChar(c);
}
} catch (IOException e) {
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.serial;
/**
*
* @author Administrator
*/
public class PortOpreate {
private String sendtxt=””;
private String recivetxt=””;
private int comid = 1;
private int comrate = 9600;
private int timeout = 4000;
private long waittime = 13000;
private String endtxt = “0D”;
private boolean pstate=false;
private String massage=””;
public void PortOpreate(boolean hasreturn) {
long curTime = System.currentTimeMillis();
long serialtime = getWaittime();
boolean state = true;
int t=0;
SerialBean SB = new SerialBean(getComid());//設置端口號2
t=SB.Initialize(getComrate());//設置波率
if(t0){
SB.WritePort(getSendtxt());//發送命令
if (hasreturn) {
String readdata = SB.ReadPort(getEndtxt(), getTimeout());//讀取以OD結束的數據,4000ms沒有數據就返回空
if (readdata.length() 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() 1 state) {//如果沒有讀到數據
readdata = SB.ReadPort(getEndtxt(), getTimeout());
System.out.println(readdata);
if (System.currentTimeMillis() – curTime serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println(“readdaa:” + state);
System.out.println(System.currentTimeMillis() – curTime);
}
if (!state) {
System.out.println(“數據讀取超時”);
setMassage(“數據讀取超時”);
}
setRecivetxt(readdata);
setPstate(state);
}
SB.ClosePort();//關閉連接
}else{
System.out.println(“端口號出現錯誤”);
setMassage(“端口號出現錯誤”);
}
}
/**
* @return the sendtxt
*/
public String getSendtxt() {
return sendtxt;
}
/**
* @param sendtxt the sendtxt to set
*/
public void setSendtxt(String sendtxt) {
this.sendtxt = sendtxt;
}
/**
* @return the recivetxt
*/
public String getRecivetxt() {
return recivetxt;
}
/**
* @param recivetxt the recivetxt to set
*/
public void setRecivetxt(String recivetxt) {
this.recivetxt = recivetxt;
}
/**
* @return the comid
*/
public int getComid() {
return comid;
}
public void setComid(int comid) {
this.comid = comid;
}
public int getComrate() {
return comrate;
}
public void setComrate(int comrate) {
this.comrate = comrate;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public long getWaittime() {
return waittime;
}
public void setWaittime(long waittime) {
this.waittime = waittime;
}
public String getEndtxt() {
return endtxt;
}
public void setEndtxt(String endtxt) {
this.endtxt = endtxt;
}
public boolean isPstate() {
return pstate;
}
public void setPstate(boolean pstate) {
this.pstate = pstate;
}
public String getMassage() {
return massage;
}
public void setMassage(String massage) {
this.massage = massage;
}
}
package common.serial;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class PortOperatorServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
PrintWriter out = response.getWriter();
try {
long curTime = System.currentTimeMillis();
long serialtime = 8000;
boolean state = true;
String Msg = “AD 01 0D”;//發送命令
SerialBean SB = new SerialBean(10);//設置端口號2
SB.Initialize(9600);//設置波率
SB.WritePort(Msg);//發送命令
/* for (int i = 5; i 10; i++) {
System.out.println( SB.ReadPort(3));//設置讀取個數
}
*/
String readdata = SB.ReadPort(“0D”,4000);//讀取以OD結束的數據
if (readdata.length() 0) { //System.out.println(readdata.length());//如果有讀到數據
System.out.println(readdata);//如果有讀到數據
}
while (readdata.length() 1 state) {//如果沒有讀到數據
readdata = SB.ReadPort(“0D”,4000);
System.out.println(readdata);
out.println(readdata);
if (System.currentTimeMillis() – curTime serialtime) {
state = false;//設置讀取錯誤超時
}
System.out.println(“readdaa:” + state);
System.out.println(System.currentTimeMillis() – curTime);
}
if (!state) {
System.out.println(“數據讀取超時”);
out.println(“數據讀取超時”);
}
SB.ClosePort();//關閉連接
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
public String getServletInfo() {
return “Short description”;
}
}
package common.code;
public final class Convents {
public final static char[] BToA = “0123456789abcdef”.toCharArray();
/**
* 把16進制字符串轉換成位元組數組A1 01 0D
* @param hex
* @return
*/
public byte[] hexStringToByte(String hex) {
String str[] = hex.split(” “);
int len = str.length;
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i len; i++) {
result[i] = (byte) (toByte(str[i].charAt(0)) * 16 + toByte(str[i].charAt(1)));
}
return result;
}
private static byte toByte(char c) {
byte b = (byte) (“0123456789ABCDEF”.indexOf(c));
return b;
}
/**
* 把位元組數組轉換成16進制字符串
* @param bArray
* @return
*/
public String byteToHexString(int b){
String st=””;
st=Integer.toHexString(b);
if (st.length() 2) {
st=”0″+Integer.toHexString(b).toUpperCase()+” “;
} else {
st=Integer.toHexString(b).toUpperCase()+” “;
}
return st;
}
public String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i bArray.length; i++) {
sTemp = Integer.toHexString(bArray[i]).toUpperCase();
}
return sb.toString();
}
}
jsp和Java後台數據如何交互
%
String path = request.getContextPath();
%
獲取jsp所在工程的名稱
var ids = new Array();
$.ajax({
type : “POST”,
contentType : ‘application/json’,
url : ‘%=path%/ui/product/havePsmPackage’,
data:JSON.stringify(ids),
async :false,
dataType : “json”,
success : function(data) {
},
error:function(){
}
});
1、前台如果傳的是一個集合,後台可以使用參數 @RequestBody ListString ids 來接收
2、如果前台是這種傳值方式 data:{“name”:name,”id”:id},
那後台可以通過創建一個字段名稱對應的實體類來接收
或者使用String name = request.getParameter(“name”)的方式來接收
3、如果ajax選擇的GET方法,那後台方法的字段名稱和url的入參名稱保持一致就能接收到數據了
4、window.location.href=”%=path%/ui/psmpackage/toPsmPackageList”;
這是跳轉到新頁面的方法
@RequestMapping(value = “/toPsmPackageList”)
public String toPsmPackageList(HttpServletRequest request) {
return “psmPackage/psmPackageList”;
}
這是後台的接受方式,返回的是對應jsp的文件夾和文件名
頁面跳轉的方法不需要@ResponseBody註解,而獲取返回值的方法則一定要加,不然獲取不到返回值
5、window.open(url); 可以在瀏覽器上新開一個頁面。對應的是window.close();
6、如何將數據帶到新增的頁面
第一:第一個頁面通過
window.location.href=”%=path%/ui/product/condition?lineCode=”+lineCode+”typeCode=”+typeCode;傳值
在新頁面可以通過var lineCode = ‘%=(String)request.getParameter(“lineCode”)%’這種方式來取值
第二:後台代碼這樣處理request.setAttribute(“product”, result);
input name=”id” type=”text” value=”${product.id}” /
${}來取值。
java開發的信息系統里,jsp與java文件是怎麼傳遞數據的啊?
jsp與java文件傳遞數據可以使用Servlet類來傳遞,jsp將數據存入到request對象中,Servlet類獲取這個request對象,並將數據取出。
示例代碼如下:
JSP代碼:%@ page language=”java” import=”java.util.*” pageEncoding=”UTF-8″%
!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
html
head
titleDemo/title
/head
body
form action=”/demoServlet” method=”post”
input type=”text” name=”name”/
input type=”submit” value=”提交”/
/form
/body
/html
Servlet代碼:
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter(“name”);//獲取jsp頁面輸入的參數
System.out.println(name);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
表單提交之後,調用Servlet類的方法,通過request對象獲取jsp頁面傳入的參數值,實現數據的傳遞。
spring 中如何實現jsp與java的交互
spring中利用mvc框架就可以實現jsp和java交互了。
以下用spring mvc輸出hello world為例來說明:
一、項目依賴的jar包:
1.Spring框架依賴的jar包:
日誌:commons-logging-1.1.3.jar;
JSTL支持:jakarta-taglibs-standard-1.1.2中的jstl.jar和standard.jar;
2.Spring的jar包:
spring-framework-3.2.5.RELEASE/libs中的jar包(這裡為了方便我直接把全部都複製過去了);
把以上的jar包全部複製到項目的WebContent/WEB-INF/lib目錄中。
二、在/WEB-INF中添加web.xml文件,文件內容如下:
?xml version=”1.0″ encoding=”UTF-8″?
web-app xmlns:xsi=”” xmlns=”” xmlns:web=”” xsi:schemaLocation=” ” id=”WebApp_ID” version=”3.0″
display-nameSpringMVCLesson/display-name
servlet
servlet-nameSpringMVCLesson/servlet-name
servlet-classorg.springframework.web.servlet.DispatcherServlet/servlet-class
init-param
param-namecontextConfigLocation/param-name
param-valueclasspath:springservlet-config.xml/param-value
/init-param
load-on-startup1/load-on-startup!– load-on-startup必須放在最後 —
/servlet
!– Spring MVC配置文件結束 —
servlet-mapping
servlet-nameSpringMVCLesson/servlet-name
url-pattern//url-pattern
/servlet-mapping
/web-app
三、springservlet-config.xml文件配置:
在項目中新建一個resources的Source Folder文件夾,並添加springservlet-config.xml文件。
?xml version=”1.0″ encoding=”UTF-8″?
beans xmlns=””
xmlns:xsi=””
xmlns:p=””
xmlns:context=””
xmlns:util=””
xmlns:mvc=””
xsi:schemaLocation=”
”
!– 默認的註解映射的支持 —
mvc:annotation-driven/
!– 如果當前請求為「/」時,則轉發到「/helloworld/index」 —
mvc:view-controller path=”/” view-name=”forward:/helloworld/index”/
!– 靜態資源映射 —
mvc:resources mapping=”/js/**” location=”/WEB-INF/js/” /
mvc:resources mapping=”/css/**” location=”/WEB-INF/css/” /
mvc:resources mapping=”/fonts/**” location=”/WEB-INF/fonts/” /
mvc:resources mapping=”/plugins/**” location=”/WEB-INF/plugins/” /
mvc:resources mapping=”images/**” location=”/WEB-INF/images/” /
!– 當上面要訪問的靜態資源不包括在上面的配置中時,則根據此配置來訪問 —
mvc:default-servlet-handler/
!– 開啟controller註解支持 —
!– use-default-filters=”false” 只掃描指定的註解 —
context:component-scan base-package=”com.demo.web.controllers” use-default-filters=”false”
context:include-filter type=”annotation” expression=”org.springframework.stereotype.Controller”/
/context:component-scan
!– 視圖解析器 —
bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”
property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView”/
property name=”contentType” value=”text/html”/
property name=”prefix” value=”/WEB-INF/views/”/
property name=”suffix” value=”.jsp”/
/bean
/beans
mvc:annotation-driven/ 開啟註解映射支持,它是為了簡化配置的縮寫形式,它相當於以下2個配置:
bean class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping”/
bean class=”org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter”/
由於我們在web.xml文件裏面配置的是攔截所有的請求到該servlet,所以我們在這裡要對靜態資源文件映射作一下配置,否則請求這些資源文件會返回404:
!– 靜態資源映射 —
mvc:resources mapping=”/js/**” location=”/WEB-INF/js/” /
mvc:resources mapping=”/css/**” location=”/WEB-INF/css/” /
mvc:resources mapping=”/fonts/**” location=”/WEB-INF/fonts/” /
mvc:resources mapping=”/plugins/**” location=”/WEB-INF/plugins/” /
mvc:resources mapping=”images/**” location=”/WEB-INF/images/” /
!– 當上面要訪問的靜態資源不包括在上面的配置中時,則根據此配置來訪問 —
mvc:default-servlet-handler/
開啟Controller註解支持,並配置只掃描指定包下面的Controller:
context:component-scan base-package=”com.demo.web.controllers” use-default-filters=”false”
context:include-filter type=”annotation” expression=”org.springframework.stereotype.Controller”/
/context:component-scan
配置視圖解析器,並指定視圖所在的文件夾:
bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”
property name=”viewClass” value=”org.springframework.web.servlet.view.JstlView”/
property name=”contentType” value=”text/html”/
property name=”prefix” value=”/WEB-INF/views/”/
property name=”suffix” value=”.jsp”/
/bean
添加HelloWorldController,在項目中新建一個web的Source Folder文件夾,並在文件夾下面添加com.demo.web.controllers包,在包中添加一個HelloWorldController類,類中內容如下:
package com.demo.web.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = “/helloworld”)
public class HelloWorldController {
@RequestMapping(value=”/index”, method = {RequestMethod.GET})
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject(“message”, “Hello World!”);
modelAndView.setViewName(“index”);
return modelAndView;
}
}
其中@Controller 註解把該class指定為controller,controller 上的@RequestMapping 註解的 value值指定該controller所映射的請求。
方法上的@RequestMapping 註解指定該方法為一個action,value 值指定該action所映射的請求,method 中的RequestMethod.GET指定該action只接受get請求。
ModelAndView 中的setViewName指定了該action所對應的視圖名稱,解析視圖時會在springservlet-config.xml文件指定的視圖文件夾中尋找對應的視圖。
添加視圖,在項目/WEB-INF文件夾下新建一個views文件夾,並在views中添加index.jsp視圖,視圖內容如下:
%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%
!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “”
html
head
meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″
titleInsert title here/title
/head
body
${message}
/body
/html
運行項目輸出結果:
jsp與java文件怎麼傳遞數據?
可以使用Servlet類來傳遞
返回一個RequestDispatcher對象
該對象的forward()方法用於轉發請求
RequestDispatcher getRequestDispatcher(String path)
例如:request.getRequestDispatcher(「url」),forward(request,response);
設置追加請求中所需的屬性參數
Void setAttribute(「屬性名」,」屬性值」)
例如:request,setAttribute(「username」,」administrator」);
用於獲取請求中攜帶的屬性參數
Object getAttribute(「屬性名」)
例如:String usernam=(String)request.getAttribute(「username」);
響應對象response方法:response.sendRedirect(「url」);
用於充定向一個新的URL地址
經常配合使用session會話對象進行所需屬性參數的傳遞
例如:session,setAttribute(「username」,」administrator」);
session.serAttribute(「password」,」123456」);
…
If()username!=null{
Out.println(「歡迎你:」+username.toString()
}
2.轉發和重定向的區別
分別從5個點進行劃分區別
(1)URl變化:轉發不會發生變化,重定向會改變地址欄的URL
(2)重新發出請求:轉發不會,從頭至尾只有一次請求,重定向會發起兩次請求
(3)是否攜帶請求:轉發會攜帶request相關信息,重定向不會攜帶,所以會丟失
(4)目標URl要求:轉發只能跳轉WEB項目下的目標文件,重定向可跳轉任意URL
(5)行為區別:轉發時服務器端的行為,重定向時客戶端行為
3.四中常用的跳轉方式
(1)後台發起轉發請求
request.getRequestDispatcher(「index.jsp」).forward(request,response);
(2)後台發起重定向
Response.sendRedirect(「indec.jsp」);
!–3.jsp標籤跳轉 相當於前端的轉發–
jsp:forward page=」index.jsp」
jsp:param value=」admin」 name=」user name」
jsp:param value=」123456」 name=」password」
/jsp:forward
!–4.超鏈接跳轉 get請求方式跳轉頁面 類似於前段的重定向–
a href=」index.jsp?username=adminadminpassword=123456」跳轉index.jsp/a
原創文章,作者:O46UP,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/129502.html