JSP linking with Java Servlet BackEnd Code - spring

I am trying to link my Jsp page with my servlet but I'm getting this error :
javax.servlet.ServletException: Servlet.init() for servlet ImageServlet threw exception
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered`
Below is my Servlet code :
package servlet;
#Component("ImageServlet")
public class ImageServlet implements HttpRequestHandler {
#Autowired
imageDA imageda = new imageDA();
ResultSet rs = null;
byte[] thumb ;// get the thumb from the user entity
#Override
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int generatedDocId = Integer.parseInt(request.getParameter("generatedDocId"));
try{
rs = imageda.getAllImage(generatedDocId);
if(rs.next()){
thumb = rs.getBytes("IMAGE");
}
}catch(SQLException ex){
ex.getMessage();
}
String name = "images";
response.setContentType("image/jpeg");
response.setContentLength(thumb.length);
response.setHeader("Content-Disposition", "inline; filename=\"" + name+ "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new ByteArrayInputStream(thumb));
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[8192];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} catch (IOException e) {
System.out.println("There are errors in reading/writing image stream "
+ e.getMessage());
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ignore) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ignore) {
}
}
}
}
}
and this is my XML code linking to my viewData.jsp JSP page :
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/viewData.jsp</url-pattern>
</servlet-mapping>
</web-app>
Edited, here is my full version of XML codes. I use most of them for my Request.getPart(), tried to configure XML for spring but it doesn't work.Thanks for helping
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<servlet>
<servlet-name>UploadFile</servlet-name>
<jsp-file>/projectAddData.jsp</jsp-file>
<multipart-config>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile</servlet-name>
<url-pattern>/projectAddData.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UploadFile1</servlet-name>
<jsp-file>/addClaim.jsp</jsp-file>
<multipart-config>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>
<servlet>
<servlet-name>UploadServlet1</servlet-name>
<servlet-class>UploadServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile1</servlet-name>
<url-pattern>/addClaim.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UploadFile2</servlet-name>
<jsp-file>/addInvoice.jsp</jsp-file>
<multipart-config>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
</servlet>
<servlet>
<servlet-name>UploadServlet2</servlet-name>
<servlet-class>UploadServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadFile2</servlet-name>
<url-pattern>/addInvoice.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/viewData.jsp</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- The path to your main spring xml file, for example: /WEB-INF/spring-config.xml -->
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>

The exception is telling you that although you intend to use spring, the ApplicationContext can't be loaded due to the absence of a required listener configuration. Spring needs to know the path to your main bean config file, and the missing listener is what it uses to find that information.
Add this to your web.xml (as a child of the root <web-app> element, and your web app will start (or at least make it past the error you're getting now).
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- The path to your main spring xml file, for example: /WEB-INF/spring-config.xml -->
<param-value>/WEB-INF/spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

Related

How to setup uploaded file's path in Spring MVC

I want to have uploaded file to be stored in my specified folder like this:
/SpringMVC/tmp
but it is stored into this folder:
C:\Users\zhanzhex\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\SpringMVC\tmp\spittr\uploads
this is my controller method for processing uploading:
#RequestMapping(value="/register", method=RequestMethod.POST)
public String processRegistration(
#RequestPart(name="profilePicture",required=false) Part profilePicture,
#Valid Spitter spitter, Errors errors) throws IOException
{
if (errors.hasErrors())
{
System.out.println("find errors");
return "registerForm";
}
profilePicture.write(spitter.getId() + "_profile." + profilePicture.getSubmittedFileName().substring(profilePicture.getSubmittedFileName().indexOf(".") + 1));
spitterRespository.saveSpitter(spitter);
return "redirect:/spitter/"+spitter.getId();
}
I just configure the temp folder for file upload (/tmp/spittr/uploads) in my web.xml, but I want to change the folder while calling write method within controller method, seems I can't. if I calling the write method like this:
profilePicture.write("/tmp/spittr/uploads/" + spitter.getId() + "_profile.jpg");
it will throw IOException to indicate that the folder is not existing:
C:\Users\zhanzhex\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\SpringMVC\tmp\spittr\uploads\tmp\spittr\uploads
so, I have to remove prefix "/tmp/spittr/uploads" when I calling profilePicture.write method.
see my web.xml below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVCs</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>spittr.config.RootConfig</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>spittrAppServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>spittr.config.WebConfig</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>/tmp/spittr/uploads</location>
<max-file-size>2097152</max-file-size>
<max-request-size>4194304</max-request-size>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>spittrAppServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I don't know why, can I change the destination folder setting? How to do that?
Instead of Part you can use MultipartFile or FilePart interfaces
#RequestPart(name="profilePicture",required=false) MultipartFile profilePicture
These interfaces expose .transferTo() function to copy data to file that you can use like
profilePicture.transferTo(new File("/path/to/file"));

below listener configuration not working in web.xml for spring application

The below ContextListener is my self-defined class and below is the code for it and the medthods defined in are not getting called .i;m not sure what internally is happening.please help me on this
package com.apalya.promo.properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import org.apache.log4j.Logger;
public class ContextListener {
Logger logger = Logger.getLogger(ContextListener.class);
public void contextInitialized(ServletContextEvent servletContextEvent) {
logger.info(" !!!!!!!!PromoTv module is Going To Be Deployed
!!!!!!!! ");
System.out.println(" !!!!!!!!PromoTv module is Going To Be
Deployed !!!!!!!! ");
try {
Context ctx = new InitialContext();
ServerProperties.setConfigMap();
ServerProperties.setDbQueriesMap();
} catch (Exception e) {
logger.info(" ########### Error In ServletContextListener
Class ######### :: " + e);
}
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
logger.info(" ++++++++++ PromoTv module is Going to Stop
++++++++++++ ");
System.out.println(" ++++++++++ PromoTv module is Going to Stop
++++++++++++ ");
}
}
`
and here is my web.xml file where i configured listener class for my user-defined class and it looks like it is not getting invoked.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com
/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Archetype Created Web Application</display-name>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
com.apalya.promo.properties.ContextListener
</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

