I am trying to show background image in my Spring mvc app. Now, the image is getting displayed in my home page but when I click a link which points to same page with some parameter appended to the url, the image is not appearing.
I am using this tag for displaying image:
<img src="./resources/css/welcome.png" id="bg" alt="">
In my application context,
<mvc:resources mapping="/resources/**" location="/resources/" />
Now, in my home page, if I click a link
MyLink
Image is not coming. The page name is welcome.jsp. Its controller is :
#Controller
public class WelcomeController {
#RequestMapping(value = "/welcome/{category}", method = RequestMethod.GET)
public String showPage(Model modelMap, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
return "welcome";
} catch (Exception exception) {
}
}
#RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String showPage1(Model modelMap, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
return "welcome";
} catch (Exception exception) {
}
}
}
I am not able to understand if the image is coming when there is not path variable in welcome.html url, why it is not being loaded when I click MyLink which appends path variable in the url? Please help me out here..
Use jstl tags core lib and c:URL to create the image src definition.
Related
i have servlet
#Component(service={Servlet.class},
property={"sling.servlet.methods=get",
"sling.servlet.resourceTypes=/content/wknd-events"})
public class MainServlet extends SlingAllMethodsServlet
{
#Reference
DemoInterfaceImpl demoInterface;
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
demoInterface.redirectUser(request,response);
}
}
demoInterface
#Component(
service= IDemoInterface.class,
immediate = true)
public class DemoInterfaceImpl implements IDemoInterface {
#Override
public void redirectUser(final SlingHttpServletRequest req,
final SlingHttpServletResponse resp) throws IOException {
resp.sendRedirect("/content/we-retail/us/en.html");
}
}
and i have my component
<a href="/content/wknd-events.html">
<button> go</button>
</a>
i want to redirect to /content/we-retail/us/en.html on button click but it doesn't work. I still go to /content/wknd-events.html. I don't understand where is my mistake
Your basic mistake is here "sling.servlet.resourceTypes=/content/wknd-events"})
The resourceType in Sling is the resourceType property set on the resources/nodes. So, if you register a servlet based on resourceType, it will get invoked only if you have the component or resource of that type. In your case , the servlet is registered with a content path as resourceType . Instead of sling.servlet.resourceTypes ; you can try sling.servlet.paths (e.g "sling.servlet.paths=/bin/test") and register your servlet to a path. Instead of giving a href attribute in the <a> tag, write an AJAX call on the click event of the button and give the servlet path as the URL.
$.ajax({
type: 'GET',
url:'/bin/test',
success: function(msg){
<!-- some code -->
}
});
In my spring MVC app (3.1.4-release, Servlet 2.5),
I am not able to display a custom 403 error page when trigger from my HandlerInterceptorAdapter.
My web.xml :
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/403</location>
</error-page>
My Error Controller :
#Controller
public class HTTPErrorController {
#RequestMapping(value="403")
public ModelAndView error403(){
return new ModelAndView("/errors/403");
}
#RequestMapping(value="404")
public ModelAndView error404(){
return new ModelAndView("/errors/404");
}
}
My Handler interceptor :
public class CSRFHandlerInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// Validate CSRF token on POST request only.
if (request.getMethod().equalsIgnoreCase("post")) {
if (!CSRFTokenManager.verifyCSRFToken(request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Bad or missing CSRF value");
return false;
}
}
return true;
}
When the sendError is sent, I have a blank page in firefox and in Ie.
404 exception is working correctly but can't figure out how to make the 403 display my custom error page.
Firefox screenshot:
http://hpics.li/8b6ab9f
Httpfox screenshot :
http://hpics.li/b032ca0
** I am using apache-tomcat-7.0.42
Thanks
I got a similar problem.
For my situation, I figured out it is because my error page do response.forward and than goto Interceptor again. (infinite loop)
i.e., You can try to simplify your /error/403 page to plaintext: "Here is 403".
everyone.
I'm using Spring MVC 4. My App sends activation url to user's email.
Activation url:
www.example.com:8080/myapp/user/activate/$2a$10$Ax2WL93zU3mqjtdxuYlYvuWWyQsPBhkhIfzYHJYk4rdNlAY8qCyC6
But, my App can't find path.
My controller:
#RequestMapping(value = "/user/activate/{hash})
public void activateUser(#PathVariable("hash") String hash) {
userService.activate(hash);
}
What am I doing wrong?
Update:
I've found out that if hash contains dot (".") then throws 404 error.
I've change my url:
www.example.com:8080/myapp/user/activate?code=$2a$10$Ax2WL93zU3mqjtdxuYlYvuWWyQsPBhkhIfzYHJYk4rdNlAY8qCyC6
and my controller:
#RequestMapping(value = "/user/activate)
public void activateUser(#RequestParam("code") String hash) {
userService.activate(hash);
}
It works perfectly.
you are not returning anything from the controller, hence receiving a 404
If you have dot (.) in your path variable value, then you must declare it explicitly in the RequestMapping, as shown below -
#RequestMapping(value = "/download/{attachmentUri:.+}", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<InputStreamResource> downloadAttachment(#PathVariable("attachmentUri") String attachmentUri,
HttpServletResponse response,
WebRequest webRequest) {
}
I've been thinking if it is possible to handle Multipart request that is not an Action request. There is a reason why it seems impossible to me :
Only ActionRequest implements
getFile() kind of methods. I can't
find any easy way how to get the file
out of request other than Action
request
What if I don't use a html form to upload a file and I don't want a view to be rendered after action request - render phase happens always after the action phase.
What if I want to create a post request (with file(s)) by ajax and use #ResourceMapping handler. How do I get it out of ResourceRequest ?
Thank you very much for your thoughts.
This is the "pattern" that is afaik the best way of handling Multipart requests
Action request from view layer goes to this method:
#ActionMapping(params = "javax.portlet.action=sample")
public void response(MultipartActionRequest request, ActionResponse response) {
response.setRenderParameter("javax.portlet.action", "success");
List<MultipartFile> fileList = request.getFiles("file");
}
render phase follows :
#RequestMapping(params = "javax.portlet.action=success")
public ModelAndView process(RenderRequest request, Model model) throws IOException {
Map map = new HashMap();
map.put("test", new Integer(1));
return new ModelAndView("someView", map);
}
You create a "bean" view :
#Component("someView")
public class SomeView extends AbstractView {
private Logger logger = Logger.getLogger(SomeView.class);
#Override
protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response)
throws Exception {
logger.info("Resolving ajax request view - " + map);
JSONObject jsonObj = new JSONObject(map);
logger.info("content Type = " + getContentType());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonObj.toString());
response.getWriter().flush();
}
}
You add BeanNameViewResolver into your servlet/portlet context:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="1" />
I am having trouble with catching and gracefully handling commons fileupload's FileUploadBase.SizeLimitExceededException or spring's MaxUploadSizeExceededException when uploading large files.
From what I can tell these exceptions are thrown during data binding, before the controller is actually reached, therefore resulting in a 500 and no calling of the exception handler method. Has anyone come across this before, and what is the best way for handling these exceptions properly?
thanks to thetoolman for this simple solution. I extended it a bit. I wanted to leave the file handling untouched and transport the Exception to the Controller.
package myCompany;
public class DropOversizeFilesMultipartResolver extends CommonsMultipartResolver {
/**
* Parse the given servlet request, resolving its multipart elements.
*
* Thanks Alexander Semenov # http://forum.springsource.org/showthread.php?62586
*
* #param request
* the request to parse
* #return the parsing result
*/
#Override
protected MultipartParsingResult parseRequest(final HttpServletRequest request) {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
List fileItems;
try {
fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
} catch (FileUploadBase.SizeLimitExceededException ex) {
request.setAttribute(EXCEPTION_KEY, ex);
fileItems = Collections.EMPTY_LIST;
} catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
return parseFileItems(fileItems, encoding);
}
}
and in the controller
#InitBinder("fileForm")
protected void initBinderDesignForm(WebDataBinder binder) {
binder.setValidator(new FileFormValidator());
}
#RequestMapping(value = "/my/mapping", method = RequestMethod.POST)
public ModelAndView acceptFile(HttpServletRequest request, Model model, FormData formData,
BindingResult result) {
Object exception = request.getAttribute(DropOversizeFilesMultipartResolver.EXCEPTION_KEY);
if (exception != null && FileUploadBase.SizeLimitExceededException.class.equals(exception.getClass())) {
result.rejectValue("file", "<your.message.key>");
LOGGER.error(exception);
}
the spring config remains the same. It would be really nice to have the exception transported to the validator, but I haven't figured out how to do this yet.
I know this is old, but I was looking for a solution to this as well and could not find anything. We are providing RESTful services using Spring and we are doing file upload and were not sure how to handle this. I came up with the following and hopefully it will be useful to someone:
All our exceptions are handled with annotations, so we have our error handler resolver set-up like this:
#Configuration
public class MyConfig{
#Bean
public AnnotationMethodHandlerExceptionResolver exceptionResolver(){
final AnnotationMethodHandlerExceptionResolver resolver = new AnnotationMethodHandlerExceptionResolver();
resolver.setMessageConverters(messageConverters());
resolver;
}
}
Then a common class that can handle the exception
public class MultipartExceptionHandler
{
#ExceptionHandler(MaxUploadSizeExceededException.class)
#ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
#ResponseBody
protected CustomError handleMaxUploadSizeExceededException(final HttpServletRequest request,
final HttpServletResponse response, final Throwable e)
throws IOException
{
logger.error(e);
CustomError c = new CustomErrorMaxFileSize("Max file size exceeded", MAX_FILE_SIZE);
return c;
}
#ExceptionHandler(MultipartException.class)
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
protected CustomError handleGenericMultipartException(final HttpServletRequest request,
final HttpServletResponse response, final Throwable e)
throws IOException
{
logger.error(e);
CustomError c = new CustomErrorGeneric("There was a problem with the upload");
return c;
}
}
Then we subclass the commons multipart resolver and implement the HandlerExceptionResolver interface
#Component(value="multipartResolver") // Spring expects this name
public class MyMultipartResolver extends CommonsMultipartResolver implements HandlerExceptionResolver
{
// This is the Spring bean that handles exceptions
// We defined this in the Java configuration file
#Resource(name = "exceptionResolver")
private AnnotationMethodHandlerExceptionResolver exceptionResolver;
// The multipart exception handler with the #ExceptionHandler annotation
private final MultipartExceptionHandler multipartExceptionHandler = new MultipartExceptionHandler();
// Spring will call this when there is an exception thrown from this
// multipart resolver
#Override
public ModelAndView resolveException(
final HttpServletRequest request,
final HttpServletResponse response,
final Object handlerParam,
final Exception ex)
{
// Notice that we pass this.multipartExceptionHandler
// and not the method parameter 'handlerParam' into the
// exceptionResolver. We do this because the DispatcherServlet
// doDispatch() method calls checkMultipart() before determining
// the handler for the request. If doing the multipart check fails
// with a MultipartException, Spring will never have a reference
// to the handler and so 'handlerParam' will be null at this point.
return exceptionResolver.resolveException(request, response, this.multipartExceptionHandler, ex);
}
}
This seems to be a quite common problem. I've had similar problems and similar questions have been asked, see for example this question. I have yet to see a nice solution to the problem. You could use a vanilla servlet filter to handle these exceptions, but that will duplicate your error handling since you already have an ExceptionHandler.