I am using the configuration based on java code instead xml files. When I try access any page from my application I get 404 .
These are my Observations:
- When I place blank index.jsp outside pages folder just inside WEB-INF folder ,I can access the page but the jsp inside pages folder is not accessible why ?.
- I guess i am unable to access controller class itself.
- Request Mapping value changes to "" from "/" but it didnt work
- component scan folder set to "pages" on controller class but it didnt work
- Have tried another solutions given by most of the community members for similar question yet I was unable to resolve .
Please help guys . Many Thanks in advance.
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>My ShoppingCart</display-name>
</web-app>
Controller.java :
package controller;
import java.io.IOException;
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.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import dao.OrderDAO;
import dao.ProductDAO;
import entity.Product;
import model.CartInfo;
import model.CustomerInfo;
import model.PaginationResult;
import model.ProductInfo;
import utils.Utils;
import validators.CustomerInfoValidator;
@Controller
@Transactional
@EnableWebMvc
@RequestMapping(value="pages")
public class MainContoller {
@Autowired
private OrderDAO orderDAO;
@Autowired
private ProductDAO productDAO;
@Autowired
private CustomerInfoValidator customerInfoValidator;
@InitBinder
public void myinitBinder(WebDataBinder dataBinder) {
Object target = dataBinder.getTarget();
if(target == null) {
return;
}
System.out.println("Target ="+target);
if(target.getClass() == CartInfo.class) {
}else if(target.getClass() == CustomerInfo.class) {
dataBinder.setValidator(customerInfoValidator);
}
}
@RequestMapping("/403")
public String accessDenied() {
return "/403";
}
@RequestMapping("/")
public String home(){
return "index";
}
@RequestMapping({"/productList"})
public String listProductHandler(Model model,
@RequestParam(value = "name", defaultValue="")String likeName,
@RequestParam(value = "page", defaultValue="1")int page){
final int maxResult = 5;
final int maxNavigationPage = 10;
PaginationResult<ProductInfo> result = productDAO.queryProducts(page, maxResult, maxNavigationPage);
model.addAttribute("PaginationProducts",result);
return "productList";
}
@RequestMapping({"/buyProduct"})
public String listProductHandler(HttpServletRequest request,Model model,
@RequestParam(value = "code",defaultValue = "")String code) {
Product product = null;
if(code!=null && code.length()>0) {
product = productDAO.findProduct(code);
}
if(product!=null) {
CartInfo cartInfo = Utils.getCartInSession(request);
ProductInfo productInfo = new ProductInfo(product);
cartInfo.addProduct(productInfo,1);
}
return "redirect:/shoppingCart";
}
@RequestMapping({"/shoppingCartRemoveProduct"})
public String removeProductHandler(HttpServletRequest request,Model model,
@RequestParam(value = "code",defaultValue="")String code){
Product product = null;
if(code!=null && code.length()>0) {
product = productDAO.findProduct(code);
}
if(product!=null) {
CartInfo cartInfo = Utils.getCartInSession(request);
ProductInfo productInfo = new ProductInfo(product);
cartInfo.removeProduct(productInfo);
}
return "redirect:/shoppingCart";
}
@RequestMapping(value = {"/shoppingCart"},method=RequestMethod.POST)
public String shoppingCartUpdateQty(HttpServletRequest request,
Model model,
@ModelAttribute("cartForm")CartInfo cartForm) {
CartInfo cartInfo = Utils.getCartInSession(request);
cartInfo.updateQuantity(cartForm);
return "redirect:/shoppingCart";
}
@RequestMapping(value= {"/shoppingCart"},method = RequestMethod.GET)
public String shoppingCartHandler(HttpServletRequest request,Model model) {
CartInfo cartInfo = Utils.getCartInSession(request);
if(cartInfo.isEmpty()) {
return "redirect:/shoppingCart'";
}
CustomerInfo customerInfo = cartInfo.getCustomerInfo();
if(customerInfo == null) {
customerInfo = new CustomerInfo();
}
model.addAttribute("customerForm",customerInfo);
return "shoppingCartCustomer";
}
@RequestMapping(value= {"/shoppingCartCustomer"},method = RequestMethod.POST)
public String shoppingCartCustomerSave(HttpServletRequest request,
Model model,
@ModelAttribute("customerForm")@Validated CustomerInfo customerForm,
BindingResult result,
final RedirectAttributes redirectAttributes) {
if(result.hasErrors()) {
customerForm.setValid(false);
return "shoppingCartCustomer";
}
customerForm.setValid(true);
CartInfo cartInfo = Utils.getCartInSession(request);
cartInfo.setCustomerInfo(customerForm);
return "redirect:/shoppingCartConfirmation";
}
@RequestMapping(value= {"/shoppingCartConfirmation"},method = RequestMethod.GET)
public String shoppingCartConfirmationReview(HttpServletRequest request,Model model) {
CartInfo cartInfo = Utils.getCartInSession(request);
if(cartInfo.isEmpty()) {
return "redirect:/shoppingCart";
}else if(!cartInfo.isValidCustomer()) {
return "redirect:/shoppingCartCustomer";
}
return "shoppingCartConfirmation";
}
@RequestMapping(value= {"/shoppingCartConfirmation"},method=RequestMethod.POST)
@Transactional(propagation = Propagation.NEVER)
public String shoppingCartConfirmationSave(HttpServletRequest request,Model model) {
CartInfo cartInfo = Utils.getCartInSession(request);
if(cartInfo.isEmpty()) {
return "redirect:/shoppingCart";
}else if(!cartInfo.isValidCustomer()) {
return "redirect:/shoppingCartCustomer";
}
try {
orderDAO.saveOrder(cartInfo);
}catch(Exception ex) {
ex.printStackTrace();
return "shoppingCartConfirmation";
}
Utils.removeCartInSession(request);
Utils.storeLastOrderedCartInSession(request, cartInfo);
return "redirect:/shoppingCartFinalize";
}
@RequestMapping(value= {"/shoppingCartFinalize"},method=RequestMethod.GET)
public String shoppingCartFinalize(HttpServletRequest request,Model model) {
CartInfo lastOrderedCart = Utils.getLastOrderedCartInSession(request);
if(lastOrderedCart == null) {
return "redirect:/shoppingCart";
}
return "shoppingCartFinalize";
}
@RequestMapping(value= {"/productImage"},method=RequestMethod.GET)
public void productImage(HttpServletRequest request,HttpServletResponse response,Model model,
@RequestParam("code")String code)throws IOException{
Product product = null;
if(code != null) {
product = this.productDAO.findProduct(code);
}
if(product!=null && product.getImage()!=null) {
response.setContentType("image/jpeg,image/jpg,image/png,image/gif");
response.getOutputStream().write(product.getImage());
}
response.getOutputStream().close();
}
}
ApplicationContextConfig.java :
package configuration;
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import dao.AccountDAO;
import dao.OrderDAO;
import dao.ProductDAO;
import daoImpl.AccountDaoImpl;
import daoImpl.OrderDaoImpl;
import daoImpl.ProductDaoImpl;
@Configuration
@ComponentScan("*")
@EnableTransactionManagement
// Load to Environment.
@PropertySource("classpath:ds-hibernate-cfg.properties")
public class ApplicationContextConfig {
// The Environment class serves as the property holder
// and stores all the properties loaded by the @PropertySource
@Autowired
private Environment env;
@Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
// Load property in message/validator.properties
rb.setBasenames(new String[] { "messages/validator" });
return rb;
}
@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// Config for Upload.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
// Set Max Size...
// commonsMultipartResolver.setMaxUploadSize(...);
return commonsMultipartResolver;
}
@Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
// See: ds-hibernate-cfg.properties
dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
dataSource.setUrl(env.getProperty("ds.url"));
dataSource.setUsername(env.getProperty("ds.username"));
dataSource.setPassword(env.getProperty("ds.password"));
System.out.println("## getDataSource: " + dataSource);
return dataSource;
}
@Autowired
@Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) throws Exception {
Properties properties = new Properties();
// See: ds-hibernate-cfg.properties
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
properties.put("current_session_context_class", env.getProperty("current_session_context_class"));
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
// Package contain entity classes
factoryBean.setPackagesToScan(new String[] { "entity" });
factoryBean.setDataSource(dataSource);
factoryBean.setHibernateProperties(properties);
factoryBean.afterPropertiesSet();
//
SessionFactory sf = factoryBean.getObject();
System.out.println("## getSessionFactory: " + sf);
return sf;
}
@Autowired
@Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
@Bean(name = "accountDAO")
public AccountDAO getApplicantDAO() {
return new AccountDaoImpl();
}
@Bean(name = "productDAO")
public ProductDAO getProductDAO() {
return new ProductDaoImpl();
}
@Bean(name = "orderDAO")
public OrderDAO getOrderDAO() {
return new OrderDaoImpl();
}
@Bean(name = "accountDAO")
public AccountDAO getAccountDAO() {
return new AccountDaoImpl();
}
}
SpringWebAppInitializer.java :
package configuration;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
public class SpringWebAppInitializer implements WebApplicationInitializer{
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(ApplicationContextConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("SpringDispatcher",
new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
ContextLoaderListener contextLoaderListener = new ContextLoaderListener(appContext);
servletContext.addListener(contextLoaderListener);
// Filter.
FilterRegistration.Dynamic fr = servletContext.addFilter("encodingFilter", CharacterEncodingFilter.class);
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
Aucun commentaire:
Enregistrer un commentaire