spring mvc annotation many servlet dispatcher

Hi I am just starting to learn Spring mvc, I use spring mvc #annotation and I have 3 servlets dispatchers (appservlet, admin, student):
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/admin-servlet.xml</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>student</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>admin</servlet-name>
<url-pattern>*.admin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>student</servlet-name>
<url-pattern>*.student</url-pattern>
</servlet-mapping>
</web-app>
After a test in a method I want a redirect to another servlet dispatcher, either the .admin or a .student. How can I do that please?
#controller
#Controller
public class AuthentificationController {
#RequestMapping(value = "verifier", method = RequestMethod.POST)
public ModelAndView redir(#ModelAttribute("per") Personne per,
HttpSession session) {
if (p1.equals(per)) {
session.setAttribute("login", per);
ModelAndView M = new ModelAndView(".admin");
return M;
}
if (p2.equals(per)) {
ModelAndView M = new ModelAndView(".student");
return M;
} else {
ModelAndView M = new ModelAndView("home");
return M;
}
}
}
The problem is that ModelAndView returns (.jsp) but I want a redirection for another servlet-dispatcher !!
Here you are:
#RequestMapping(value = "verifier", method = RequestMethod.POST)
public String redir(#ModelAttribute("per") Personne per, HttpSession session) {
if (p1.equals(per)) {
session.setAttribute("login", per);
return "redirect:.admin";
} else if (p2.equals(per)) {
return "redirect:.student"
} else {
return "home";
}
}

how to handle url that are not mapped in spring

