http://www.huqiwen.com/2013/01/10/liferay-6-1-development-study-17-springmvc-portlet/

http://www.blogjava.net/allen-zhe/archive/2008/07/03/212259.html

http://www.open-open.com/lib/view/open1374399276230.html

http://www.cnblogs.com/liukemng/p/3751338.html

http://www.cnblogs.com/liukemng/p/3751338.html

http://www.googlestable.com/

http://www.aol.com/

http://208.187.128.27/

package com.demo.web.models;

import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style; public class FormatModel{ @NumberFormat(style=Style.CURRENCY)
   private double money;
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date date; public double getMoney(){
return money;
}
public Date getDate(){
return date;
} public void setMoney(double money){
this.money=money;
}
public void setDate(Date date){
this.date=date;
} }

如何实现全局的异常处理?

在spring MVC的配置文件中:

  1. <!-- 总错误处理-->
  2. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  3. <property name="defaultErrorView">
  4. <value>/error/error</value>
  5. </property>
  6. <property name="defaultStatusCode">
  7. <value>500</value>
  8. </property>
  9. <property name="warnLogCategory">
  10. <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
  11. </property>
  12. </bean>

这里主要的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。

具体可以配置哪些属性,我是通过查看源码知道的。

你也可以实现HandlerExceptionResolver接口,写一个自己的异常处理程序。spring的扩展性是很好的。

通过SimpleMappingExceptionResolver我们可以将不同的异常映射到不同的jsp页面(通过exceptionMappings属性的配置)。

同时我们也可以为所有的异常指定一个默认的异常提示页面(通过defaultErrorView属性的配置),如果所抛出的异常在exceptionMappings中没有对应的映射,则Spring将用此默认配置显示异常信息。

注意这里配置的异常显示界面均仅包括主文件名,至于文件路径和后缀已经在viewResolver中指定。如/error/error表示/error/error.jsp

显示错误的jsp页面:

  1. <%@ page language="java" contentType="text/html; charset=GBK"
  2. pageEncoding="GBK"%>
  3. <%@ page import="java.lang.Exception"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=GBK">
  8. <title>错误页面</title>
  9. </head>
  10. <body>
  11. <h1>出错了</h1>
  12. <%
  13. Exception e = (Exception)request.getAttribute("exception");
  14. out.print(e.getMessage());
  15. %>
  16. </body>
  17. </html>

其中一句:request.getAttribute("exception"),key是exception,也是在SimpleMappingExceptionResolver类默认指定的,是可能通过配置文件修改这个值的,大家可以去看源码。

参考文章:

http://www.blogjava.net/wuxufeng8080/articles/191150.html

http://fangjunai.blog.163.com/blog/static/1124970520108102013839/

  1. @Autowired和@Qualifier  自动注入[根据类型注入]
  2. @Autowired 可以对成员变量、方法以及构造函数进行注释,
  3. @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。
  4. ps:两者结合使用相当于@Resourcede效果。
  5. @Resource   自动注入[根据名称注入],可写参数name=""
  6. @Controller 表示控制器
  7. @Service    表示业务处理层[一般在serviceImpl]
  8. @Repository 表示持久层[一般在daoImpl]
  9. @Component  当你的类不清楚是哪一层的时候使用该注解
  10. @ResponseBody  异步返回数据类型为json
  11. @RequestMapping  路径,请求类型等设置
  12. @InitBinder   数据绑定
package org.springframework.samples.mvc31.crudcontroller;
 
import javax.validation.Valid;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/accounts")
public class AccountController {
 
private AccountManager accountManager;
 
@Autowired
public AccountController(AccountManager accountManager) {
this.accountManager = accountManager;
}
 
@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
model.addAttribute("accounts", this.accountManager.getAccounts());
return "accounts/list";
}
 
@RequestMapping(value="/new", method = RequestMethod.GET)
public String newForm(Model model) {
model.addAttribute(new Account());
return "accounts/new";
}
 
// The account is loaded from the "account" URI variable via {@link AccountConverter}.
 
@RequestMapping(value="/{account}/edit", method = RequestMethod.GET)
public String edit(@PathVariable Account account) {
return "accounts/edit";
}
 
// The account is loaded from the "account" URI variable via {@link AccountConverter}.
// Data binding and validation are also applied.
 
