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.
Related
I am stuck with the transaction in Spring.
I don't know why never do a rollback.
Does anybody know what it is happening?
web.xml:
<web-app id="WebApp_ID" 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>Spring Security Application</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-database.xml, /WEB-INF/spring-security.xml</param-value>
</context-param>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
FileCabServiceImpl.java
#Service("FileCabService")
public class FileCabServiceImpl implements FileCabService
{
#Autowired
private FileCabMapper fileCabMapper;
#Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void insertFileCab(FileCab fileCab)
{
fileCabMapper.insertFileCab(fileCab);
throw new NullPointerException(); // Error to do the rollback
}
}
Controller.java:
#RestController
public class ReservationController
{
private final Logger logger = LoggerFactory.getLogger(ReservationController.class);
#Autowired
ReservationServiceImpl reservationService;
#Autowired
FileCabService fileCabService;
#Autowired
FileCounterService fileCounterService;
#RequestMapping(value = "/api/reservation", consumes = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
public void reservationProcess()
{
FileCab fileCab = new FileCab();
fileCab.setnUser("user");
fileCab.setiPax(5);
fileCab.setnNamePax("");
Date dateIn = new Date();
fileCab.setdDateIn(dateIn);
fileCab.setdDateOut(dateIn);
fileCab.setnCodeRef("");
int fileCounter = fileCounterService.getiFileCounterByYear(2017, 1);
fileCab.setnTravelFile(String.valueOf(++fileCounter));
fileCab.setiUserGroup(1);
fileCab.setnYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
fileCab.setdOpenDay(Calendar.getInstance().getTime());
fileCab.setiAgency(0);
fileCab.setnStatus("Cerrado");
fileCab.setbPrePaid(0);
fileCab.setbPaid(0);
fileCab.setdDatePrePaid(null);
fileCab.setDcPrePaidAmount(BigDecimal.ZERO);
fileCab.setiTourService(0);
fileCab.setnObservations("");
fileCabService.insertFileCab(fileCab);
}
}
spring-database.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName">
<context:annotation-config />
<context:component-scan base-package="es.app.spring" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://xxx.xxx.xxxx.xxx:3306/spring_res?autoReconnect=true" />
<property name="username" value="XXXXXX" />
<property name="password" value="XXXXXX" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="es.app.spring.model"/>
<property name="mapperLocations" value="classpath*:es.app.spring.mappers/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="es.app.spring.mappers" />
</bean>
</beans>
Any help will be appreciate.
Thank you
I have my first spring project with a rest service.
Only one problem I cannot solve myself. My "get" request gives the objects date value this way:
{"id":6,"type":"Trainer","changed":"2015-06-20","created":"2015-06-19"}
but I want it in timestamp format, as I thought was the default.
The input dates in my PUT request are parsed from timestamp format as expected.
I am using springframework 4.1.6.RELEASE and fasterxml.jackson 2.5.4
with these spring artifacts: spring-context, spring-webmvc, spring-jdbc
and these fasterxml artifacts: jackson-core, jackson-databind
This is my Controller method:
#Override
#RequestMapping(value="/{id}", method=RequestMethod.GET)
#ResponseBody
public T getObject(#PathVariable("id") long id) {
T obj = dao.getById(id);
logger.debug("GET " + getClass().getSimpleName() + "." + id + ": " + obj);
return obj;
}
My web.xml:
<?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_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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
classpath:Beans.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>
</web-app>
servlet-context.xml:
<?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: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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="de.kreth.clubhelperbackend" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
and my Beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/clubhelperbackend" />
<property name="username" value="markus" />
<property name="password" value="0773" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<bean id="sqlForDialect" class="de.kreth.clubhelperbackend.SqlForMysql">
<constructor-arg ref="jdbcTemplate" />
</bean>
<bean id="personDao" class="de.kreth.clubhelperbackend.dao.PersonDao">
<property name="sqlDialect" ref="sqlForDialect" />
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="dbcheckAspect" class="de.kreth.clubhelperbackend.aspects.MysqlDbCheckAspect">
<constructor-arg ref="dataSource" />
</bean>
<!-- <bean id="logger" class="de.kreth.clubhelperbackend.aspects.LoggerAspect" /> -->
<aop:aspectj-autoproxy>
<aop:include name="dbcheckAspect" />
<!-- <aop:include name="logger"/> -->
</aop:aspectj-autoproxy>
</beans>
So, how can I get the json date output in general as a timestamp?
Please note, that I don't want to change the data classes (getters) as they are generated from another project.
--- Edit:
The Person Model:
public class Person implements java.io.Serializable, Data {
private static final long serialVersionUID = -2810735258874241724L;
private Long id;
private String type;
/** Not-null value. */
private java.util.Date changed;
/** Not-null value. */
private java.util.Date created;
public Person() {
}
public Person(Long id) {
this.id = id;
}
public Person(Long id, String type,java.util.Date changed, java.util.Date created) {
this.id = id;
this.type = type;
this.changed = changed;
this.created = created;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
/** Not-null value. */
public java.util.Date getChanged() {
return changed;
}
/** Not-null value; ensure this value is available before it is saved to the database. */
public void setChanged(java.util.Date changed) {
this.changed = changed;
}
/** Not-null value. */
public java.util.Date getCreated() {
return created;
}
#Override
public void setCreated(Date created) {
this.created = created;
}
}
The date interface:
package de.kreth.clubhelperbackend.pojo;
import java.util.Date;
public interface Data {
public Long getId() ;
public void setId(Long id);
public Date getChanged();
public void setChanged(Date changed);
public Date getCreated();
public void setCreated(Date created);
}
According Jackson docs, Jackson should use timestamps in miliseconds by default.
So I see two options. One is that your date format is enforced by #JsonFormat annotation on your date field as #beerbajay mentioned in his comment.
Second option is that somebody configured custom ObjectMapper for your MappingJacksonHttpMessageConverter. Such example configuration is in this SO answer. I would try to find it in your application and talk to the teammate that introduced it why it's needed.
If such custom ObjectMapper isn't configured, it's strange, but at least you can try to explicitly configure SerializationConfig.getDateFormat as WRITE_DATES_AS_TIMESTAMPS to true.
I think Jackson treats java.util.Date and java.sql.Date differently. Even though the later is actually a subclass of the former, Jackson assumes both classes are totally different.
So, if you don't want the value to be converted to 'yyyy-MM-dd', ensure that it is not a java.sql.Date object.
For example:
class Student {
private java.util.Date birthDate;
// getter and setter
}
Student san = new Student();
// Then JSON converted to: 'yyyy-MM-dd' format
san.setBirthDate(new java.sql.Date(System.currentTimeMillis()));
// Then JSON converted to: timestamp format or according to #JsonFormat format
san.setBirthDate(new java.util.Date());
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).
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 use Spring 3.2.0, JPA 2 AND my IDE is SpringToolSuit 3.1.0.
When I run Test class (main class) I get this exception, I googled but I can not find any solution.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]: Invocation of init method failed; nested exception is java.lang.reflect.UndeclaredThrowableException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1486)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:524)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1117)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:922)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.first.form.Test.main(Test.java:17)
Caused by: java.lang.reflect.UndeclaredThrowableException
at $Proxy3.addTransformer(Unknown Source)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:213)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:286)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1483)
... 12 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager$Jpa2PersistenceUnitInfoDecorator.invoke(DefaultPersistenceUnitManager.java:617)
... 18 more
Caused by: java.lang.IllegalStateException: Cannot apply class transformer without LoadTimeWeaver specified
at org.springframework.orm.jpa.persistenceunit.SpringPersistenceUnitInfo.addTransformer(SpringPersistenceUnitInfo.java:109)
... 23 more
applicationContext.xml is:
<?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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="testJPA"></property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="persistenceAnnotation"
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="userDao" class="com.first.dao.UserDAOImp"></bean>
</beans>
persistence.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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">
<persistence-unit name="testJPA" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.first.entity.UserInfo</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="xxxxx"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
Test class:
package com.first.form;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.first.dao.UserDAO;
import com.first.entity.UserInfo;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("**** "+ applicationContext);
/*UserDAO userDao = (UserDAO) applicationContext.getBean("userDao");
UserInfo userInfo = new UserInfo();
userInfo.setName("name");
userInfo.setFamily("family");
System.out.println("User names is: " + userDao.getAllUsers());
userDao.createUser(userInfo);*/
System.out.println("User is successfully created");
}
}
Try adding
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
Please check here for more details about weaving for JPA
The correct entityManagerFactory should be :
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="testJPA"></property>
</bean>
By this factory we do not need "loadTimeWeaver".
Alternatively ,try adding this to your JVM start parameters
-javaagent:C:/jars/spring-instrument-3.0.4.RELEASE.jar ( or latest version)