培训第2个月的第12天----SpringMVC初识

              今天学习了springMVC是怎样使用的,所以总结一下,方便以后来查看。

一.springMVC的核心配置文件

            springMVC的核心配置文件的名称可以任意,位置也可以任意(这点和spring的核心文件一样),但是在需要加载这个文件的时候,需要在web.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:aop="http://www.springframework.org/schema/aop"
		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-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
								http://www.springframework.org/schema/context
									http://www.springframework.org/schema/context/spring-context-3.2.xsd">


<!-- 在src目录下创建一个类似于xxx-servlet.xml的文件,用于配置springMVC 
               该文件只用于配置控制器Controller一端的内容
-->

            <!-- 扫描包,发挥在java代码中所标注的注释作用(功能) -->
            <context:component-scan base-package="com.java.controller"></context:component-scan>
          

  
</beans>

二.web.xml

               启动web容器,并加载其他的容器。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>spring_mvc</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>
   <description>基于一个DispatcherServlet来设计的servlet</description>
   <servlet-name>springMVC</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   <!-- 配置初始化参数 -->
   <init-param>
       <description>用于初始化参数</description>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:springMVC.xml</param-value>
   </init-param>
</servlet>

<!-- 配置过滤器,用于将路径过滤,什么样的路径才交给servlet来处理 -->
<servlet-mapping>
   <servlet-name>springMVC</servlet-name>
   <url-pattern>*.mvc</url-pattern>
</servlet-mapping>

<!-- 配置被监听的上下文参数 --> 
<context-param>
    <description>配置被监听的上下文参数</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springMVC.xml</param-value>
</context-param>

<!-- springMVC也是一个spring容器,也要由web.xml文件来启动 -->
<listener>
	<description>用于监听springMVC容器,ContextLoaderListener</description>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  
 

</web-app>

三.index.jsp

             用于和控制器的数据交互。

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%String path = request.getContextPath(); %>
<!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>欢迎登陆首页</title>

<!-- 引入js 文件 -->
<script type="text/javascript" src="js/jquery.min.js"></script>

<!-- ajax 代码 -->
<script type="text/javascript">
    /* $(function(){
    	 $.ajax({
    		 url:"controller1/method_3.mvc",
    		 //将返回值data转换为json格式
    		 dataType:"json",
    		 success:function(data){
    			 alert(typeof(data));
    			 alert(data[0].username);
    			 alert(data[0].password);
    			 alert(data[1].userSex);
    		 },
    		 error:function(){
    			 alert("你有失败了");
    		 }	 
    	 })
     });*/

</script>

</head>
<body>
  <a href="<%=path %>/controller1/method_1.mvc">点击进入方法一</a>
   <br/>
  <a href="<%=path %>/controller1/method_3.mvc">点击返回json数据</a>
   <br/>
  <a href="<%=path %>/controller1/method_4.mvc?username=11111&password=22222">点击进行自动装箱</a>
    <br/>
  <a href="<%=path %>/controller1/method_5.mvc">点击将数据待会当前页面</a> ${user1}
</body>
</html>

四.controller控制器

                 用于处理前台所发送过来的请求。

package com.java.controller;

import java.util.Map;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.java.Bean_yuanshi.User;

