Category Archives: Java

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

Java開発–オブジェクトからJSON文字列へ変換する方法

JAVAコード:
public static String simpleObjectToJsonStr(Object obj,List<Class> claList) throws IllegalArgumentException, IllegalAccessException{
if(obj==null){
return “null”;
}
String jsonStr = “{“;
Class<?> cla = obj.getClass();
Field fields[] = cla.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
if(field.getType() == long.class){
jsonStr += “\””+field.getName()+”\”:”+field.getLong(obj)+”,”;
}else if(field.getType() == double.class){
jsonStr += “\””+field.getName()+”\”:”+field.getDouble(obj)+”,”;
}else if(field.getType() == float.class){
jsonStr += “\””+field.getName()+”\”:”+field.getFloat(obj)+”,”;
}else if(field.getType() == int.class){
jsonStr += “\””+field.getName()+”\”:”+field.getInt(obj)+”,”;
}else if(field.getType() == boolean.class){
jsonStr += “\””+field.getName()+”\”:”+field.getBoolean(obj)+”,”;
}else if(field.getType() == Integer.class||field.getType() == Boolean.class
||field.getType() == Double.class||field.getType() == Float.class
||field.getType() == Long.class){
jsonStr += “\””+field.getName()+”\”:”+field.get(obj)+”,”;
}else if(field.getType() == String.class){
jsonStr += “\””+field.getName()+”\”:\””+field.get(obj)+”\”,”;
}else if(field.getType() == List.class){
String value = simpleListToJsonStr((List<?>)field.get(obj),claList);
jsonStr += “\””+field.getName()+”\”:”+value+”,”;
}else{
if(claList!=null&&claList.size()!=0&&claList.contains(field.getType())){
String value = ObjToJsonStrFunc(field.get(obj),claList);
jsonStr += “\””+field.getName()+”\”:”+value+”,”;
}else{
jsonStr += “\””+field.getName()+”\”:null,”;
}
}
}
jsonStr = jsonStr.substring(0,jsonStr.length()-1);
jsonStr += “}”;
return jsonStr;
}

Java入門–java.lang.string.splitの使い方

参考コード1:
String str=”Java base skill string split demo”;
String[] strarray=str.split(” “);
for (int i = 0; i < strarray.length; i++)
System.out.println(strarray[i]);
実行結果:
Java
base
skill
string
split
demo

参考コード2:
String str=”Java string split test”;
String[] strarray=str.split(” “,2);
for (int i = 0; i < strarray.length; i++)
System.out.println(strarray[i]);
実行結果:
Java
skill string split demo

参考コード3:
String str=”172.17.10.23″;
String[] strarray=str.split(“\\.”);
for (int i = 0; i < strarray.length; i++)
System.out.println(strarray[i]);
実行結果:
172
17
10
23

Java開発–@Documented アノテーションの使い方

参考コード:
package com.startnees24.pckd.documentedannotation ;
import java.lang.annotation.Documented ;
@PcDocumentedtAnnotation(key=”apple”,value=”itunecard”)
public class PcDocumentedtAnnotationDemo{

@PcDocumentedtAnnotation(key=”apple”,value=”itunecard”)
public String toString(){
return “this is easy @Documented demo” ;
}
};

@Documented
@interface PcDocumentedtAnnotation{
public String key() default “iphone” ;
public String value() default “apple” ;
}

Java入門–DecimalFormatを使って数値をフォーマットする

javaコード:
import java.text.DecimalFormat;
import java.util.Locale;

public class DecimalFdtDemo {

/**
* @param args
*/
public static void main(String[] args) {

System.out.println(“*******DecimalFormcat demo***********”);
DecimalFormat format = new DecimalFormat(“###,####.000”);
System.out.println(format.format(3444443333456.1227222));

Locale.setDefault(Locale.US);
DecimalFormat usFmt = new DecimalFormat(“###,###.000”);
System.out.println(usFmt.format(3444443333456.1227222));

DecimalFormat adPatFmt = new DecimalFormat();
adPatFmt.applyPattern(“##,###.000”);
System.out.println(adPatFmt.format(3444443333456.1227));

DecimalFormat zhiFormat = new DecimalFormat();
zhiFormat.applyPattern(“0.000E0000”);
System.out.println(zhiFormat.format(10000));
System.out.println(zhiFormat.format(12345678.345));

DecimalFormat perFmt = new DecimalFormat();
perFmt.applyPattern(“#0.000%”);
System.out.println(perFmt.format(0.3052222));
}

}
実行結果
*******DecimalFormcat demo***********
3,4444,4333,3456.123
3,444,443,333,456.123
3,444,443,333,456.123
1.000E0004
1.235E0007
30.522%

Java入門–数値変換(String->int String-long)のサンプル

参考コード:
//数値変換String->int
public static final int toInt(String ctn)
{
if(ctn.length() ==0){
ctn=”0″;
}

Integer i = new integer(ctn);
return i.intValue();

}
//数値変換String->long
public static final long toLong(String ctn)
{
if(ctn.length() ==0){
ctn=”0″;
}
Long i = new Long(ctn);
return i.longValue();
}