pass spring context from xml to java - spring-mvc

I´m rewriting a spring context from xml to java class but I don´t know this part:
<interceptors>
<interceptor>
<mapping path="/index.html"/>
<beans:bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
<beans:property name="cacheSeconds" value="0"/>
<beans:property name="useExpiresHeader" value="true"/>
<beans:property name="useCacheControlHeader" value="true"/>
<beans:property name="useCacheControlNoStore" value="true"/>
</beans:bean>
</interceptor>
</interceptors>
I have rewritten this but the interceptors and mapping tags I don´t know:
#Bean
public WebContentInterceptor webContentInterceptor() {
WebContentInterceptor webContentInterceptor = new WebContentInterceptor();
webContentInterceptor.setCacheSeconds(0);
webContentInterceptor.setUseExpiresHeader(true);
webContentInterceptor.setUseCacheControlHeader(true);
webContentInterceptor.setUseCacheControlNoStore(true);
return webContentInterceptor;
}

Assuming you have a class like WebConfig where you have added #EnableWebMvc, modify it to something like the following:
#EnableWebMvc
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
final WebContentInterceptor webContentInterceptor = new WebContentInterceptor();
//the rest of the initialization here
registry.addInterceptor(webContentInterceptor).addPathPatterns("/index.html);
}
}

Related

Hibernate forming the query wrong for insert

I have a registration page, which values I am trying to insert values into the mysql DB.
The code as below
Controler Class
#RequestMapping(value="/register",method=RequestMethod.POST)
public String registerDetails(#ModelAttribute("register")Register register)
{
boolean result=registerService.registerDetails(register);
if(result)
return "register";
else
return "error";
}
ServiceClass
#Override
#Transactional
public boolean registerDetails(Register register) {
// TODO Auto-generated method stub
registerDAO.registerDetails(register);
return true;
}
DAO Class
#Override
public boolean registerDetails(Register register) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
session.persist(register);
return true;
}
config xml file
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/nodedb" />
<beans:property name="username" value="root" />
<beans:property name="password" value="rJGonEQQCrshs81f5LJg0naD+wsG49slpGgldbRJRFo=" />
</beans:bean>
<!-- Hibernate 4 SessionFactory Bean definition -->
<beans:bean id="hibernate4AnnotatedSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.journaldev.spring.model.Person</beans:value>
<beans:value>com.journaldev.spring.model.Register</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<beans:bean id="personDAO" class="com.journaldev.spring.dao.PersonDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="personService" class="com.journaldev.spring.service.PersonServiceImpl">
<beans:property name="personDAO" ref="personDAO"></beans:property>
</beans:bean>
<beans:bean id="registerDAO" class="com.journaldev.spring.dao.RegisterDAOImpl">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="registerService" class="com.journaldev.spring.service.RegisterServiceImpl">
<beans:property name="registerDAO" ref="registerDAO"></beans:property>
</beans:bean>
<context:component-scan base-package="com.journaldev.spring" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate4AnnotatedSessionFactory" />
</beans:bean>
Model class
package com.journaldev.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Register")
public class Register {
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String emailId;
private String fName;
private String lName;
private String password;
private String cpassword;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConPassword() {
return cpassword;
}
public void setConPassword(String conPassword) {
this.cpassword = conPassword;
}
}
My DDL query
CREATE TABLE `Register` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`emailId` varchar(50) NOT NULL DEFAULT '',
`fname` varchar(20) DEFAULT NULL,
`lname` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`conpassword` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
)
here is the stacktrace
Hibernate: insert into Register (cpassword, emailId, fName, lName,
password) values (?, ?, ?, ?, ?)
WARN : org.hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error:
1054, SQLState: 42S22
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Unknown column
'cpassword' in 'field list'
Jul 20, 2019 10:48:30 PM org.apache.catalina.core.StandardWrapperValve
invoke
SEVERE: Servlet.service() for servlet [appServlet] in context with path
[/SpringMVCHibernate] threw exception [Request processing failed;
nested
exception is org.hibernate.exception.SQLGrammarException: could not
execute statement] with root cause
java.sql.SQLSyntaxErrorException: Unknown column 'cpassword' in 'field
list'
Any idea where I am doing wrong ? I am a newbie to this technology and thus a simple question, But I feel there is slight mistake and I am not able to figure it out.
In your table column name is conpassword but in model class it is cpassword. May be you have changed the name later and setters are still like that way.
So, you can rename them in same way, then regenerate the setter(to avoid misunderstanding) again , delete the table and try building/running your project again.
Hope, this will work

Can an abstract class extend JdbcDaoSupport/NamedParameterJdbcDaoSupport in Spring MVC?

I'm trying to implement a Spring MVC web-app (using Spring-FW-ver: 4.3.1). And my web-app's DAO layer architecture is as follows :-
//1. BaseDAO interface
public interface BaseDAO {
//abstract methods
}
//2. BaseDAOJdbcImpl.java file - an abstract DAO class for common method(s) which other sub-DAO classes can inherit
#Repository
public abstract class BaseDAOJdbcImpl extends NamedParameterJdbcDaoSupport implements BaseDAO
{
// implementations of above BaseDAO abstract methods
}
//3. UserDAO interface that extends BaseDAO interface
public interface UserDAO extends BaseDAO {
//abstract methods for User
}
//4. UserDAOJdbcImpl.java class file
#Repository
public class UserDAOJdbcImpl extends BaseDAOJdbcImpl implements UserDAO
{
// implementations of above UserDAO abstract methods
}
And the webapp-servlet.xml Spring-MVC config file :-
.
.
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="springcrud"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/pmsDS"/>
</bean>
<bean id="baseDAOJdbcImpl" class="springcrud.dao.BaseDAOJdbcImpl">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles3.TilesView
</value>
</property>
</bean>
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
.
.
I'm getting the following error :-
java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required
The dataSource object is not being injected into DAO layer. Is the above DAO layer architecture valid or is it a problem with Spring configuration?

