| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

「Spring MVC Tips」の版間の差分

提供: MyMemoWiki
ナビゲーションに移動 検索に移動
(ページの作成:「==Spring MVC Tips== [Spring][Spring MVC] ==コントローラー== ===リクエストパラメータを必須でなくする=== *@RequestParam を指定するとデ…」)
 
1行目: 1行目:
 
==Spring MVC Tips==
 
==Spring MVC Tips==
[Spring][Spring MVC]
+
[[Spring][Spring MVC]]
  
 
==コントローラー==
 
==コントローラー==
15行目: 15行目:
 
*文字化け対策をする
 
*文字化け対策をする
 
=====Form=====
 
=====Form=====
  <form id="formUpload" action="upload.html" method="POST" enctype="multipart/form-data" >
+
  &lt;form id="formUpload" action="upload.html" method="POST" enctype="multipart/form-data" &gt;
   <input name="attach_file" />
+
   &lt;input name="attach_file" /&gt;
   <input type="submit" value="アップロード"/>
+
   &lt;input type="submit" value="アップロード"/&gt;
  </form>
+
  &lt;/form&gt;
  
 
=====文字コードをiso-8859-1として変換=====
 
=====文字コードをiso-8859-1として変換=====
38行目: 38行目:
 
  int len = 0;
 
  int len = 0;
 
  byte[] buffer = new byte[1024];
 
  byte[] buffer = new byte[1024];
  while ((len = bis.read(buffer)) >= 0) {  
+
  while ((len = bis.read(buffer)) &gt;= 0) {  
 
     os.write(buffer,0, len);
 
     os.write(buffer,0, len);
 
  }
 
  }
 
  bis.close();
 
  bis.close();

2020年2月15日 (土) 08:05時点における版

Spring MVC Tips

[[Spring][Spring MVC]]

コントローラー

リクエストパラメータを必須でなくする

  • @RequestParam を指定するとデフォルトで必須なのでパラメータがない場合、URLにマッチしない
  • required=falseとする
@RequestMapping(value="/test.html",method = RequestMethod.GET)
public String setupForm( @RequestParam(value="id", required=false) String id, ModelMap model) {
              :


ファイルアップロード

  • MultipartFile を利用する
  • 文字化け対策をする
Form
<form id="formUpload" action="upload.html" method="POST" enctype="multipart/form-data" >
  <input name="attach_file" />
  <input type="submit" value="アップロード"/>
</form>
文字コードをiso-8859-1として変換
@RequestMapping(value="/upload.html", method = RequestMethod.POST)
public String uploadFile(MultipartFile file) {
    String filename = new String(file.getOriginalFilename().getBytes("iso-8859-1"),"utf-8");

ファイルダウンロード

//String fileName = new String(originalFileName.getBytes("utf-8"),"iso-8859-1"); // Chrome OK, IE NG
String fileName = new String(originalFileName.getBytes("ms932"),"iso-8859-1"); // Chrome OK, IE OK

response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "filename=\"" + fileName + "\"");

BufferedInputStream  bis = new BufferedInputStream(attachFileDownloadService.getAttachFileOutputStream(attachFileInfo));
os = response.getOutputStream();

int len = 0;
byte[] buffer = new byte[1024];
while ((len = bis.read(buffer)) >= 0) { 
    os.write(buffer,0, len);
}
bis.close();