Category Archives: Java

Android入門–Socket通信のサンプルコード

javaコード:
Socket socket = new Socket(“172.17.2.11”, 10000);
OutputStream os = socket.getOutputStream();
PrintWriter cft = new PrintWriter(os);
cft.write(“connect to server”);
cft.flush();
socket.shutdownOutput();
socket.close();

Java入門–ウェブサーバーにファイルをPOSTする方法

Javaコード:
public static String doPostFile(String reqUrl, String fileUrl) {
return doPostFile(reqUrl, fileUrl, ENCODEING);
}

private static String doPostFile(String reqUrl, String fileUrl, String encoding) {
HttpURLConnection urlcont = null;
String responseContent = null;
try {
URL url = new URL(reqUrl);

urlcont = (HttpURLConnection) url.openConnection();
urlcont.setRequestMethod(“POST”);
urlcont.setConnectTimeout(CONNECTTIMEOUT);
urlcont.setDoOutput(true);
urlcont.setRequestProperty(“Content-type”,”application/x-java-serialized-object”);

File file = new File(fileUrl);
InputStream ins = new FileInputStream(file);
byte[] data = IOUtils.toByteArray(ins);

urlcont.getOutputStream().write(data, 0, data.length);
urlcont.getOutputStream().flush();
urlcont.getOutputStream().close();

InputStream in = urlcont.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(in,
ENCODEING));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty(“line.separator”);
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
rd.close();
in.close();
} catch (IOException e) {
System.err.println(“ネットワークエラー”);
logger.info(“—ネットワークエラー”);
} finally {
if (urlcont != null) {
urlcont.disconnect();
}
}
return responseContent;
}
}

Java入門–finalクラス(class)の使い方

Javaコード
package com.startnews24.itdemo;
class Sample {
String name;
int a;

void m() {
System.out.println(“m() function is called”);
}

}
final class Daiwa {
int i = 5, j = 7;
Sample cf = new Sample();

void g() {
System.out.println(“g() function is called”);
}

}
public class DemoClas {
public static void main(String[] args) {
Daiwa obj=new Daiwa();
obj.g();
obj.i=40;
obj.j++;

}

}

実行結果

g() function is called

Java5入門–@Overrideオーバーライドの使い方

Javaコード:
public class CFTInterceptor extends AnnotationValidationInterceptor {

@Override
public String intercept(ActionInvocation invocation) throws Exception, IllegalStateException {
//Javaコード
final DemoDispatchAction action=(DemoDispatchAction)invocation.getAction();
中略
return super.intercept(invocation);

}
}

Java学習–日付・時間の表示GMTとUTCの変換方法

Javaコード
package koko;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class CftTimeZone {

public static void main(String[] args) {
try {
String ts = “2016-10-23T17:15:44.000Z”;
System.out.println(“ts = ” + ts);
ts = ts.replace(“Z”, ” UTC”);
System.out.println(“ts = ” + ts);
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd’T’HH:mm:ss.SSS Z”);

Date dt = sdf.parse(ts);

TimeZone tz = sdf.getTimeZone();
Calendar c = sdf.getCalendar();
//System.out.println(“Display name: ” + tz.getDisplayName());
System.out.println(getString(c));
} catch (ParseException pe) {
System.out.println(“Error offset: ” + pe.getErrorOffset());
pe.printStackTrace();
}
}

private static String getString(Calendar c) {
StringBuffer result = new StringBuffer();
result.append(c.get(Calendar.YEAR));
result.append(“-“);
result.append((c.get(Calendar.MONTH) + 1));
result.append(“-“);
result.append(c.get(Calendar.DAY_OF_MONTH));
result.append(” “);
result.append(c.get(Calendar.HOUR_OF_DAY));
result.append(“:”);
result.append(c.get(Calendar.MINUTE));
result.append(“:”);
result.append(c.get(Calendar.SECOND));
return result.toString();
}
}

実行結果
ts = 2016-10-23T17:15:44.000Z
ts = 2016-10-23T17:15:44.000 UTC
2016-10-23 17:15:44

Struts2でファイルアップロードをする方法

