spirngmvc入門—springmvc的使用(1)

開始步驟

  1. 導入相關依賴
  2. 在web.xml中配置DispathServlet
  3. 加入Spring MVC 的配置文件
  4. 編寫處理請求的處理器,並標識爲處理器
  5. 編寫視圖
    注:編寫步驟視個人習慣,以下步驟稍作調整,以減少頁面字數

1.創建maven工程,並導入相關依賴(pom.xml)

<properties>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
		<spring.version>5.2.3.RELEASE</spring.version>
	</properties>
</properties>
<properties>
	<!-- spring的依賴包 -->
	<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aspects</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<!-- mysql驅動包 -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.48</version>
	</dependency>
	<!-- mybatis的依賴包 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis</artifactId>
		<version>3.5.3</version>
	</dependency>
	<!-- spring整合mybatis的包 -->
	<dependency>
		<groupId>org.mybatis</groupId>
		<artifactId>mybatis-spring</artifactId>
		<version>2.0.0</version>
	</dependency>
	<!-- 數據庫連接池 -->
	<dependency>
		<groupId>commons-dbcp</groupId>
		<artifactId>commons-dbcp</artifactId>
		<version>1.4</version>
	</dependency>
	<!-- servlet 和 jsp -->
	<dependency>
		<groupId>javax.servlet.jsp</groupId>
		<artifactId>javax.servlet.jsp-api</artifactId>
		<version>2.3.3</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>javax.servlet-api</artifactId>
		<version>4.0.0</version>
		<scope>provided</scope>
	</dependency>
	<!-- gson包 -->
	<dependency>
		<groupId>com.google.code.gson</groupId>
		<artifactId>gson</artifactId>
		<version>2.8.5</version>
	</dependency>
	<!-- 日誌包 -->
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency>
</properties>

2. 項目結構與html頁面

  1. index.html頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1> <a href="demo/find1?ename=huathy&age=20" target="_blank">find1</a> </h1>
<h1> <a href="javascript:find2()" >find2</a> </h1>
<h1> <a href="javascript:find3()" >find3</a> </h1>
<h1> <a href="demo/find4?name=huathy" target="_blank">find4</a> </h1>
<script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
	function find2(){
		$.post("demo/find2",{ name : 'huathy' },function(data){
			console.log(data);
		},"json");
	}

	function find3(){
		$.post("demo/find3",{ 
			pid : 101, 
			pname : 'huathy', 
			age : 20, 
			tel : '123456789'
		},function(data){
			console.log(data);
		},"json");
	}
</script>
</body>
</html>
  1. emp.html與dept.html
    在這裏插入圖片描述

3.編寫實體類(Person.java)

package com.hx.springmvc.entity;

public class Person {
	private int pid;
	private String pname;
	private int age;
	private String tel;

	@Override
	public String toString() {
		return "Person [pid=" + pid + ", pname=" + pname + ", age=" + age + ", tel=" + tel + "]";
	}

	public int getPid() {
		return pid;
	}
	public void setPid(int pid) {
		this.pid = pid;
	}
	public String getPname() {
		return pname;
	}
	public void setPname(String pname) {
		this.pname = pname;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + pid;
		result = prime * result + ((pname == null) ? 0 : pname.hashCode());
		result = prime * result + ((tel == null) ? 0 : tel.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (pid != other.pid)
			return false;
		if (pname == null) {
			if (other.pname != null)
				return false;
		} else if (!pname.equals(other.pname))
			return false;
		if (tel == null) {
			if (other.tel != null)
				return false;
		} else if (!tel.equals(other.tel))
			return false;
		return true;
	}

	public Person(int pid, String pname, int age, String tel) {
		super();
		this.pid = pid;
		this.pname = pname;
		this.age = age;
		this.tel = tel;
	}
	public Person() {
		super();
	}
}

4.編寫業務實現類(DeptBizImpl.java)

package com.hx.springmvc.biz;

import org.springframework.stereotype.Service;
import com.hx.springmvc.entity.Person;

@Service
public class DeptBizImpl {
	public Person find(){
		return new Person(101,"huathy",19,"18100001111");
	}
}

5. 編寫控制器類(DemoController.java)

package com.hx.springmvc.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hx.springmvc.biz.DeptBizImpl;
import com.hx.springmvc.entity.Person;

@Controller		//說明是個控制器
@RequestMapping("/demo")	//指定映射路徑,即通過demo訪問
public class DemoController{
	
	@Autowired
	private DeptBizImpl deptBizImpl;
	
	@RequestMapping("/find1")
	public String find1(String ename,Integer age){	//String默認是一個跳轉地址
		System.out.println(ename + "\t" +age);
		return "redirect:/back/emp.html";	//重定向到back/emp.html
	}
	
	@RequestMapping("/find2")
	@ResponseBody	//說明以json格式返回數據
	public Person find2(String ename,HttpSession session){
		Person person = deptBizImpl.find();
		session.setAttribute("person", person);
		System.out.println( session.getAttribute("person") );
		return person;
	}
	
	@RequestMapping("/find3")
	@ResponseBody
	public List<Person> find3(Person p){
		System.out.println(p);
		List<Person> list = new ArrayList<>();
		list.add( new Person(101,"huathy",18,"123456778") );
		list.add( new Person(102,"huasy",20,"123456778") );
		list.add( new Person(102,"qq",20,"123456778") );
		return list;
	}
	
	@RequestMapping("/find4")
	public String find4(@RequestParam("name")String ename){
		System.out.println(ename);
		return "/back/dept.html";	//默認轉發到指定路徑
	}
}

6. 編寫xml配置(spring-beans.xml、spring-mvc.xml)

  1. spring-beans.xml
<?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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">	
	<!-- 需要掃描的包 -->
	<context:component-scan base-package="com.hx.springmvc" />
</beans>
  1. spring-mvc.xml
<?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:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">	
	<!-- 需要掃描的包 -->
	<context:component-scan base-package="com.hx.springmvc" />	
	<!-- 放過靜態資源 -->
	<mvc:default-servlet-handler />	
	<!-- 啓用mvc註解 -->
	<mvc:annotation-driven />
</beans>

7. 編寫WEB-INF下的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_3_1.xsd"
	id="WebApp_ID" version="3.1">
	<!-- 編碼集過濾器 -->
	<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>forceRequestEncoding</param-name>	<!--強制轉換-->
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>forceResponseEncoding</param-name>	<!--強制轉換-->
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
	<!-- 用來實例化IOC容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring-beans.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- 配置servlet -->
	<servlet>
		<servlet-name>DispathcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>	<!-- 初始化參數 -->
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispathcherServlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>
	
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
</web-app>

附:原理圖及原理簡介

1.用戶訪問 /index
2.根據web.xml中的配置 所有的訪問都會經過DispatcherServlet
3.根據 根據配置文件springmvc-servlet.xml ,訪問路徑/index
會進入IndexController類
4.在IndexController中指定跳轉到頁面index.jsp,並傳遞message數據
5.在index.jsp中顯示message信息
在這裏插入圖片描述

附:

  1. spirngmvc入門—springmvc的使用(1):https://blog.csdn.net/qq_40366738/article/details/104841413
  2. springmvc入門—springmvc的使用(2):https://blog.csdn.net/qq_40366738/article/details/104857441
  3. springmvc入門—springmvc的使用(3)interceptor攔截器:https://blog.csdn.net/qq_40366738/article/details/104905550
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章