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的配置文件中:
- <!-- 总错误处理-->
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="defaultErrorView">
- <value>/error/error</value>
- </property>
- <property name="defaultStatusCode">
- <value>500</value>
- </property>
- <property name="warnLogCategory">
- <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
- </property>
- </bean>
这里主要的类是SimpleMappingExceptionResolver类,和他的父类AbstractHandlerExceptionResolver类。
具体可以配置哪些属性,我是通过查看源码知道的。
你也可以实现HandlerExceptionResolver接口,写一个自己的异常处理程序。spring的扩展性是很好的。
通过SimpleMappingExceptionResolver我们可以将不同的异常映射到不同的jsp页面(通过exceptionMappings属性的配置)。
同时我们也可以为所有的异常指定一个默认的异常提示页面(通过defaultErrorView属性的配置),如果所抛出的异常在exceptionMappings中没有对应的映射,则Spring将用此默认配置显示异常信息。
注意这里配置的异常显示界面均仅包括主文件名,至于文件路径和后缀已经在viewResolver中指定。如/error/error表示/error/error.jsp
显示错误的jsp页面:
- <%@ page language="java" contentType="text/html; charset=GBK"
- pageEncoding="GBK"%>
- <%@ page import="java.lang.Exception"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GBK">
- <title>错误页面</title>
- </head>
- <body>
- <h1>出错了</h1>
- <%
- Exception e = (Exception)request.getAttribute("exception");
- out.print(e.getMessage());
- %>
- </body>
- </html>
其中一句:request.getAttribute("exception"),key是exception,也是在SimpleMappingExceptionResolver类默认指定的,是可能通过配置文件修改这个值的,大家可以去看源码。
参考文章:
- @Autowired和@Qualifier 自动注入[根据类型注入]
- @Autowired 可以对成员变量、方法以及构造函数进行注释,
- @Qualifier 的标注对象是成员变量、方法入参、构造函数入参。
- ps:两者结合使用相当于@Resourcede效果。
- @Resource 自动注入[根据名称注入],可写参数name=""
- @Controller 表示控制器
- @Service 表示业务处理层[一般在serviceImpl]
- @Repository 表示持久层[一般在daoImpl]
- @Component 当你的类不清楚是哪一层的时候使用该注解
- @ResponseBody 异步返回数据类型为json
- @RequestMapping 路径,请求类型等设置
- @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; @RequestMapping("/accounts") public class AccountController { private AccountManager accountManager; public AccountController(AccountManager accountManager) { this.accountManager = accountManager; @RequestMapping(method = RequestMethod.GET) public String list(Model model) { model.addAttribute("accounts", this.accountManager.getAccounts()); @RequestMapping(value="/new", method = RequestMethod.GET) public String newForm(Model model) { model.addAttribute(new Account()); // 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) { // 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()) { 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()) { 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 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; @RequestMapping(value="/team") public class TeamController { private TeamService teamService; @RequestMapping(value="/add", method=RequestMethod.GET) public ModelAndView addTeamPage() { ModelAndView modelAndView = new ModelAndView("add-team-form"); modelAndView.addObject("team", new Team()); @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); @RequestMapping(value="/list") public ModelAndView listOfTeams() { ModelAndView modelAndView = new ModelAndView("list-of-teams"); List<Team> teams = teamService.getTeams(); modelAndView.addObject("teams", teams); @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); @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); @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); 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.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; public class RegistrationController { protected Logger logger = LoggerFactory.getLogger(getClass()); private Environment environment; private EmailService emailService; 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) { model.addAttribute("user", new User()); CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); model.addAttribute("csrfParameterName", csrfToken.getParameterName()); model.addAttribute("csrfToken", csrfToken.getToken()); @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) { bindingResult.addError(new ObjectError("user", "validation.user.alreadyExists")); model.addAttribute("bindingResult", bindingResult); model.addAttribute("user", user); user.setOneTimeToken(uuidFactory.generateUUID()); 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.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 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.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; @Import(PropertyPlaceholderConfig.class) public class ImageController { private static final Logger log = LoggerFactory.getLogger(ImageController.class); private ImageDao imageDao; @Value("${file.upload.directory}") private String fileUploadDirectory; log.debug("ImageController home"); @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); @RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) { log.debug("uploadPost called"); Iterator<String> itr = request.getFileNames(); List<Image> list = new LinkedList<>(); 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); 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"); log.error("Could not upload file "+mpf.getOriginalFilename(), e); Map<String, Object> files = new HashMap<>(); files.put("files", list); @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()); InputStream is = new FileInputStream(imageFile); IOUtils.copy(is, response.getOutputStream()); 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()); InputStream is = new FileInputStream(imageFile); IOUtils.copy(is, response.getOutputStream()); 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()); File thumbnailFile = new File(fileUploadDirectory+"/"+image.getThumbnailFilename()); List<Map<String, Object>> results = new ArrayList<>(); Map<String, Object> success = new HashMap<>(); success.put("success", true); <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="http://www.springframework.org/tags" %> * jQuery File Upload Plugin Demo 9.0.0 * https://github.com/blueimp/jQuery-File-Upload * Copyright 2010, Sebastian Tschan * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT <!-- Force latest IE rendering engine or ChromeFrame if installed --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>jQuery File Upload Demo</title> <meta name="description" content="File Upload widget with multiple file selection, drag&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> <div class="navbar navbar-default navbar-fixed-top"> <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> <a class="navbar-brand" href="https://github.com/blueimp/jQuery-File-Upload">jQuery File Upload</a> <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">© Sebastian Tschan</a></li> <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> <p>File Upload widget with multiple file selection, drag&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> <!-- 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"> <!-- 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> <button type="submit" class="btn btn-primary start"> <i class="glyphicon glyphicon-upload"></i> <span>Start upload</span> <button type="reset" class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel upload</span> <button type="button" class="btn btn-danger delete"> <i class="glyphicon glyphicon-trash"></i> <input type="checkbox" class="toggle"> <!-- The global file processing state --> <span class="fileupload-process"></span> <!-- 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> <!-- The extended global progress state --> <div class="progress-extended"> </div> <!-- The table listing the files available for upload/download --> <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Demo Notes</h3> <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 & 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> <!-- The blueimp Gallery widget --> <div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even"> <div class="slides"></div> <a class="play-pause"></a> <ol class="indicator"></ol> <!-- 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"> <span class="preview"></span> <p class="name">{%=file.name%}</p> <strong class="error text-danger"></strong> <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> {% if (!i
&& !o.options.autoUpload) { %} <button class="btn btn-primary start"> <i class="glyphicon glyphicon-upload"></i> <button class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <!-- 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"> {% if (file.thumbnailUrl) { %}
<a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a> <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a> <span>{%=file.name%}</span> <div><span class="label label-danger">Error</span> {%=file.error%}</div> <span class="size">{%=o.formatFileSize(file.size)%}</span> {% 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> <input type="checkbox" name="delete" value="1" class="toggle"> <button class="btn btn-warning cancel"> <i class="glyphicon glyphicon-ban-circle"></i> <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> 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") @RequestMapping("/captcha") public class CaptchaController { protected static Logger logger = Logger.getLogger("controller"); @Resource(name = "captchaService") private ImageCaptchaService captchaService; @RequestMapping(value = "/getImage", method = RequestMethod.GET) 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(); // get the session id that will identify the generated captcha. // the same id must be used to validate the response, the session id 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()); JPEGImageEncoder jpegEncoder = JPEGCodec .createJPEGEncoder(jpegOutputStream); jpegEncoder.encode(challenge); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } catch (CaptchaServiceException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 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();