天天看點

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢

  1. 配置好eclipse的所需環境,jdk,tomcat
  2. 建立一個動态網頁 Dynamic Web Projec工程
  3. 在WebContent檔案夾下的下建立要給index.jsp檔案,然後啟動項目,看是否啟動成功。
  4. 開始搭建Spring mvc 架構 在WEB-INF檔案夾下的lib檔案夾中導入所需要的相關jar包,直接在官網下載下傳SpringFramework的GA(釋出)版本,然後将檔案夾中的jar包導入以上目錄中。此外還需要自己下載下傳commons-logging,jstl和standard相關的jar包。并且也導入。
    eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
  5. 在src目錄下建立config目錄,并在目錄下建立applicationContext.xml (spring規定)注意這裡的檔案夾和檔案名都時固定的不可修改。并在配置檔案中先填入以下代碼
    eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<?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:aop="http://www.springframework.org/schema/aop"
	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.xsd">

	<!-- 開啟Spring全文注解功能識别的标簽 -->
	<context:annotation-config />
	<!-- base-package指定包掃描路徑及其以下所有子包 -->
	<context:component-scan base-package="com.guoqi" />
</beans>
           
  1. 在config目錄下再建立一個springmvc.xml檔案,這裡是用于springmvc使用。并在配置檔案中配置掃描功能和視圖解析器,如果前後端分離的方式則不用設定視圖解析器。
    eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<?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">

	<!-- control層的注解掃描路徑 -->
	<context:component-scan
		base-package="com.guoqi.control" />
	<!-- 開啟SpringMVC的注解功能 -->
	<mvc:annotation-driven />

	<!-- 設定加載内部視圖解析器,如果前後端分離則不用此項 
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置視圖解析的字首 -->
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!-- 配置視圖解析的字尾 -->
		<property name="suffix" value=".jsp" />
	</bean>
</beans>-->
           
  1. 然後src下建立包,并且再建立一個測試用的controller,并在測試用的controller中寫入以下内容: (在寫入以下内容時侯注意導入相應包)
eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
package com.guoqi.control; 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class TestController {

	@RequestMapping("/hello")
	public String hello() {
		System.out.println("Hello SpringMVC!");
		return null;
	}
}	
           

在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_4_0.xsd"
	id="WebApp_ID" version="4.0">
	<display-name>RuanTong0305</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<context-param>
		<!-- 加載配置spring變量 -->
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:*applicationContext.xml</param-value>
	</context-param>
	<!-- 加載spring的監聽器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置前端控制器的核心配置, 使用視圖層必要配置 -->
	<servlet>
		<servlet-name>DispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置初始化參數,從springmvc.xml中加載參數 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:*springmvc.xml</param-value>
		</init-param>
	</servlet>

	<!-- 設定攔截發往主機的所有.do請求 -->
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>
           

設定完後儲存然後啟動項目,通過位址欄http://localhost:8080/RuanTong0304/hello.do通路到指定的controller,這裡頁面會顯示404,因為我們在hello控制器寫的傳回内容為null,是以顯示404。但是控制台已經輸出我們的内容,說明我們寫的代碼沒有問題。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢

現在設定一個可以跳轉的頁面的controller中的方法。在剛才的controller中添加一個新方法。這點新代碼表示當請求index.do時候,傳回一個視圖,視圖為index.jsp

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
@RequestMapping("/index")
	public String index() {
		System.out.println("Hello indexJSP!");
		return "index.jsp";
	}
           

然後通過浏覽器輸入http://localhost:8080/RuanTong0304/index.do通路到目前的方法,并且成功跳轉到index.jsp頁面中。同時注意,項目中WEB-INF下的頁面都是外部不能通路的(位址欄輸入内容無法通路),隻能通過内部調用才可以通路。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢

下一步要和資料庫進行連接配接,建立一個實體類。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
package com.guoqi.bean;

public class Test {
	private int id;
	private float sum;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public float getSum() {
		return sum;
	}

	public void setSum(float sum) {
		this.sum = sum;
	}

	@Override
	public String toString() {
		return "Test [id=" + id + ", sum=" + sum + "]";
	}

}

           

再建立一個實體類對應的DAO類,申明通路資料的方法

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
package com.guoqi.dao;

import java.util.List;

import com.guoqi.bean.Test;

public interface TestDAO { 
	
	// 添加
	public int insert(Test test); 
	// 删除
	public int delete(int id); 
	// 修改
	public int update(Test test); 
	// 根據ID擷取指定資料
	public Test getTestById(int id); 
	// 查詢所有
	public List<Test> selectAll();

}

           