@RequestMapping(value="/{account}", method = RequestMethod.PUT)
public String update(@Valid @ModelAttribute Account account, BindingResult result) {
if (result.hasErrors()) {
return "accounts/edit";
}
this.accountManager.saveOrUpdate(account);
return "redirect:../accounts";
}
 
// The account is created with its default constructor.
// Data binding and validation are also applied.
 
@RequestMapping(method = RequestMethod.POST)
public String save(@Valid @ModelAttribute Account account, BindingResult result) {
if (result.hasErrors()) {
return "accounts/edit";
}
this.accountManager.saveOrUpdate(account);
return "redirect:accounts";
}
 
// The account is loaded from the "account" URI variable via {@link AccountConverter}.
 
@RequestMapping(value="/{account}", method = RequestMethod.DELETE)
public String delete(@PathVariable Account account) {
this.accountManager.delete(account);
return "redirect:../accounts";
}
 
}
 
 
 
package com.sprhib.controller;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import com.sprhib.model.Team;
import com.sprhib.service.TeamService;
 
@Controller
@RequestMapping(value="/team")
public class TeamController {
 
@Autowired
private TeamService teamService;
 
@RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addTeamPage() {
ModelAndView modelAndView = new ModelAndView("add-team-form");
modelAndView.addObject("team", new Team());
return modelAndView;
}
 
@RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingTeam(@ModelAttribute Team team) {
 
ModelAndView modelAndView = new ModelAndView("home");
teamService.addTeam(team);
 
String message = "Team was successfully added.";
modelAndView.addObject("message", message);
 
return modelAndView;
}
 
@RequestMapping(value="/list")
public ModelAndView listOfTeams() {
ModelAndView modelAndView = new ModelAndView("list-of-teams");
 
List<Team> teams = teamService.getTeams();
modelAndView.addObject("teams", teams);
 
return modelAndView;
}
 
@RequestMapping(value="/edit/{id}", method=RequestMethod.GET)
public ModelAndView editTeamPage(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("edit-team-form");
Team team = teamService.getTeam(id);
modelAndView.addObject("team",team);
return modelAndView;
}
 
@RequestMapping(value="/edit/{id}", method=RequestMethod.POST)
public ModelAndView edditingTeam(@ModelAttribute Team team, @PathVariable Integer id) {
 
ModelAndView modelAndView = new ModelAndView("home");
 
teamService.updateTeam(team);
 
String message = "Team was successfully edited.";
modelAndView.addObject("message", message);
 
return modelAndView;
}
 
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView deleteTeam(@PathVariable Integer id) {
ModelAndView modelAndView = new ModelAndView("home");
teamService.deleteTeam(id);
String message = "Team was successfully deleted.";
modelAndView.addObject("message", message);
return modelAndView;
}
 
}
 
package org.jamesdbloom.web.controller;
 
import org.jamesdbloom.dao.UserDAO;
import org.jamesdbloom.domain.User;
import org.jamesdbloom.email.EmailService;
import org.jamesdbloom.uuid.UUIDFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
 
/**
* @author jamesdbloom
*/
@Controller
public class RegistrationController {
 
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private UserDAO userDAO;
    @Resource
    private Environment environment;
    @Resource
    private EmailService emailService;
    @Resource
    private UUIDFactory uuidFactory;
 
