Spring3.2 MVC框架搭建

最近要做一個Web項目,採用了Spring的MVC框架,特此記錄下這次搭建過程

1.準備Spring所需的MVC,IOC,數據庫等Jar包:

wKioL1TB46PiwfVXAAIB0_z3dxM216.jpg

spring配置文件:

wKioL1TCDWDyMlBrAABQQKqI53I159.jpg


2.Web.xml文件

  配置攔截請求DispatcherServlet,上下文監聽器SpringContext,過濾器Filter

  <!-- 配置DispatcherServlet,指定攔截.do的請求,  請求轉發給對應的Controller處理 -->
  <servlet>
    <servlet-name>DtServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/*-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DtServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>customDim.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置Spring的上下文監聽器,並且指定Spring的xml配置文件的路徑 -->
  <listener>
    <listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>
  
  
  <!-- 配置filter,返回UTF-8編碼的數據格式 -->
  <filter>  
    <filter-name>characterEncodingFilter</filter-name>  
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    <init-param>  
        <param-name>encoding</param-name>  
        <param-value>UTF-8</param-value>  
    </init-param>  
    <init-param>  
        <param-name>forceEncoding</param-name>  
        <param-value>true</param-value>  
    </init-param>  
  </filter>  
  <filter-mapping>  
      <filter-name>characterEncodingFilter</filter-name>  
      <url-pattern>/*</url-pattern>  
  </filter-mapping>


3. spring-context.xml上下文監聽器文件配置:IOC對象初始化

    <context:property-placeholder location="classpath:jdbc.properties" /> 
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
         destroy-method="close">  
        <property name="driverClassName" value="${jdbc.driver}" />  
        <property name="url" value="${jdbc.url}" />  
        <property name="username" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <property name="maxWait" value="${jdbc.maxWait}" />
        <property name="defaultAutoCommit" value="${jdbc.defaultAutoCommit}" />
    </bean>  
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
    
     <bean id="dataDao" class="com.sun.dt.dao.impl.DataDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    
    <bean id="dataService" class="com.sun.dt.service.impl.DataServiceImpl">
        <property name="dataDao" ref="dataDao"></property>
    </bean>

4. jdbc.properties文件

jdbc.driver=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@127.0.0.1:1526:testdb
jdbc.username=test001
jdbc.password=123456
jdbc.maxActive=10
jdbc.maxIdle=3
jdbc.maxWait=5
jdbc.defaultAutoCommit=false


5.spring-mvc.xml中MVC攔截後轉發配置controller

<beans:beans>
<!-- 加載Spring的全局配置文件 -->
<beans:import resource="spring-context.xml" />
<!-- SpringMVC配置 -->
<!-- 通過component-scan 讓Spring掃描com.sun.dt.controller下的所有的類,讓Spring的代碼註解生效 -->
<context:component-scan base-package="com.pingan.dt.controller"></context:component-scan>
<!-- 配置SpringMVC的視圖渲染器, 讓其前綴爲:/ 後綴爲.jsp  將視圖渲染到/page/<method返回值>.jsp中 -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/page/" p:suffix=".jsp">
</beans:bean>
</beans:beans>

6.MVC中Conntroller類

  通過spring-mvc.xml文件中配置攔截的請求都轉給com.sun.dt.conntroller類處理,類中可針對不同不同URL請求給不同的conntroller類和其方法處理

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/data/*")
public class DataController {

	@Resource(name = "dataService") 
	private DataService dataService;
	
	private  String username = "test001";
	
	private String code = "";

	//獲取維度機構信息
	@RequestMapping(value="department",method=RequestMethod.GET) 
    public  @ResponseBody List department(){  
		ArrayList<Department> list = dataService.getDepartmentInfo(code);
        return list;  
    } 
	
	
	@RequestMapping(value="catgory1",method=RequestMethod.GET) 
    public void catgory11(String username,HttpServletResponse response){  
	 
	    String jsonString = dataService.getCategoryInfo(username);
	    try {
		    response.setCharacterEncoding("UTF-8"); 
	        response.setContentType("text/json");   
			PrintWriter out = response.getWriter();
	        out.print(jsonString); 
	        out.flush();  
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    } 
	
	//獲取用戶自定義維度信息
	@RequestMapping(value="catgory",method=RequestMethod.GET) 
    public void catgory(PrintWriter printWriter){  
	 
	    String jsonString = dataService.getCategoryInfo(umName);
        printWriter.write(jsonString); 
	    printWriter.flush();  
	    
    } 
	
	
	// 用戶自定義維度保存接口
	@RequestMapping(value="dimdef",method=RequestMethod.POST) 
    public @ResponseBody Map<String,String> dimdef(@RequestParam("json")String json){  
		HashMap<String,String> map = new HashMap<String,String>();
		
		System.out.println(json);
		if(checkJson(json)){
			dataService.saveDefDimension(umName, json);
			map.put("result", "defined dimension finished");
			map.put("code","1");
			
		}else{
			map.put("result", "json invalid");
			map.put("code","-1");
		}
		return map;
    } 
	
	
	// 用戶樹形結構書籤保存接口
	@RequestMapping(value="marksaving",method=RequestMethod.POST) 
    public @ResponseBody Map<String,String> saveBookMark(@RequestParam("bookmark")String json){  
		HashMap<String,String> map = new HashMap<String,String>();
		System.out.println(json);
		if(checkJson(json)){
			dataService.saveBookMark(umName, json);
			//System.out.println(json);
			map.put("result", "defined dimension finished");
			map.put("code","1");
			
		}else{
			map.put("result", "json invalid");
			map.put("code","-1");
		}
		return map;
    } 
	
	// 用戶獲取書籤獲取書籤列表信息接口
	@RequestMapping(value="marklist",method=RequestMethod.GET) 
    public  @ResponseBody List bookMarkList(){  
		ArrayList<BookMark> list = dataService.getBookMarkList(umName);
        return list;  
    } 
	
	// 用戶獲取書籤節點信息接口
	@RequestMapping(value="bookmark",method=RequestMethod.GET) 
    public void bookMark(PrintWriter printWriter,@RequestParam("markid")String markId){  
		BookMark bm = new BookMark();
		bm.setMarkId(markId);
		bm.setUmName(umName);
	    String jsonString = dataService.getBookMarkInfo(bm);
        printWriter.write((jsonString == null) ? "" : jsonString); 
	    printWriter.flush();  
	    
    } 
	
	// 用戶書籤刪除接口markid=11
	@RequestMapping(value="markdel",method=RequestMethod.GET) 
    public @ResponseBody Map<String,String> delBookMark(@RequestParam("markid")String markId){  
        HashMap<String,String> map = new HashMap<String,String>();
		System.out.println("markdel " + markId);
		if(!markId.equals("")){
			dataService.delBookMark(markId);
			//System.out.println(json);
			map.put("result", "defined dimension finished");
			map.put("code","1");
			
		}else{
			map.put("result", "json invalid");
			map.put("code","-1");
		}
		return map;
    } 
	
	// 用戶書籤刪除接口markid=11
	@RequestMapping(value="markupdate",method=RequestMethod.POST) 
    public @ResponseBody Map<String,String> updateBookMark(@RequestParam("bookmark")String json){
		HashMap<String,String> map = new HashMap<String,String>();
		System.out.println(json);
		if(checkJson(json)){
			dataService.updateBookMark(umName, json);
			//System.out.println(json);
			map.put("result", "defined dimension finished");
			map.put("code","1");
			
		}else{
			map.put("result", "json invalid");
			map.put("code","-1");
		}
		return map;
    } 
	
	private boolean checkJson(String json){
		return true;
	}
	

}

7.瀏覽器中直接輸入

wKioL1TCIRmQg9-_AABWt749LI8864.jpg

即可看見獲取機構返回信息



參考:http://blog.csdn.net/swingpyzf/article/details/8904205

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章