1.一つファイルアップロード
package com.ljcft.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction1 extends ActionSupport implements Serializable {

private File image;
private String imageFileName;
private String imageContentType;

public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageContentType() {
return imageContentType;
}
public void setImageContentType(String imageContentType) {
this.imageContentType = imageContentType;
}
public String execute(){
System.out.println(imageContentType);
try {

// System.out.println(imageFileName);
ServletContext sc = ServletActionContext.getServletContext();
String storePath = sc.getRealPath(“/files”);
// OutputStream out = new FileOutputStream(storePath+”\\”+imageFileName);
// InputStream in = new FileInputStream(image);
// byte b[] = new byte[1024];
// int len = -1;
// while((len=in.read(b))!=-1){
// out.write(b, 0, len);
// }
// out.close();
// in.close();
FileUtils.copyFile(image, new File(storePath,imageFileName));
ActionContext.getContext().put(“message”, “ファイルアップ成功!”);
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
}
2.複数ファイルアップロード
package cn.ljcft.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction2 extends ActionSupport implements Serializable {

private File[] images;
private String[] imagesFileName;
private String[] imagesContentType;

public File[] getImages() {
return images;
}

public void setImages(File[] images) {
this.images = images;
}

public String[] getImagesFileName() {
return imagesFileName;
}
public void setImagesFileName(String[] imagesFileName) {
this.imagesFileName = imagesFileName;
}
public String[] getImagesContentType() {
return imagesContentType;
}
public void setImagesContentType(String[] imagesContentType) {
this.imagesContentType = imagesContentType;
}
public String execute(){
try {
if(images!=null&&images.length>0){
ServletContext sc = ServletActionContext.getServletContext();
String storePath = sc.getRealPath(“/files”);
for(int i=0;i<images.length;i++)
FileUtils.copyFile(images[i], new File(storePath,imagesFileName[i]));
}
ActionContext.getContext().put(“message”, “ファイルアップロード成功!”);
return SUCCESS;
} catch (Exception e) {
e.printStackTrace();
return ERROR;
}
}
}

3.jsp画面
<body>
<form action=”${pageContext.request.contextPath}/upload/upload2.action” method=”post” enctype=”multipart/form-data”>
ファイル1:<input type=”file” name=”images”/><br/>
ファイル2:<input type=”file” name=”images”/><br/>
<input type=”submit” value=”アップロード”/>
</form>
</body>

4.struts.xml設定
<constant name=”struts.multipart.maxSize” value=”52428800″></constant>
<package name=”upload” namespace=”/upload” extends=”mypackage”>
<action name=”upload1″ class=”cn.ljcft.action.UploadAction1″ method=”execute”>
<result name=”success”>/success.jsp</result>
</action>
<action name=”upload2″ class=”com.ljcft.action.UploadAction2″ method=”execute”>
<result name=”success”>/success.jsp</result>
</action>
</package>

Struts2.3.16.3基本環境を構築する方法

1.必要なjar
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
struts2-core-2.3.16.3.jar
xwork-core-2.3.16.3.jar
2.web.xmlの設定
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app id=”WebApp_9″ version=”2.4″ xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>

<display-name>Struts Blank</display-name>

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

</web-app>

3.struts.xmlの設定
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.3//EN”
“http://struts.apache.org/dtds/struts-2.3.dtd”>

<struts>

<constant name=”struts.enable.DynamicMethodInvocation” value=”false” />
<constant name=”struts.devMode” value=”true” />

<package name=”default” namespace=”/” extends=”struts-default”>

<default-action-ref name=”index” />

<global-results>
<result name=”error”>/error.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping exception=”java.lang.Exception” result=”error”/>
</global-exception-mappings>

<action name=”index”>
<result type=”redirectAction”>
<param name=”actionName”>Welcome</param>
<param name=”namespace”>/startne</param>
</result>
</action>
</package>

<include file=”startne.xml”/>

<!– Add packages here –>

</struts>

startne.xml
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!DOCTYPE struts PUBLIC
“-//Apache Software Foundation//DTD Struts Configuration 2.0//EN”
“http://struts.apache.org/dtds/struts-2.0.dtd”>

<struts>

<package name=”startne” namespace=”/startne” extends=”default”>

<action name=”Welcome” class=”startne.Welcome”>
<result>/startne/Welcome.jsp</result>
</action>

<action name=”Login_*” method=”{1}” class=”startne.Login”>
<result name=”input”>/startne/Login.jsp</result>
<result type=”redirectAction”>Menu</result>
</action>

<action name=”*” class=”startne.DemoSupport”>
<result>/startne/{1}.jsp</result>
</action>

<!– Add actions here –>
</package>
</struts>

Javaでexcelファイルを作成するサンプル

Javaコード:
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelOp{
public static void main(String[] args){
XSSFWorkbook workbook = new XSSFWorkbook();

workbook.createSheet(“tanhen”);

FileOutputStream out = null;
try{
out = new FileOutputStream(“precdf.xlsx”);
workbook.write(out);
}catch(IOException e){
System.out.println(e.toString());
}finally{
try {
out.close();
}catch(IOException e){
System.out.println(e.toString());
}
}
}
}

Struts2でServletContextを取得する方法

1. ServletActionContext
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport{

public String execute() throws Exception {

ServletContext context = ServletActionContext.getServletContext();

return SUCCESS;

}

}

2. ServletContextAware

import javax.servlet.ServletContext;
import org.apache.struts2.util.ServletContextAware;
import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction
extends ActionSupport implements ServletContextAware{

ServletContext context;

public String execute() throws Exception {

return SUCCESS;

}

public void setServletContext(ServletContext context) {
this.context = context;
}
}

Java開発–Map(List)オブジェクトからJSON文字列へ変換する

JAVAコード

1.List–>JSON文字列
@SuppressWarnings(“rawtypes”)
public static String simpleListToJsonStr(List<?> list,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
if(list==null||list.size()==0){
return “[]”;
}
String jsonStr = “[“;
for (Object object : list) {
jsonStr += simpleObjectToJsonStr(object,claList)+”,”;
}
jsonStr = jsonStr.substring(0,jsonStr.length()-1);
jsonStr += “]”;
return jsonStr;
}

2.Map–>JSON文字列

public static String simpleMapToJsonStr(Map<?,?> map){
if(map==null||map.isEmpty()){
return “null”;
}
String jsonStr = “{“;
Set<?> keySet = map.keySet();
for (Object key : keySet) {
jsonStr += “\””+key+”\”:\””+map.get(key)+”\”,”;
}
jsonStr = jsonStr.substring(0,jsonStr.length()-1);
jsonStr += “}”;
return jsonStr;
}