    private void setupModel(Model model) {
        model.addAttribute("passwordPattern", User.PASSWORD_PATTERN);
        model.addAttribute("emailPattern", User.EMAIL_PATTERN);
        model.addAttribute("environment", environment);
    }
 
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String registerForm(HttpServletRequest request, Model model) {
        setupModel(model);
        model.addAttribute("user", new User());
        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
        if (csrfToken != null) {
            model.addAttribute("csrfParameterName", csrfToken.getParameterName());
            model.addAttribute("csrfToken", csrfToken.getToken());
        }
        return "register";
    }
 
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@Valid User user, BindingResult bindingResult, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws MalformedURLException, UnsupportedEncodingException {
 
        boolean userAlreadyExists = user.getEmail() != null && (userDAO.findByEmail(user.getEmail()) != null);
        if (bindingResult.hasErrors() || userAlreadyExists) {
            setupModel(model);
            if (userAlreadyExists) {
                bindingResult.addError(new ObjectError("user", "validation.user.alreadyExists"));
            }
            model.addAttribute("bindingResult", bindingResult);
            model.addAttribute("user", user);
            return "register";
        }
        user.setOneTimeToken(uuidFactory.generateUUID());
        userDAO.save(user);
        emailService.sendRegistrationMessage(user, request);
        redirectAttributes.addFlashAttribute("message", "Your account has been created and an email has been sent to " + user.getEmail() + " with a link to create your password and login, please check your spam folder if you don't see the email within 5 minutes");
        redirectAttributes.addFlashAttribute("title", "Account Created");
        return "redirect:/message";
    }
 
}
 
 
package org.davidmendoza.fileUpload.web;
 
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.davidmendoza.fileUpload.config.PropertyPlaceholderConfig;
import org.davidmendoza.fileUpload.dao.ImageDao;
import org.davidmendoza.fileUpload.model.Image;
import org.imgscalr.Scalr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
/**
*
* @author jdmr
*/
@Controller
@RequestMapping
@Import(PropertyPlaceholderConfig.class)
public class ImageController {
    
    private static final Logger log = LoggerFactory.getLogger(ImageController.class);
    
    @Autowired
    private ImageDao imageDao;
    @Value("${file.upload.directory}")
    private String fileUploadDirectory;
 
    @RequestMapping
    public String index() {
        log.debug("ImageController home");
        return "image/index";
    }
    
    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public @ResponseBody Map list() {
        log.debug("uploadGet called");
        List<Image> list = imageDao.list();
        for(Image image : list) {
            image.setUrl("/picture/"+image.getId());
            image.setThumbnailUrl("/thumbnail/"+image.getId());
            image.setDeleteUrl("/delete/"+image.getId());
            image.setDeleteType("DELETE");
        }
        Map<String, Object> files = new HashMap<>();
        files.put("files", list);
        log.debug("Returning: {}", files);
        return files;
    }
    
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) {
        log.debug("uploadPost called");
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf;
        List<Image> list = new LinkedList<>();
        
        while (itr.hasNext()) {
            mpf = request.getFile(itr.next());
            log.debug("Uploading {}", mpf.getOriginalFilename());
            
            String newFilenameBase = UUID.randomUUID().toString();
            String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
            String newFilename = newFilenameBase + originalFileExtension;
            String storageDirectory = fileUploadDirectory;
            String contentType = mpf.getContentType();
            
            File newFile = new File(storageDirectory + "/" + newFilename);
            try {
                mpf.transferTo(newFile);
                
                BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290);
                String thumbnailFilename = newFilenameBase + "-thumbnail.png";
                File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename);
                ImageIO.write(thumbnail, "png", thumbnailFile);
                
                Image image = new Image();
                image.setName(mpf.getOriginalFilename());
                image.setThumbnailFilename(thumbnailFilename);
                image.setNewFilename(newFilename);
                image.setContentType(contentType);
                image.setSize(mpf.getSize());
                image.setThumbnailSize(thumbnailFile.length());
                image = imageDao.create(image);
                
                image.setUrl("/picture/"+image.getId());
                image.setThumbnailUrl("/thumbnail/"+image.getId());
                image.setDeleteUrl("/delete/"+image.getId());
                image.setDeleteType("DELETE");
                
                list.add(image);
                
            } catch(IOException e) {
                log.error("Could not upload file "+mpf.getOriginalFilename(), e);
            }
            
        }
        
        Map<String, Object> files = new HashMap<>();
        files.put("files", list);
        return files;
    }
    
    @RequestMapping(value = "/picture/{id}", method = RequestMethod.GET)
    public void picture(HttpServletResponse response, @PathVariable Long id) {
        Image image = imageDao.get(id);
        File imageFile = new File(fileUploadDirectory+"/"+image.getNewFilename());
        response.setContentType(image.getContentType());
        response.setContentLength(image.getSize().intValue());
        try {
            InputStream is = new FileInputStream(imageFile);
            IOUtils.copy(is, response.getOutputStream());
        } catch(IOException e) {
            log.error("Could not show picture "+id, e);
        }
    }
    
    @RequestMapping(value = "/thumbnail/{id}", method = RequestMethod.GET)
    public void thumbnail(HttpServletResponse response, @PathVariable Long id) {
        Image image = imageDao.get(id);
        File imageFile = new File(fileUploadDirectory+"/"+image.getThumbnailFilename());
        response.setContentType(image.getContentType());
        response.setContentLength(image.getThumbnailSize().intValue());
        try {
            InputStream is = new FileInputStream(imageFile);
            IOUtils.copy(is, response.getOutputStream());
        } catch(IOException e) {
            log.error("Could not show thumbnail "+id, e);
        }
    }
    
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.DELETE)
    public @ResponseBody List delete(@PathVariable Long id) {
        Image image = imageDao.get(id);
        File imageFile = new File(fileUploadDirectory+"/"+image.getNewFilename());
        imageFile.delete();
        File thumbnailFile = new File(fileUploadDirectory+"/"+image.getThumbnailFilename());
        thumbnailFile.delete();
        imageDao.delete(image);
        List<Map<String, Object>> results = new ArrayList<>();
        Map<String, Object> success = new HashMap<>();
        success.put("success", true);
        results.add(success);
        return results;
    }
 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="http://www.springframework.org/tags" %>