Mockito doesn't mock in spring mvc controller test

I have controller
#Controller
public class AuthorController {
#Autowired
private AuthorDAO authorDao;
#RequestMapping("/authors")
public String showAuthor(#RequestParam String name, ModelMap model) {
Author author = authorDao.findByName(name);
model.addAttribute("author", author);
return "authors";
}
}
I wrote test for it
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:test-application-context.xml"})
public class AuthorControllerTest {
private static final String JACK_C = "Jack C.";
#Autowired
AuthorController controller;
#Test
public void testShowAuthor() {
Author expectedAuthor = new Author();
AuthorDAO daoMock = mock(AuthorDAO.class);
when(daoMock.findByName(JACK_C)).thenReturn(expectedAuthor);
ModelMap model = new ModelMap();
String view = controller.showAuthor(JACK_C, model);
assertEquals("View name is incorrect","authors", view);
assertSame(expectedAuthor, model.get("author"));
verify(daoMock).findByName(JACK_C);
}
}
test-application-context.xml:
<context:annotation-config />
<context:component-scan base-package="com.github.futu" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property
name="url" value="jdbc:mysql://localhost:3306/blog" /> <property name="username"
value="blogger" /> <property name="password" value="blogger" /> </bean>
<bean id="com.github.futu.dao.AuthorDAO" class="com.github.futu.dao.impl.AuthorDAOXml"/>
<bean id="com.github.futu.dao.PostDAO" class="com.github.futu.dao.impl.PostDAOXml" />
<bean id="validator" class="com.github.futu.validator.PostValidator" />
But real dao is called. What have I missed?
You're creating a mock here
AuthorDAO daoMock = mock(AuthorDAO.class);
that is completely unrelated to your controller injected into your test class
#Autowired
AuthorController controller;
Of course the autowired AuthorDao target is going to come from your XML configuration
#Autowired
private AuthorDAO authorDao;
Ideally you would change your XML configuration only produce a #Controller bean and add a setter to it to set the AuthorDao from within the test, using your mock.

Spring mvc not able to read messages.properties file

I am trying to use custom validation error messages by using properties file. I have placed messages.properties file in web content/web-inf/ folder.
NonEmpty.batchDomain.batchName=Invalid message 2.
My applicationContext file is :
<context:component-scan base-package="com.coaching.controller" />
<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views
directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:default-servlet-handler />
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages" />
</bean>
And my controller is :
#RequestMapping(method = RequestMethod.POST)
public ModelAndView addBatch(
#Valid #ModelAttribute("batchDomain") BatchDomain batchDomain,
BindingResult result, HttpServletRequest request,
HttpServletResponse response) throws Exception {
try {
if (result.hasErrors()) {
ModelAndView modelAndView = new ModelAndView("newBatch");
return modelAndView;
}
}
BatchDomain is :
public class BatchDomain {
#NotNull
#NotEmpty
#Size(min = 1, max = 100)
private String batchName;
#Min(1)
#Max(1000)
private int strength;
}
As far as I have seen in google, I am following the correct approach. So, what can be the reason behind this issue?
You may try to put file "messages.properties" in /src/main/resource directory.

spring-mvc: error mapping url for form controller

i have a problem with spring mvc
my spring bean
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean
class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="welcome.htm">welcomeController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
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>
<bean name="welcomeController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="welcome" />
<bean name="/bscList.htm" class="cbs.web.BscController">
<property name="bscDao" ref="myBscDao" />
</bean>
<bean name="/bscForm.htm" class="cbs.web.BscFormController">
<property name="commandName" value="bsc"/>
<property name="commandClass" value="cbs.domain.Bsc"/>
<property name="formView" value="bscForm"/>
<property name="successView" value="bscList.htm"/>
<property name="bscDao" ref="myBscDao"/>
</bean>
</beans>
my form controller
public class BscFormController extends SimpleFormController {
private static Logger log = Logger.getLogger(BscController.class);
private BscDao bscDao;
public void setBscDao(BscDao bscDao) {
this.bscDao = bscDao;
}
protected Object formBackingObject(HttpServletRequest request)
throws Exception {
String id = request.getParameter("id");
if (!StringUtils.isBlank(id)) {
return bscDao.get(new Integer(id));
}
return new Bsc();
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
log.debug("entering 'onSubmit' method...");
Bsc bsc = (Bsc) command;
String success = getSuccessView();
if (request.getParameter("delete") != null) {
bscDao.remove(bsc.getId());
} else {
bscDao.save(bsc);
}
return new ModelAndView(success);
}
}
my problem:
when I access /bscList.htm, it's display list of bsc (bscList.jsp template),
but when I access /bscForm.htm, it's still display bsc's list, not show my form (bscForm.jsp template)
I have test with some simple controller:
controller implement org.springframework.web.servlet.mvc.Controller, evething run fine
controller extends SimpleFormController, map error:
No mapping found for HTTP request with URI [/cbs/testform.htm] in DispatcherServlet with name 'dispatcher'
when i use HandlerMapping ControllerClassNameHandlerMapping, all request URL '/bsc*' will map to BscController (/bscForm.htm will not map to BscFormController)

Resources