Springmvc 01

javaee的体系结构

springmvc是类似于web层的mvc框架

springmvc和spring

  springmvc是spring的一部分

Struts2执行流程:

  1. strutsPrepareAndExcuteFilter拦截请求(控制层),拦截请求,转发请求
  2. 寻找Action执行
  3. ActionProxy:strutsActionProxy extends defaultActionProxy
  4. ActionMapping去寻找执行类Action

Springmvc入门程序

1.创建一个web程序

需要的jar包

配置web.xml(配置前端控制器DispatcherServelet)

 <servlet>
  <servlet-name>springmvc</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>
  <!--  默认加载 方式:文件命名:serlvet-name-servlet.xml====springmvc-servlet.xml
  					 路径:必须在WEB-INF目录下面
   -->
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.do</url-pattern>
  </servlet-mapping>

配置springmvc.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
		<!-- 
		配置处理器映射器 springmvc默认处理的处理器映射器
		BeanNameUrlHandlerrMapping:根据自定义的control的name属性的url寻找handler(Action:Controller) -->
		<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
		
		 <!-- 配置处理器适配器执行controller,springmvc默认的SimpleUrlHandlerMapping:执行controller -->
		 <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>

		<!-- 配置自定义控制器 -->
		<bean  id="myController" name="/hello.do" class="it.com.controller.MyController"></bean>

	     <!-- 	配置springmvc视图解析器:解析逻辑视图
				后台返回逻辑视图index
				视图解析器解析出真正的物理视图  前缀+逻辑视图+后缀 -->
		<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsps/"></property>
		<property name="suffix" value=".jsp"></property>
		</bean> 
		</beans>

 自定义controller

public class MyController  implements Controller{

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//接收请求 参数 验证参数
		//封装参数调用业务方法
		//返回视图
		ModelAndView mv=new ModelAndView();
		//设置页面回显数据
		mv.addObject("hello","欢迎学习springmvc");
		
		//指定跳转的视图
		//返回物理视图
		//mv.setViewName("WEB-INF/jsps/index.jsp");
		//返回逻辑视图
		mv.setViewName("index");
		
		return mv;
	}

}

定义视图页面

根据视图解析出路径:WEB-INF/jsps/index.jsp

${hello}

根据代码分析springmvc执行流程

适配器的源代码

处理映射器

BeanNameUrlHandlerMapping 功能:寻找controller,根据url请求去匹配bean的name的url,从而获取controller

SimpleUrlHandlerMaping

 功能:寻找Controller,根据浏览器url匹配简单url的key又根据Controller的id找到Controller

		<!-- 简单url处理器映射器 把url集中进行处理 -->
		 <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
		 <property name="mappings">
		 <props>
		 <prop key="/mine.do">myController</prop>
		 <prop key="/ss.do">http</prop>
		 <prop key="/abc.do">http</prop>
		 </props>
		 </property>
		</bean>
		
		<!-- 配置自定义控制器 -->
		<bean  id="myController" name="/hello.do" class="it.com.controller.MyController"></bean>
		<bean  id="http"  class="it.com.controller.HttpController"></bean>

ControllerClassNameHandlerMapping

功能:寻找controller根据类名.do访问,类名首字母小写

 映射器之间共存:3个处理映射器可以共存

处理器适配器

SimpleControllerHandlerAdapter

功能:执行controller,调用controller里面的方法,返回modelAndView

	<!-- 配置处理器适配器执行controller,springmvc默认的-->
		 <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdpter">

HttpRequestHandlerAdapter

执行controller

         <!-- HttpRequestHandlerAdapter负责执行实现接口HttpRequestHandler的后端控制器	-->
	    <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean>

2个处理适配器可以共存

命令控制器

springmvc通过命令设计模式接收页面参数

自定义命令控制器

public class CommandController extends AbstractCommandController{

	
	//指定把参数封装到那个对象
	public  CommandController(){
		this.setCommandClass(User.class);
	}
	
	
	@Override
	protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException error)
			throws Exception {
		//值被封装命令对象
		User user=(User) command;
		
		ModelAndView mv=new ModelAndView();
		//设置model数据 值可以任意的pojo
		mv.addObject("user",user);
		//指定返回视图页面
		mv.setViewName("index");
		return mv;
	}
	
}

定义JavaBean

	private Integer id;
	private String username;
	private String age;
	private Date birthday;
	private String sex;
	private String address;

add.jsp

<form action="${pageContext.request.contextPath}/command.do" method="post">
姓名:<input type="text" name="username" id="username">
年龄:<input type="text" name="age" id="age">
生日:<input type="text" name="birthday" id="birthday">
地址:<input type="text" name="address" id="address">
<input type="submit" value="提交">
</form>

跳转到add页面

由于add页面在WEB-INF下面不能访问,需要通过controller来访问

public class ToAddController implements Controller{

	@Override
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//跳转到添加页面
		ModelAndView mv=new ModelAndView();
		mv.setViewName("add");
		return mv;
	}

}

在springmvc中配置bean

<bean  name="/command.do"   class="it.com.controller.CommandController"></bean>
<bean  name="/toAdd.do"   class="it.com.controller.ToAddController"></bean>

