JavaWeb——SpringMVC

一、SpringMVC

Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。使用 Spring 可插入的 MVC 架构,从而在使用Spring进行WEB开发时,可以选择使用Spring的Spring MVC框架或集成其他MVC开发框架

  • 对Servlet进行了封装
  • 替代Servlet,作为控制器

二、执行流程

  1. 用户向服务器发送请求,请求被Spring 前端控制Servelt DispatcherServlet捕获;
  2. DispatcherServlet对请求URL进行解析,得到请求资源标识符(URI)。然后根据该URI,调用HandlerMapping获得该Handler配置的所有相关的对象(包括Handler对象以及Handler对象对应的拦截器),最后以HandlerExecutionChain对象的形式返回;
  3. DispatcherServlet 根据获得的Handler,选择一个合适的HandlerAdapter。(附注:如果成功获得HandlerAdapter后,此时将开始执行拦截器的preHandler(...)方法)
  4. 提取Request中的模型数据,填充Handler入参,开始执行Handler(Controller)。
  5.  Handler执行完成后,向DispatcherServlet 返回一个ModelAndView对象;
  6. 根据返回的ModelAndView,选择一个适合的ViewResolver(必须是已经注册到Spring容器中的ViewResolver)返回给DispatcherServlet ;
  7.  ViewResolver 结合Model和View,来渲染视图。
  8. 将渲染结果返回给客户端。

三、相关配置文件

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>2019-8-30</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>
  
  <!-- 配置一个前端Servlet控制器 -->
  <servlet>
			  <servlet-name>dispatcherServlet</servlet-name>
			  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
			  <!-- 引入配置文件 -->
			  <init-param>
					  <param-name>contextConfigLocation</param-name>
					  <param-value>classpath:SpringMVC.xml</param-value>
			  </init-param>
  </servlet>
  <servlet-mapping>
			  <servlet-name>dispatcherServlet</servlet-name>
			  <url-pattern>*.go</url-pattern>
  </servlet-mapping>
</web-app>

Controller层

package beer.onexone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

//标识为controller层
@Controller
public class BasisSpringMVC {
					//标识访问路径
	@RequestMapping("basis")
	public String basis(Model model) {
		model.addAttribute("message", "测试");
		return "basis";
	}
}

接收参数JSP

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
		<h1>${message }</h1>
</body>
</html>

运行结果

四、参数绑定

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>2019-8-30</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>
  
  <!-- 配置一个前端Servlet控制器 -->
  <servlet>
			  <servlet-name>dispatcherServlet</servlet-name>
			  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
			  <!-- 引入配置文件 -->
			  <init-param>
					  <param-name>contextConfigLocation</param-name>
					  <param-value>classpath:SpringMVC.xml</param-value>
			  </init-param>
  </servlet>
  <servlet-mapping>
			  <servlet-name>dispatcherServlet</servlet-name>
			  <url-pattern>*.go</url-pattern>
  </servlet-mapping>
</web-app>

前端页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
					<form action="trans.go"><br>
					ID<input type="text" name="id"><br>
					 Name<input type="text" name="name"><br>
					 Age<input type="text" name="age"><br>
					 
					 CatName<input type="text" name="cats[0].name"><br>
					  CatAge<input type="text" name="cats[0].age"><br>
					  
					 CatName<input type="text" name="cats1].name"><br>
					  CatAge<input type="text" name="cats[1].age"><br>
					  
					 CatName<input type="text" name="map[0].name"><br>
					  CatAge<input type="text" name="map[0].age"><br>
					  
					 CatName<input type="text" name="map[1].name"><br>
					  CatAge<input type="text" name="map[1].age"><br>
					  
					  <input type="submit" value="Submit"><br>
					</form>
					 
</body>
</html>

POJO

package beer.onexone.beans;

public class Cat {
	
		private	String name;
		private	int age;
		
		public Cat() {
			super();
		}
		public Cat(String name, int age) {
			super();
			this.name = name;
			this.age = age;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		@Override
		public String toString() {
			return "Cat [name=" + name + ", age=" + age + "]";
		}
		
}
package beer.onexone.beans;

import java.util.List;
import java.util.Map;

public class Person {
	private	int id;
	private	String name;
	private	int age;
	private	List<Cat> cats;
	private	Map<String, Cat> map;
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Person(int id, String name, int age, List<Cat> cats, Map<String, Cat> map) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.cats = cats;
		this.map = map;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public List<Cat> getCats() {
		return cats;
	}
	public void setCats(List<Cat> cats) {
		this.cats = cats;
	}
	public Map<String, Cat> getMap() {
		return map;
	}
	public void setMap(Map<String, Cat> map) {
		this.map = map;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + ", cats=" + cats + ", map=" + map + "]";
	}
	
}

MVC

package beer.onexone.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import beer.onexone.beans.Person;

@Controller
public class Trans {
			
	@RequestMapping("trans")
	//可以用POJO直接接受数据
	public String trans(Person person ,String name)  {
		System.out.println(name);
		System.out.println(person);
		return "success";
		
	}
}

结果

赤刀2
Person [id=123, name=赤刀2, age=12, cats=[Cat [name=uu, age=11], Cat [name=null, age=11]], map={0=Cat [name=dd, age=11], 1=Cat [name=vn, age=22]}]

参数绑定

//在参数中直接绑定ServletAPI
	@RequestMapping("back")
	public String back(HttpServletRequest request, HttpServletResponse response)  {
		request.setAttribute("message", "request");
		return "basis";
	}
	//用ModelMap绑定参数
	@RequestMapping("model")
	public String useModel( ModelMap map)  {
		map.addAttribute("message", "request");
		return "basis";
	}
	//使用ModelAndView
	@RequestMapping("mv")
	public ModelAndView mV( ModelAndView modelAndView)  {
		//视图解析器地址
		modelAndView.setViewName("success");
		//传入页面的值
		modelAndView.addObject("message","ModelAndView");
		return modelAndView;
	}

五、自定义类型转换器

package beer.onexone.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;

//自定义转化起类,实现Converter<S, T>接口
public class ConvertDate  implements Converter<String, Date>{
	@Override
	public Date convert(String dateString) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,yyyy-MM-dd");
		try {
			return simpleDateFormat.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
			return null;
		}
	}
}

XML添加配置

<!-- 自动配置参数 --><!-- 添加自定义转换类 -->
	<mvc:annotation-driven   conversion-service="dateConvert"/>
	<!-- 添加自定义的转换器 -->
	<bean id="dateConvert" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       <!--添加转换器 -->
		<property name="converters">
						<list>
							<bean class="beer.onexone.utils.ConvertDate"></bean>
						</list>
		</property>

六、跳转

	//使用重定向
	@RequestMapping("reDir")
	public String reDir( ModelAndView modelAndView)  {
		return "redirect:https://longpress.ink";
	}
	
	//使用转发
	@RequestMapping("reSend")
	public String reSend(HttpServletRequest request,  HttpServletResponse response)  {
		request.setAttribute("message", "reSend");
		return "forward:CallBack/success.jsp";
	}

jingsongchan

发表评论

电子邮件地址不会被公开。 必填项已用*标注