/*1.既然使用springMVC来做控制器,那么导入springMVC的jar包是必不可少的。
 *而且,在导入jar包时,我们只需要导入jar文件即可,sources和javadoc可以
 *不用导入。
 *2.创建一个springMVC的核心配置文件,用于指定要扫描的包。
 *3.定义一个web.xml文件,用于配置servlet和监听器。我们可以先配置servlet
 *过滤访问的url,来交给适当的controller控制器来响应。如果我们不配置监听器和
 *上下文context-param,那么当servlet被访问时,才初始化参数init-param,
 *如果配置了,那么就在web容器创建时,就加载init-param。
 *4.创建用于处理请求的控制器Controller。注意,要在controller上面添加组件
 *注解,否则controller将不会变成bean放到IOC容器中。
 *5.要为所访问的控制器(处理请求的控制器)和控制器中的方法添加映射路径(访问路径)。
 *这里我们没添加‘/’时,将会和当前目录自动进行拼接。
 *6.注意:如果用了@RequestMapping注解,那么方法就应该有String类型的返回值,
 *用来指定方法执行完要跳转的方法或页面。如果将方法设为void没有返回值,那么就会出现
 *404的异常。
 *7.当用重定向进行参数传递时,需要在url路径后添加?,在问号后面填写所要传递的参数
 *参数和参数之间要使用&符号来进行分隔。
 *8.通过重定向传递参数,传递到了一个方法中,如果方法的参数名和url中的参数名相同,
 *那么就会自动接收。如果不相同,那么就需要通过@RequestParam(“”)注解来指定
 *接收。在接收的时候,如果两个类型之间可以相互转换,那么springMVC将会自动给我们
 *转换。
 *9.@ResponseBody注解用来将当前方法的请求路径当作响应体(页面),并可以把re
 *turn的字符传打印到响应体中。如果用ajax来访问方法,那么会将返回的字符串带到ajax
 *中,我们可以事先定义将返回值的字符串转换成什么数据类型(如果可以转换的话),一旦转换
 *不成功,那么就会执行error方法。
 *10.在使用自动装箱时,只需要在url后面填写对应的属性名,如果url的参数名和对象的
 *属性的名称一致,那么就会把这个参数给这个对象的属性。
 *11.当向前台传递参数时,传递的参数为方法的形式参数。并且在return的时候,要使用
 *forword而不是redirect,因为一旦重定向了,那么就会将返回的参数丢失。
 *
 *
 *
 */


/*1.DispatcherServlet是前置控制器,配置在web.xml文件中的。拦截匹配的请求,
 *Servlet拦截匹配规则要自已定义,把拦截下来的请求,依据相应的规则分发到目标
 *Controller来处理,是配置spring MVC的第一步。
 *2.@Controller 负责注册一个bean 到spring 上下文中。
 *3.@RequestMapping 注解为控制器指定可以处理哪些 URL 请求。
 *4.@ResponseBody注解用于将Controller的方法返回的对象,通过适当的HttpMes
 *sageConverter转换为指定格式后,写入到Response对象的body数据区。
 *5.@RequestParam 在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法。
 *
 * */

@RequestMapping("/controller1")
@Component
public class Controller1 {
    @RequestMapping("/method_1") 
	public String method_1() {
		System.out.println("method_1() 已被执行");
		//文件路径用不用“/”到底有什么差别?
		return "redirect:/controller1/method_2.mvc?username=qiaotao&password=1234&age=20";
	}
    
    @RequestMapping("/method_2") 
    public String method_2(String username,@RequestParam("password") String pd,int age) {
    	System.out.println("method_2() 已被执行");
    	System.out.println("username="+username);
    	System.out.println("pd="+pd);
    	System.out.println("age="+(age+1));
    	return "redirect:/index.jsp";
    }
    
    //像前台返回json信息。
    @ResponseBody
    @RequestMapping("/method_3") 
    public String method_3() {
    	System.out.println("method_3() 已被执行");
    	//定义json格式的数据
    	String json_str="[{\"username\":\"qiaotao\",\"password\":\"123456\"},{\"userSex\":\"女\"}]";
    	return json_str;
    }
    
    //(对象)自动装箱
    @RequestMapping("/method_4")
    public String method_4(User user) {
    	System.out.println("method_4() 已被执行");
    	System.out.println("user.username="+user.getUserName()+"  ;  "+"user.password="+user.getUserPassword());
    	return "redirect:/index.jsp";
    }
    
    //向前台传递参数
    @RequestMapping("/method_5")
    public String method_5(Map<String,Object> map) {
    	System.out.println("method_5() 已被执行");
    	User user=new User();
    	user.setUserName("wahahaha");
    	user.setUserMajor("shuxue");
    	map.put("user1",user);
		return "forward:/index.jsp";
    	
    }
}

                关于springMVC我今天就总结这么多。。。。。嘻嘻嘻

猜你喜欢

转载自blog.csdn.net/qq_41160264/article/details/82355215