再建立一個資料庫連接配接工具類

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
package com.guoqi.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBHelper {

	private static String DIRVER = "com.mysql.jdbc.Driver"; 
	private static String URL = "jdbc:mysql://localhost:3306/test"; 
	private static String USERNAME = "root"; 
	private static String PASSWORD = "1234";

	/**
	 * 擷取連接配接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName(DIRVER);
			conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

	/**
	 * 關閉連接配接
	 * 
	 * @param conn
	 */
	public static void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加、删除、修改
	 * 
	 * @param conn
	 * @param sql
	 * @param values
	 * @return
	 */
	public static int executeUpdate(Connection conn, String sql, Object... values) {
		int i = -1;
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			for (int index = 0; index < values.length; index++) {
				ps.setObject((index + 1), values[index]);
			}
			i = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return i;
	}

	/**
	 * 查詢
	 * 
	 * @param conn
	 * @param sql
	 * @param values
	 * @return
	 */
	public static ResultSet executeQuery(Connection conn, String sql, Object... values) {
		ResultSet rs = null;
		try {
			PreparedStatement ps = conn.prepareStatement(sql);
			for (int index = 0; index < values.length; index++) {
				ps.setObject((index + 1), values[index]);
			}
			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
	}
}

           

再對DAO中申明的接口進行實作。在其中使用最普通方法進行對申明接口的實作。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
package com.guoqi.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.guoqi.bean.Test;
import com.guoqi.dao.TestDAO;
import com.guoqi.util.DBHelper;

@Repository("testDAO") // 等價于<bean id="testDAO" class="com.guoqi.dao.impl.TestDAOImpl" />
public class TestDAOImpl implements TestDAO {

	@Override
	public int insert(Test test) {
		Connection conn = DBHelper.getConnection();
		String sql = "insert into test(`sum`) values(?)";
		return DBHelper.executeUpdate(conn, sql, test.getSum());
	}

	@Override
	public int delete(int id) {
		Connection conn = DBHelper.getConnection();
		String sql = "delete from test where id = ?";
		return DBHelper.executeUpdate(conn, sql, id);
	}

	@Override
	public int update(Test test) {
		Connection conn = DBHelper.getConnection();
		String sql = "update test set `sum` = ? where `id` = ?";
		return DBHelper.executeUpdate(conn, sql, test.getSum(), test.getId());
	}

	@Override
	public List<Test> selectAll() {
		// 日志收集
		System.out.println("This is product selectAll");
		Connection conn = DBHelper.getConnection();
		String sql = "select * from test";
		List<Test> list = new ArrayList<Test>();
		ResultSet rs = DBHelper.executeQuery(conn, sql);
		try {
			while (rs.next()) {
				Test t = new Test();
				t.setId(rs.getInt(1));
				t.setSum(rs.getFloat(2));
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println("This is product selectAll END!!!");
		return list;
	}

	@Override
	public Test getTestById(int id) {
		Connection conn = DBHelper.getConnection();
		String sql = "select * from test where id = ?";
		ResultSet rs = DBHelper.executeQuery(conn, sql, id);
		Test t = null;
		try {
			if (rs.next()) {
				t = new Test();
				t.setId(rs.getInt(1));
				t.setSum(rs.getFloat(2));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return t;
	}

}

           

在對web.xml進行配置,添加以下代碼

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<!-- 配置上下文變量 -->
  <context-param>
  <!-- 将指定的上下文變量寫入到指定的路徑中 -->
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:*applicationContext.xml</param-value>
	</context-param>
	<!-- 加載監聽器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

           

再對配置檔案springmvc.xml進行配置,添加以下代碼:

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<!-- 設定加載内部視圖解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
           

還要對配置檔案applicationContext.xml進行設定:

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<!-- 開啟Spring注解功能識别的标簽 -->
	<context:annotation-config />
	<!-- 開啟Spring mvc包掃描的功能 -->
	<!-- base-package指定包掃描路徑及其以下所有子包 -->
	<context:component-scan
		base-package="com.guoqi" />
           

以上,總共對三個配置檔案進行了修改。

最後在controller建立一個新的方法,此方法調用資料庫進行查詢。通過此類進行對資料庫連接配接和操作。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
@RequestMapping("/getAllTest")
public String getAllTest(Model model) {
	List<Test> list = testService.selectAll();
	model.addAttribute("list", list);
	return "testTable";
}
           

因為我們在這個新方法中傳回的是一個視圖,是以我們需要在WEB-INF檔案夾下建立一個jsp檔案夾,并且建立一個testTable.jsp檔案

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table border="1" cellspacing="0" align="center">
		<tr>
			<th>id</th>
			<th>sum</th>
			<th>操作</th>
		</tr>
		<c:forEach items="${list }" var="test">
			<tr>
				<td>${test.id }</td>
				<td>${test.sum }</td>
				<td><a href="toUpdateTest.do?id=${test.id }">修改</a>&nbsp;<a
					href="deleteTest.do?id=${test.id }">删除</a></td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>
           

最後在浏覽器中調用,測試是否成功。可以看到,最終成功了。

eclipse從零開始搭建spring mvc 并實作簡單的指定頁面通路和資料查詢