My dispatcher servlet mapping
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springconfig/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
And the controller has handler like
#RequestMapping("moduleone")
public class ApplicationController {
#RequestMapping(value="Login.html",method=RequestMethod.GET)
public ModelAndView showLoginPage(){
ModelAndView mv=new ModelAndView("../moduleone/Login");
mv.addObject("loginForm", new LoginForm());
return mv;
}
#RequestMapping(value="Home.html", method = RequestMethod.GET)
public ModelAndView showHome(HttpServletRequest request) {
ModelAndView mv=new ModelAndView("Home");
mv.addObject("customerName",appCon.getFirstName() );
return mv;
}
}
Is it possible to handler request that are not mapped in controller
like
http://localhost:8090/Project/moduleone/invalidpage.html
http://localhost:8090/Project/moduleone/invalidurl/invalidpage
I have tried #RequestMapping(value="*",method=RequestMethod.GET) but doest work
As 404 (page not found) actually produces an exception on web container level, containers usually provide an exception handling mechanism, thus you can try exception (or so called error) handling, as shown below;
First create a controller
#Controller
public class PageNotFoundErrorController {
#RequestMapping(value="/pageNotFound.html")
public String handlePageNotFound() {
// do something
return "pageNotFound";
}
}
and configure web.xml in order to map the error to the controller written above;
<error-page>
<error-code>404</error-code>
<location>/pageNotFound.html</location>
</error-page>
you can also extend it by simply adding 403, 500 and other error-codes to web.xml and mapping them to any controller.
What is even more fascinating is that you can also map any exception (even the ones created by your code); here you can find a nice example about it http://www.mkyong.com/spring-mvc/spring-mvc-exception-handling-example/
I try the code block and if change your scenario a bit i can handle it.
//This one is OK
http://localhost:8090/Project/moduleone/invalidpage.html
//add invalid.html not a folder it should be file
http://localhost:8090/Project/moduleone/invalidurl/invalidpage.html
HomeController.java
#RequestMapping(value = {"*/*.html","*.html"}, method = RequestMethod.GET)
public String test(HttpServletResponse response) throws IOException {
return new String("home");
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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>TestSpringMVC</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springconfig/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
I can handle both request with this way.
I think you should define an exception page for your second scenario.
Also you can read this issue

Apache CXF with Spring

I am using Apache CXF with Spring , please tell me how the CXFServlet reads the myapp-ws-context.xml
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:myapp-ws-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<display-name>CXF Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Have you seen sources of org.apache.cxf.transport.servlet.CXFServlet (open source)?
Everything is more than explicit:
#Override
protected void loadBus(ServletConfig sc) {
ApplicationContext wac = WebApplicationContextUtils.
getWebApplicationContext(sc.getServletContext());
String configLocation = sc.getInitParameter("config-location");
if (configLocation == null) {
try {
InputStream is = sc.getServletContext().getResourceAsStream("/WEB-INF/cxf-servlet.xml");
if (is != null && is.available() > 0) {
is.close();
configLocation = "/WEB-INF/cxf-servlet.xml";
}
} catch (Exception ex) {
//ignore
}
}
if (configLocation != null) {
wac = createSpringContext(wac, sc, configLocation);
}
if (wac != null) {
setBus(wac.getBean("cxf", Bus.class));
} else {
setBus(BusFactory.newInstance().createBus());
}
}
Note that WebApplicationContextUtils is a Spring class that tries to find an application context in servlet context attribute named: org.springframework.web.context.WebApplicationContext.ROOT.
Actually your classpath:myapp-ws-context.xml is read by Spring, not CXF.
By adding below configuration in your web.xml, it would be read by Spring and the context would be loaded:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:myapp-ws-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
But you could configure your Servlet/WebApp scope of Spring objects, like multipartResolver etc., to make the objects' scopes clearly, by enhancing your CXFServlet configuration like below:
<servlet>
<display-name>CXF Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<init-param>
<param-name>config-location</param-name>
<param-value>/WEB-INF/your-webapp-scope-spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
*Please take note that from your web-app context, you can access all objects in the context loaded from contextConfigLocation. *

Resources