中文乱码解决

get请求乱码

post乱码

Spring编码过滤器:在web.xml配置

 <filter-name>characterEncoding</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>
  </filter>
  
  <filter-mapping>
  <filter-name>characterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>

时间类型转换

注解开发

创建一个web工程

配置web.xml

<filter>
  <filter-name>characterEncoding</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>
  </filter>
  
  <filter-mapping>
  <filter-name>characterEncoding</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!-- 默认加载方式
  	   默认加载必须规范:
  	   * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml
  	   * 路径规范:必须在WEB-INF目录下面
   -->
   <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>   
   </init-param>
  </servlet>
  
  <servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>*.do</url-pattern>
  </servlet-mapping>

配置springmvc.xml

<context:component-scan base-package="cn.itcast"></context:component-scan>
		
		<!-- 配置注解处理器映射器 
			功能:寻找执行类Controller
		-->
		<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
		
		<!-- 配置注解处理器适配器 
			功能:调用controller方法,执行controller
		-->
		<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
		
		
		<!-- 配置sprigmvc视图解析器:解析逻辑试图 
			 后台返回逻辑试图:index
			视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp
		-->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/jsps/"></property>
		<property name="suffix" value=".jsp"></property>		
		</bean>

 自定义controller

  注解开发流程

   RequestMapping

  requestMapping("hello")

    requestMapping("/hello.do")

    requestMapping(value="/hello.do")

@RequestMapping("/hello.do")
	 public String hello(){ 
		 return "index";
	 }

    requestMapping(value=”/hello.do”,method=RequestMethod.GET)

requestMapping(value=”/hello.do”,method=RequestMethod.GET)
	 public String hello(){ 
		 return "index";
	 }

 requestMapping(value=”/hello.do”,method=RequestMethod.POST)

浏览器直接访问,a标签都是get请求

表单提交(指定post),ajax指定post提交,post提交。

requestMapping(value=”/hello.do”,method={RequestMethod.POST, RequestMethod.GET})

 @requestMapping(value=”/hello.do”,method={RequestMethod.POST, RequestMethod.GET})
	 public String hello(){ 
		 return "index";
	 }

 Request的根路径

@RequestMapping(”/user”)

UserController{

requestMapping(“save”)

Save()

requestMapping(“update”)

Update{}

requestMapping(“find”)

Fiind()

 

项目名/user/save.do

@RequestMapping(”/items”)

ItemsController{

 

requestMapping(“save”)

Save()

requestMapping(“update”)

Update{}

requestMapping(“find”)

Fiind()

 

 

项目/items/save.do

封装参数

分析接受参数类型

基本类型,int,String等等基本类型

pojo类型

包装类型

springmvc默认支持类型:HttpSession,HttpRequestServlet,Model..

struts2参数:属于属性封装

springmvc参数封装:基于方法进行封装

 

基本类型

需求:封装int类型参数

页面传递参数都是字符串

<hr color="blue" size="12">
<form action="${pageContext.request.contextPath}/user/recieveInt.do" method="post">
ID:<input type="text" name="id" id="id">
<input type="submit" value="提交">
</form>
	@RequestMapping("recieveInt")
	public String recieveInt(Integer id){
		System.out.println(id);
		return "success";
	}

 接受字符串类型

<hr color="blue" size="12">
<form action="${pageContext.request.contextPath}/user/recieveStr.do" method="post">
姓名:<input type="text" name="username" id="username">
<input type="submit" value="提交">
</form>
	//接收string类型参数
	@RequestMapping("recieveStr")
	public String recieveStr(String username){
		System.out.println(username);
		return "success";
	}

接受数组:分析:批量删除:checkbox复选框。Value必须有值。

<hr color="blue" size="12">
<form action="${pageContext.request.contextPath}/user/recieveArray.do" method="post">
ID:<input type="checkbox" name="ids" id="ids" value="1">
ID:<input type="checkbox" name="ids" id="ids" value="2">
ID:<input type="checkbox" name="ids" id="ids" value="3">
<input type="submit" value="提交">
</form>
	@RequestMapping("recieveArray")
	public String recieveIds(Integer []ids){
		System.out.println(ids);
		return "success";
	}
	

 接收POJO

<form action="${pageContext.request.contextPath}/user/recieveUser.do" method="post">
姓名:<input type="text" name="username" id="username">
年龄:<input type="text" name="age" id="age">
生日:<input type="text" name="birthday" id="birthday">
地址:<input type="text" name="address" id="address">
<input type="submit" value="提交">
</form>
	@RequestMapping("recieveUser")
	public String recieveUser(User user){
		System.out.println(user);
		return "success";
	}

  接受包装类型参数

userCustom{

private user user;

private List<User> userList;

private Map<K,V> maps;

 

private items items;

 

public class UserCustomer {
	private User user;
	
	private List<User> userList;
	private Map<String,Object> maps=new HashMap<String,Object>();
	
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public Map<String, Object> getMaps() {
		return maps;
	}

	public void setMaps(Map<String, Object> maps) {
		this.maps = maps;
	}


}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页