This is my imageForm.jsp:
%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title></title>
</head>
<body>
<h2>Image Form</h2>
<form:form method="POST" action="/showImage">
Picture: <input type="file" name="image">
<br />
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
This is showImage.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<h2>Show Image</h2>
<p>Profile Picture : ${image.image}</p>
</body>
</html>
And this is my controller:
package com.springapp.mvc;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
#RequestMapping(value = "/imageForm")
public ModelAndView showImageForm(Model model) {
return new ModelAndView("imageForm", "command", new Image());
}
#Transactional
#RequestMapping(value = "/showImage")
public ModelAndView showResult(#ModelAttribute("")Image image, ModelAndView model) {
model.setViewName("showImage");
System.out.println("Transaction");
em.persist(image);
System.out.println("persisted");
model.addObject("image", image);
return model;
}
}
This is the Image.java model class:
package com.springapp.mvc;
import javax.persistence.*;
#Entity
public class Image {
#Id
private int imageID;
private byte[] image;
public int getImageID() {
return imageID;
}
public void setImageID(int imageID) {
this.imageID = imageID;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
}
And the persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="NewPersistenceUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.springapp.mvc.Image</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/advocatoree"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
I can choose an image from my PC and when I press the submit button, the showImage.jsp page shows me this: Profile Picture : [B#1c6a19f
The entry is persisted in database, but under the image attribute, it shows: [BLOB - 39 B]
If I click on it, I get a .bin file downloaded. I don't how I should approach this problem, can someone please help me?
the best way to do it - save the picture in any working directory using FileOutputStream, in db you can save unique picture name or path to it. Also you shall receive from the client byte[] in base64 format. The problem may be that you get an byte array represented as string (like "asd561$%#!"), then use Base64.getDecoder().decode(your_string).
Related
this is the java code:i am not getting any error indication but the output of the code is not displayed on the web server.it is showing the web address as:(http://localhost:6027/HttpSearchBar/Example). Tell me whether the local host 6027 is a valid address?
package search.com;
import java.io.IO Exception;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Example extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 102831973239L;
public void dopost (HttpServletRequest hreq, HttpServletResponse hres)throws ServletException, IOException{
System.out.println("hello");
try {
hres.setContentType("text/html");
String s1 = hreq.getParameter("username");
String s2 = hreq.getParameter("password");
ServletContext sc = getServletContext();
if ((s1.equals("abc"))&&(s2.equals("xyz"))) {
hres.sendRedirect("welcome");
}else {
PrintWriter pw = hres.getWriter();
pw.print("invalid username/password");
RequestDispatcher rd = sc.getRequestDispatcher("login.html");
rd.include(hreq, hres);
}
} catch (Exception e) {
// TODO: handle exception
System.err.print(e);
}
} }
this is html code:
<!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=ISO-8859-1">
<title>Example Html</title>
</head>
<body bgcolor=yellow text=blue>
<center>
<h1>
<u>LoginForm</u>
</h1>
<form action="Example" method="post">
UserName<input type="text" name="username">
Password<input type="text" name="Password">
<input type="submit" value="login" /><input type="reset">
</form>
</center>
</body>
</html>
this is web.xml code:
<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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>HttpSearchBar</display-name>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>Example</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/Example</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/Example</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>java.io.IOException</exception-type>
<location>/Example</location>
</error-page>
<error-page>
<exception-type>java.lang. Throw able </exception-type>
<location>/search.com.Example</location>
</error-page>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
<welcome-file>login.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
this is displayed when server is started:
Oct 22, 2018 6:41:52 PM org.apache.catalina.core.ApplicationDispatcher
invoke
WARNING: Servlet Example is currently unavailable
Send a request to http://localhost:6027/ from your browser. If you can see the default Apache Tomcat page the localhost:6027 is a valid address.
There are a couple of reasons that you might not see any response.
Java is case sensitive. Your do post method is incorrect. Replace with doPost
public void doPost(HttpServletRequest hreq, HttpServletResponse hres)
throws ServletException, IOException {
Your html password input name is name="Password", and you are getting it with lowercase p.
String s2 = hreq.getParameter("Password"); //uppercase P
Finally don't use RequestDispatcher, just redirect the page. Replace everything in your else statement.
hres.sendRedirect("login.html");
By referring to the server log that has attached, it seems that you are trying to run your servlet project on apache tomcat server. Default Tomcat port is 8080. That is you should try to access your running app on:
http://localhost:8080
if you want to customize the running port you have to do it using the server.xml file.
I am trying to create rest service using apache camel swagger component.
Now i have this camel context as:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<!-- a bean for user services -->
<bean id="personService" class="www.tempuri.person.PersonService"/>
<camelContext id="myCamel" xmlns="http://camel.apache.org/schema/spring">
<restConfiguration component="servlet" bindingMode="auto" contextPath="myService/rest" port="8080">
<dataFormatProperty key="prettyPrint" value="true"/>
</restConfiguration>
<!-- defines the rest services using the context-path /Equipment -->
<rest path="/getPerson/persons" consumes="application/json,application/xml" produces="application/json,application/xml">
<description>Person rest service</description>
<post uri="/search" type="www.tempuri.person.model.GetPerson"
outType="www.tempuri.person.model.GetPerson">
<description>Get Person(s)</description>
<param name="body" type="body" description="Get Person(s)" required="true"/>
<responseMessage code="400" message="Bad Request" />
<responseMessage code="200" message="Person Data" />
<responseMessage code="401" message="Unauthorized" />
<to uri="bean:personService?method=getPersons"/>
</post>
</rest>
</camelContext>
</beans>
And below is my model class GetPerson:
package www.tempuri.person.model;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonRootName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#ApiModel(description = "Represents Persons")
#XmlRootElement(name="getPerson")
#JsonRootName(value = "getPerson")
public class GetPerson {
#ApiModelProperty(value = "Application Area of GetPerson", required = true)
private ApplicationArea applicationArea;
#ApiModelProperty(value = "Data Area of GetPerson", required = true)
private DataArea dataArea;
/**
* #return the dataArea
*/
public DataArea getDataArea() {
return dataArea;
}
/**
* #param dataArea the dataArea to set
*/
public void setDataArea(DataArea dataArea) {
this.dataArea = dataArea;
}
public ApplicationArea getApplicationArea() {
return applicationArea;
}
public void setApplicationArea(ApplicationArea applicationArea) {
this.applicationArea = applicationArea;
}
}
Now in case of application xml it is working good and the request structure has a root element as getPerson, but in case of JSON Request it doesn't show the root element getPerson. I know that there is something called WRAP_ROOT_VALUE which can be used to enable the root name in case of json. But the problem is i don't know how to do it using camel-config.xml.
How can i set the WRAP_ROOT_VALUE through my camel-config.xml or is there some other way. Thanks in advance..
I am trying to resolve a problem where I cannot return a list with Kundera query for redis back end. I have problem returning a single entity and no problem persistening entities. However when I try to do a simple select to return a single type it always returns me an empty list.
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
https://raw.github.com/impetus-opensource/Kundera/Kundera-2.0.4/kundera-core/src/test/resources/META-INF/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="redis_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>com.factory.ng.api.domain.DomainEntity</class>
<class>com.factory.ng.api.domain.Factory</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="kundera.show.query" value="true" />
<property name="kundera.nodes" value="localhost" />
<property name="kundera.port" value="6379" />
<property name="kundera.keyspace" value="RedisK" />
<property name="kundera.dialect" value="redis" />
<property name="kundera.client" value="redis" />
<property name="kundera.client.lookup.class" value="com.impetus.client.redis.RedisClientFactory" />
<property name="kundera.transaction.resource.class" value="com.impetus.client.redis.RedisTransaction" />
<property name="kundera.indexer.class" value="com.impetus.client.redis.RedisIndexer" />
</properties>
</persistence-unit>
...
Here is the entity that I am trying to retrieve.
#Entity
#XmlRootElement
public class Factory extends DomainEntity implements IHasSlots {
/**
* Serialization Id
*/
private static final long serialVersionUID = 7829467874878679280L;
private String name;
private List<Line> lines;
public Factory() {
this(null);
}
public Factory(String name) {
this(name, new ArrayList<Line>());
}
public Factory(String name, Collection<Line> lines) {
this(name, new ArrayList<Line>(lines));
}
...
This unit test always ends with an assert error that the list is empty.
#Test
public void testList() {
EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("redis_pu");
EntityManager em = emFactory.createEntityManager();
List<Factory> factories = em.createQuery("SELECT e FROM Factory e").getResultList();
//Collection<Factory> factories = factoryDao.list();
Assert.assertTrue(factories.size() > 0);
}
I have given my welcome file in web.xml
But when running the application, it is showing 404 error on http://172.16.2.16:8080/sampletest/
It is a spring application.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>sampletest</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- Spring MVC -->
<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>
</web-app>
I am using eclipse luna, java 8, tomcat 8 and maven framework.
index.html file is directly under webapp folder and web.xml is under webapp/WEB-INF folder.
If I use index.jsp instead of index.html, it is working. Then welcome page will load using http://172.16.2.16:8080/sampletest/
The issue is only with welcome file. Otherwise spring configuration is working.
http://localhost:8080/sampletest/test/ will load the data from database.
Error log in console
......................
Jul 10, 2014 12:38:42 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 4963 ms
Jul 10, 2014 12:38:42 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/sampletest/] in DispatcherServlet with name 'dispatcher'
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
Dispatcher
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<context:component-scan base-package="com.sample.test" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan">
<array>
<value>com.sample.test.domain</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">false</prop>
<prop key="hibernate.use_sql_comments">false</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.connection.characterEncoding">UTF-8</prop>
<prop key="hibernate.connection.useUnicode">true</prop>
<prop key="hibernate.connection.CharSet">UTF-8</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/sampletest?autoConnect=true" />
<property name="user" value="root" />
<property name="password" value="root" />
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- HibernateTransactionManager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="openSessionInViewInterceptor"
class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
<property name="flushModeName">
<value>FLUSH_AUTO</value>
</property>
</bean>
</beans>
Controller
package com.sample.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sample.test.dto.Response;
import com.sample.test.facade.AccelFlowFacade;
#Controller
public class SampleTestController {
#Autowired
#Qualifier("sampleTestFacade")
SampleTestFacade sampleTestFacade;
public SampleTestFacade getSampleTestFacade() {
return sampleTestFacade;
}
public void setSampleTestFacade(SampleTestFacade sampleTestFacade) {
this.sampleTestFacade= sampleTestFacade;
}
#RequestMapping(value = "/test", method = RequestMethod.GET)
public #ResponseBody Response display() throws Exception {
sampleTestFacade.disaply();
Response res = new Response();
return res;
}
}
Try adding <mvc:default-servlet-handler/> in your dispatcher-servlet.xml.
See here for details.
You have mapped all your incoming requests to the dispatcher here,
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
So all your URL requests for the application goes inside the dispatcher as '/' maps all incoming requests . check for the stacktraces in your application server log
update:
You get the below warning because there are no handler for the '/' pattern,
WARNING: No mapping found for HTTP request with URI [/AccelFlow/] in
DispatcherServlet with name 'dispatcher'
You can do either of below options ,
Map a url with '/' to the controller
Add a specific URL pattern to the spring dispatcher such as .htm or .do as you wish
Modify your web.xml,
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
And in your controller,
#RequestMapping(value = "/test.htm", method = RequestMethod.GET)
public #ResponseBody Response display() throws Exception {
accelFlowFacade.disaply();
Response res = new Response();
return res;
}
At the startup by default all incoming requests are mapping to '/' pattern as you write in the web.xml:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
update:
Try to map a Controller method for the default view:
#RequestMapping(value = "/", method = GET)
public String welcome() {
return "index";
}
Add viewresolver to dispather-servlet.xml:
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/"
p:suffix=".jsp" />
Remove welcome file from the web.xml as automatically spring will search for index page by default:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
Welcome file can be access using following changes.
change 1. add resource path in dispatcher as following :
<mvc:resources mapping="/" location="/index.html" />
change 2. add controller handler like following :
#Controller
public class RestController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome() {
return "index.html";
}
}
changes 3: index.html file should be in WebContent folder in project.
Note : If you are not able to add mvc bean in dispatcher servlet file then add
xmlns:mvc="http://www.springframework.org/schema/mvc
in dispatcher servlet config file.
using <mvc:resources mapping="/" location="/index.html" /> is goods for static pages , however changing it to
#RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome() {
return "index.html";
}
is not good design as all model in other controllers may point back to index page, instead use
<mvc:resources mapping="/" location="/redfresh.html" />
and make refresh page such
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="refresh" content="0;URL='/index'" />
</head>
<body>
</body>
</html>
and point in controller to index such:
#Controller
public class indexPageController {
#RequestMapping(value = "/index", method = RequestMethod.GET, produces = "text/html")
public String index() {
return "index";
}
}
Just add your index.html to webContent folder. Because welcome file is searched in that folder itself.
I'm very new to JSP, I'm a front-end developer but for jobs reasons I'm studing to achieve the server-side.
Currently I'm working on a "test" web site with JSP+Spring+MySQL.
Yesterday I was able, not without struggling, to login and logout validating users in the dataspace of the database.
What I'm trying to achieve today is to populate a table on the submit event of a form.
Got this, USERPANEL.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Success</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--script src="./js/ajax.js"></script-->
</head>
<body>
<h1>Hello ${applicationModel.loginModel.userName}!</h1>
<div class="user-control-panel">
<form:form id="logout" action="logout.do" method="post" commandName="logoutDetails">
<input type="submit" value="Logout" />
<input type="hidden" name="userName" id="userName" value="${applicationModel.loginModel.userName}" />
<input type="hidden" name="debugmode" id="debugmode" value="${applicationModel.loginModel.debugmode}" />
</form:form>
</div>
<div>
<form:form id="listAll" action="movies.do" method="post" commandName="moviesDetails">
<input type="submit" value="List movies" />
<input type="hidden" name="minLim" value="-1" />
<input type="hidden" name="maxLim" value="-1" />
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
<th>Subtitled</th>
<th>Dual</th>
<th>Poster</th>
<th>Link</th>
</tr>
</thead>
<tbody>
<c:forEach var="movie" items="${applicationModel.moviesModel.list}">
<tr>
<td>${movie.movieID}</td>
<td>${movie.titulo}</td>
<td>${movie.anyo}</td>
<td>${movie.genero}</td>
<td>${movie.subtitulada}</td>
<td>${movie.dual}</td>
<td>${movie.poster}</td>
<td>${movie.megaLink}</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
</div>
</body>
</html>
MOVIESCONTROLLER.java
package com.wolfchamane.controller;
import com.wolfchamane.model.MoviesModel;
import com.wolfchamane.service.MoviesService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
#Controller
#RequestMapping(value = "/movies")
public class MoviesController {
private MoviesModel moviesModel;
#Autowired
private MoviesService moviesService;
#RequestMapping(method = RequestMethod.GET)
public ModelAndView init(){
moviesModel = new MoviesModel();
return new ModelAndView("movies", "moviesDetails", moviesModel);
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView listAll(
#ModelAttribute("moviesDetails") MoviesModel moviesModel,
BindingResult bindingResult,
HttpServletRequest request,
HttpServletResponse response){
ModelAndView redirectView = null;
if (moviesService.listAll(moviesModel)){
RedirectView view = new RedirectView("userpanel.do", true);
redirectView = new ModelAndView(view);
}
return redirectView;
}
}
MOVIESDAOIMP.java
package com.wolfchamane.dao;
import com.wolfchamane.model.MovieModel;
import java.sql.*;
import com.wolfchamane.model.MoviesModel;
import java.util.ArrayList;
public class MoviesDAOImp implements MoviesDAO{
#Override
public boolean listAll(MoviesModel moviesModel) {
boolean bRet = false;
PreparedStatement pst = null;
Statement st = null;
try{
String query;
ResultSet rs = null;
//SELECT ALL
if ((moviesModel.getMinLim() < 0)&&(moviesModel.getMaxLim() < 0)){
query = "SELECT"
+" m.movie_id AS \"ID\", m.movie_title AS \"TITULO\","
+" m.movie_year AS \"ANYO\", g.genero_text_esES AS \"GENERO\","
+" m.subtitulada AS \"SUBS\", m.`dual` AS \"DUAL\","
+" m.poster AS \"POSTER\", m.megaLink AS \"LINK\""
+" FROM mymovies_movies m, mymovies_generos g"
+" WHERE (m.genero = g.genero_id)"
+" ORDER BY m.movie_title;";
st = ConnectionDAO.getStatement(moviesModel.isDebugmode());
rs = st.executeQuery(query);
}
if (rs != null){
ArrayList<MovieModel> list = new ArrayList();
while(rs.next()){
MovieModel aux = new MovieModel();
aux.setMovieID(rs.getInt("ID"));
aux.setTitulo(rs.getString("TITULO"));
aux.setAnyo(rs.getInt("ANYO"));
aux.setGenero(rs.getString("GENERO"));
aux.setSubtitulada((rs.getInt("SUBS") == 1));
aux.setDual((rs.getInt("DUAL") == 1));
aux.setPoster(rs.getString("POSTER"));
aux.setMegaLink(rs.getString("LINK"));
list.add(aux);
}//while
moviesModel.setList(list);
}
else
bRet = false;
if (st != null)
st.close();
if (pst != null)
pst.close();
if (rs != null)
rs.close();
}catch(SQLException sql){
System.out.println("SQL Exception: "+sql.getMessage());
bRet = false;
}finally{
return bRet;
}
}
}
MOVIESSERVICEIMP.java
package com.wolfchamane.service;
import com.wolfchamane.dao.MoviesDAO;
import com.wolfchamane.model.MoviesModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service("MoviesService")
public class MoviesServiceImp implements MoviesService{
#Autowired
MoviesDAO moviesDAO;
#Override
public boolean listAll(MoviesModel moviesModel){
return moviesDAO.listAll(moviesModel);
}
}
WEB.XML
<?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">
<display-name>MyMoviesAPP</display-name>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login.jsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>dashboard</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dashboard</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
SERVLETS
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.wolfchamane" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.wolfchamane" />
<mvc:annotation-driven />
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
I always get the following error:
javax.servlet.ServletException: Servlet.init() para servlet login lanzó excepción
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'moviesController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.wolfchamane.service.MoviesService com.wolfchamane.controller.MoviesController.moviesService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MoviesService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.wolfchamane.dao.MoviesDAO com.wolfchamane.service.MoviesServiceImp.moviesDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.wolfchamane.dao.MoviesDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
java.lang.Thread.run(Thread.java:722)
What should I change/add/modify?
The former idea is that when logged user clicks on "List All" button, the table bellow will populated with the data from the database.
have you specified <context:component-scan base-package="com.telemedicine." /> for scanning package
in which "MovieService" contained. use #Repository in dao impl.
Suggestion :use SimpleJdbcTemplate + SimpleJdbcDaoSupport it will remove JDBC boilerplate code.