<!DOCTYPE HTML>
<!--
/*
* jQuery File Upload Plugin Demo 9.0.0
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
-->
<html lang="en">
<head>
    <!-- Force latest IE rendering engine or ChromeFrame if installed -->
    <!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
    <meta charset="utf-8">
    <title>jQuery File Upload Demo</title>
    <meta name="description" content="File Upload widget with multiple file selection, drag&amp;drop support, progress bars, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads and client-side image resizing. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap styles -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <!-- Generic page styles -->
    <link rel="stylesheet" href="css/style.css">
    <!-- blueimp Gallery styles -->
    <link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css">
    <!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
    <link rel="stylesheet" href="css/jquery.fileupload.css">
    <link rel="stylesheet" href="css/jquery.fileupload-ui.css">
    <!-- CSS adjustments for browsers with JavaScript disabled -->
    <noscript><link rel="stylesheet" href="css/jquery.fileupload-noscript.css"></noscript>
    <noscript><link rel="stylesheet" href="css/jquery.fileupload-ui-noscript.css"></noscript>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-fixed-top .navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://github.com/blueimp/jQuery-File-Upload">jQuery File Upload</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="https://github.com/blueimp/jQuery-File-Upload/tags">Download</a></li>
                <li><a href="https://github.com/blueimp/jQuery-File-Upload">Source Code</a></li>
                <li><a href="https://github.com/blueimp/jQuery-File-Upload/wiki">Documentation</a></li>
                <li><a href="https://blueimp.net">&copy; Sebastian Tschan</a></li>
            </ul>
        </div>
    </div>
</div>
<div class="container">
    <h1>jQuery File Upload Demo</h1>
    <h2 class="lead">Basic Plus UI version</h2>
    <ul class="nav nav-tabs">
        <li><a href="basic.html">Basic</a></li>
        <li><a href="basic-plus.html">Basic Plus</a></li>
        <li class="active"><a href="index.html">Basic Plus UI</a></li>
        <li><a href="angularjs.html">AngularJS</a></li>
        <li><a href="jquery-ui.html">jQuery UI</a></li>
    </ul>
    <br>
    <blockquote>
        <p>File Upload widget with multiple file selection, drag&amp;drop support, progress bars, validation and preview images, audio and video for jQuery.<br>
            Supports cross-domain, chunked and resumable file uploads and client-side image resizing.<br>
            Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.</p>
    </blockquote>
    <br>
    <!-- The file upload form used as target for the file upload widget -->
    <form id="fileupload" action='<s:url value="/upload"/>' method="POST" enctype="multipart/form-data">
        <!-- Redirect browsers with JavaScript disabled to the origin page -->
        <noscript><input type="hidden" name="redirect" value="http://blueimp.github.io/jQuery-File-Upload/"></noscript>
        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
                <!-- The fileinput-button span is used to style the file input field as button -->
                <span class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <span>Add files...</span>
                    <input type="file" name="files[]" multiple>
                </span>
                <button type="submit" class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start upload</span>
                </button>
                <button type="reset" class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel upload</span>
                </button>
                <button type="button" class="btn btn-danger delete">
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" class="toggle">
                <!-- The global file processing state -->
                <span class="fileupload-process"></span>
            </div>
            <!-- The global progress state -->
            <div class="col-lg-5 fileupload-progress fade">
                <!-- The global progress bar -->
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <!-- The extended global progress state -->
                <div class="progress-extended">&nbsp;</div>
            </div>
        </div>
        <!-- The table listing the files available for upload/download -->
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>
    <br>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">Demo Notes</h3>
        </div>
        <div class="panel-body">
            <ul>
                <li>The maximum file size for uploads in this demo is <strong>5 MB</strong> (default file size is unlimited).</li>
                <li>Only image files (<strong>JPG, GIF, PNG</strong>) are allowed in this demo (by default there is no file type restriction).</li>
                <li>Uploaded files will be deleted automatically after <strong>5 minutes</strong> (demo setting).</li>
                <li>You can <strong>drag &amp; drop</strong> files from your desktop on this webpage (see <a href="https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support">Browser support</a>).</li>
                <li>Please refer to the <a href="https://github.com/blueimp/jQuery-File-Upload">project website</a> and <a href="https://github.com/blueimp/jQuery-File-Upload/wiki">documentation</a> for more information.</li>
                <li>Built with Twitter's <a href="http://twitter.github.com/bootstrap/">Bootstrap</a> CSS framework and Icons from <a href="http://glyphicons.com/">Glyphicons</a>.</li>
            </ul>
        </div>
    </div>
</div>
<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <div class="slides"></div>
    <h3 class="title"></h3>
    <a class="prev">‹</a>
    <a class="next">›</a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
</div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            <strong class="error text-danger"></strong>
        </td>
        <td>
            <p class="size">Processing...</p>
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </td>
        <td>
            {% if (!i && !o.options.autoUpload) { %}
                <button class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start</span>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="js/vendor/jquery.ui.widget.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="http://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Load-Image/js/load-image.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<!-- blueimp Gallery script -->
<script src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="js/jquery.fileupload-ui.js"></script>
<!-- The main application script -->
<script src="js/main.js"></script>
<!-- The XDomainRequest Transport is included for cross-domain file deletion for IE 8 and IE 9 -->
<!--[if (gte IE 8)&(lt IE 10)]>
<script src="js/cors/jquery.xdr-transport.js"></script>
<![endif]-->
</body>
</html>
 
 
package tr.com.lucidcode.controller;
 
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
 
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
 
@SuppressWarnings("restriction")
@Controller
@RequestMapping("/captcha")
public class CaptchaController {
 
protected static Logger logger = Logger.getLogger("controller");
 
@Resource(name = "captchaService")
private ImageCaptchaService captchaService;
 
@RequestMapping(value = "/getImage", method = RequestMethod.GET)
public @ResponseBody
Model showImage(HttpServletRequest request,
HttpServletResponse response, Model model) throws Exception {
 
logger.debug("Received a request to show captcha image");
 
byte[] captchaChallengeAsJpeg = null;
 
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
 
try {
// get the session id that will identify the generated captcha.
// the same id must be used to validate the response, the session id
// is a good candidate!
 
String captchaId = request.getSession().getId();
 
logger.debug("Captcha ID which gave the image::" + captchaId);
 
// call the ImageCaptchaService getChallenge method
BufferedImage challenge = captchaService.getImageChallengeForID(
captchaId, request.getLocale());
 
// a jpeg encoder
JPEGImageEncoder jpegEncoder = JPEGCodec
.createJPEGEncoder(jpegOutputStream);
jpegEncoder.encode(challenge);
} catch (IllegalArgumentException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} catch (CaptchaServiceException e) {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return null;
}
 
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
 
// flush it in the response
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// response.setContentType("image/jpeg");
// response.getOutputStream().write(jpegOutputStream);
ServletOutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
 
return null;
}
 
}

Liferay 6.1开发学习的更多相关文章

  1. Android开发学习之路-RecyclerView滑动删除和拖动排序

    Android开发学习之路-RecyclerView使用初探 Android开发学习之路-RecyclerView的Item自定义动画及DefaultItemAnimator源码分析 Android开 ...

  2. web前端开发学习内容

    应该 具备的 知识技能 :懂web标准,熟练手写 xhtml css3 并符合 符合w3c标准                       代码能 兼容主流浏览器.ie6.7.8.9 ff 等.    ...

  3. Android开发学习路线图

    Android开发学习方法: Android是一个比较庞大的体系,从底层的Linux内核到上层的应用层,各部分的内容跨度也比较大.因此,一个好的学习方法对我们学习Android开发很重要. 在此建议, ...

  4. NET开发学习项目资源(2)

    NET开发学习项目资源 击标题链接即可下载. 目录: 1.征婚交友网站 前台交友信息和后台会员管理两大部分组成. 前台功能模块 该模块主要包括查询交友信息.显示交友信息.会员登录.会员信息管理.修改会 ...

  5. Civil 3D API二次开发学习指南

    Civil 3D构建于AutoCAD 和 Map 3D之上,在学习Civil 3D API二次开发之前,您至少需要了解AutoCAD API的二次开发,你可以参考AutoCAD .NET API二次开 ...

  6. 【前端】移动端Web开发学习笔记【2】 & flex布局

    上一篇:移动端Web开发学习笔记[1] meta标签 width设置的是layout viewport 的宽度 initial-scale=1.0 自带 width=device-width 最佳实践 ...

  7. 【前端】移动端Web开发学习笔记【1】

    下一篇:移动端Web开发学习笔记[2] Part 1: 两篇重要的博客 有两篇翻译过来的博客值得一看: 两个viewport的故事(第一部分) 两个viewport的故事(第二部分) 这两篇博客探讨了 ...

  8. .net 网站开发学习资源

    慕课网 前端基础学习 http://www.imooc.com/course/list?c=fe 了解需求 例子之一 http://wenku.it168.com/d_000517899.shtml ...

  9. 驱动开发学习笔记. 0.07 Uboot链接地址 加载地址 和 链接脚本地址

    驱动开发学习笔记. 0.07 Uboot链接地址 加载地址 和 链接脚本地址 最近重新看了乾龙_Heron的<ARM 上电启动及 Uboot 代码分析>(下简称<代码分析>) ...

随机推荐

  1. c# 学习笔记(三)

    程序集程序集的私有部署 不用在注册表中注册组件卸载只需要从文件系统中删除他即可 共享程序集和GAC 只有强命名程序集能被添加到GAC中程序集数据签名只需在安装到GAC时检查一次 GAC内的并肩执行GA ...

  2. expdp 备份数据库

    操作系统层面创建目录 [root@Oracle10g ~]# mkdir -p /home/oracle/db_back/ 2. 修改目录的所属用户.所属组 [root@Oracle10g ~]# c ...

  3. [!] CocoaPods was not able to update the `master` repo...

    输入pod install之后出现: [!] CocoaPods was not able to update the `master` repo. If this is an unexpected ...

  4. C++ 性能剖析 (四):Inheritance 对性能的影响

    (这个editor今天有毛病,把我的format全搞乱了,抱歉!) Inheritance 是OOP 的一个重要特征.虽然业界有许多同行不喜欢inheritance,但是正确地使用inheritanc ...

  5. underscorejs-invoke学习

    2.13 invoke 2.13.1 语法: _.invoke(list, method, *args) 2.13.2 说明: 每个list属性值都执行method方法,根据method方法返回一个数 ...

  6. 深入Java虚拟机读书笔记第三章安全

    为什么需要安全性 Java的安全模型是其多个重要结构特点之一,它使Java成为适于网络环境的技术.Java安全模型侧重于保护终端用户免受从网络下载的.来自不可靠来源的.恶意程序(以及善于程序中的bug ...

  7. JQUERY1.9学习笔记 之内容过滤器(四) parent选择器

    描述:选择至少包含一个子节点的元素(一个标签或是文本). 例:找出所有有子元素的td标签,包含文本. <!doctype html><html lang="en" ...

  8. 实验一:基于Winsock完成简单的网络程序开发

    第一部分:简答的UDP网络通信程序 // UDP5555.cpp : Defines the entry point for the application. //================== ...

  9. request.getParameterMap();

    Map<String, String[]> map = request.getParameterMap(); for(Map.Entry<String,String[]> e: ...

  10. 主流屏幕对比:IPS/LTPS/CGS/IGZO/AMOLED

    IPS.LTPS.CGS.IGZO.AMOLED都是什么屏幕又有什么区别?目前的手机屏幕技术实在太多,本文旨在介绍各种面板以及屏幕技术,便于大家更好地进行区分. 近年来手机屏幕技术层出不穷,早在几年前 ...