---
# System prepended metadata

title: 準備環境
tags: [Spring  MVC]

---

---
tags: Spring  MVC
---
# 準備環境

## 一、宣告DispatcherServlet所需要的 Java 類別
WebAppConfig.java

```
@Configuration  //代表是組態檔
@EnableWebMvc   //代表啟用WebMvc
@ComponentScan("com.web.store")  //掃描
public class WebAppConfig implements WebMvcConfigurer {

	
	//視圖解析器(通知Spring 框架到哪裡去找 JSP 網頁。)
	@Bean
	public ViewResolver internalResourceViewResolver() {
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();
	resolver.setPrefix("/WEB-INF/views/");//開頭的路徑名稱
	resolver.setSuffix(".jsp");// 尾巴為 .jsp的檔案
	return resolver;
	}	
	
}
```

WebAppInitializer.java

```
@Configuration  //代表是組態檔
@EnableWebMvc   //代表啟用WebMvc
@ComponentScan("com.web.store")  //掃描
public class WebAppConfig implements WebMvcConfigurer {

	
	//視圖解析器(通知	Spring 框架到哪裡去找 JSP 網頁。)
	@Bean
	public ViewResolver internalResourceViewResolver() {
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();
	resolver.setPrefix("/WEB-INF/views/");//開頭的路徑名稱
	resolver.setSuffix(".jsp");// 尾巴為 .jsp的檔案
	return resolver;
	}
	
}

```

## 二、使用資料庫功能 RootAppConfig.java
必須註釋
@Configuration
@EnableTransactionManagement
並且定義
1. javax.sql.DataSource
2. LocalSessionFactoryBean
3. HibernateTransactionManager

```
@Configuration
@EnableTransactionManagement
public class RootAppConfig {

	
	@Bean
    public DataSource dataSource() {
        ComboPooledDataSource ds = new ComboPooledDataSource();
        ds.setUser("sa");
        ds.setPassword("sa123456");
        try {
            ds.setDriverClass("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        ds.setJdbcUrl("jdbc:sqlserver://localhost:1433;databaseName=JSPDB");
        ds.setInitialPoolSize(4);
        ds.setMaxPoolSize(8);
        return ds;
    }
    
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
        factory.setDataSource(dataSource());
        factory.setPackagesToScan(new String[] {
                    "com.web.store.model"
                });
        factory.setHibernateProperties(additionalProperties());
        return factory;
    }
    @Bean(name="transactionManager")
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
         HibernateTransactionManager txManager = new HibernateTransactionManager();
         txManager.setSessionFactory(sessionFactory);
         return txManager;
      }    
    
    private Properties additionalProperties()  {
        Properties properties=new Properties();
        properties.put("hibernate.dialect", org.hibernate.dialect.SQLServer2012Dialect.class);
        properties.put("hibernate.show_sql", Boolean.TRUE);
        properties.put("hibernate.format_sql", Boolean.TRUE);
        properties.put("default_batch_fetch_size", 10);
        //這是給hibernate寫的，spring不能用這個，用了會造成@Transactional無效
       // properties.put("hibernate.current_session_context_class", "thread");
        properties.put("hibernate.hbm2ddl.auto", "update");
        return properties;
    }
}
```


檢查pom檔，有無加入 Hibernate以及spring-orm的 dependency
(其實可以直接複製老師整個pom檔內容)

![](https://i.imgur.com/B8dPeMb.png)

![](https://i.imgur.com/YZCHWz9.png)

最後，確認tomcat的lib下，是否有jdbc的jar檔

![](https://i.imgur.com/9Q5KZGN.png)

## 三、新建類別控制器以( @Controller 修飾的類別)
HomeController(導到index)

```
package com.web.store.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.web.store.service.ProductService;

@Controller//掃描時才知道他是bean的一種
public class HomeController {

	

	
	//將物件放到容器去傳遞，類似getSession.setAttribute功能
	@GetMapping("/welcome")
	
	public String welcome(Model model) {
	model.addAttribute("title", "歡迎蒞臨君雅網路商城!!!");
	model.addAttribute("subtitle", "網路上獨一無二的購物天堂");
	return "welcome";
	}
	
	@GetMapping({"/","/index.html","/bass.html"})  //代表http://localhost:8080/mvcExercise/bass.html 或是
	public String index() {
	return "index";//都會導到index.jsp
	}	
}

```


三、在webapp>WEB>創一個view資料夾，並且將所有的jsp檔案放此，如index
![](https://i.imgur.com/mTOJYwT.png)





