使用Spring MVC进行web开发

    和struts框架的MVC一样,Spring MVC也是通过一个前端servlet接收所有请求,并将具体工作委托给其他组件进行处理,DispatcherServlet就是Spring MVC的前端servlet,它是spring MVC的核心。从接收请求到返回响应的过程中,DispatcherServlet负责协调和组织不同组件来完成请求处理,并返回响应。

一下通过一个示例来介绍Spring MVC的使用:

第一步:配置web.xml文件

在web项目中使用spring必须在web.xml文件中配置Spring的ContextLoaderListener,以实现在web服务启动时就启动spring容器。另外,在使用到Spring MVC时,还需要将DispatcherServlet这个servlet配置在web.xml中,并指定spring要加载的web层配置文件。以下是一个web.xml的具体配置信息:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 配置启动spring容器的Listener -->
  <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>
  
  <!-- 配置Spring MVC的核心Servlet DispatcherServlet -->
  <servlet>
  	<servlet-name>webApplicationServlet</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>contextConfigLocation</param-name>
  		<!-- 配置DispatcherServlet的contextConfigLocation参数,使其加载指定路径下的spring web层配置文件 -->
  		<!-- 如果不指定这个参,默认会去WEB-INF/目录下加载:<servlet-name>-servlet.xml -->
  		<param-value>WEB-INF/servlet/webApplicationServlet.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 配置拦截所有的请求 -->
  <servlet-mapping>
  	<servlet-name>webApplicationServlet</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>
  
</web-app>

第二步:配置Spring配置文件--applicationContext.xml

这个文件是spring必不可少的配置文件,在这里不做具体展示。

第三步:配置spring web层配置文件

这个web层配置文件是Spring MVC的DispatcherServlet所需要加载的配置文件,在上面的web.xml中它对应的是:WEB-INF/servlet/webApplicationServlet.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: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/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
    <context:component-scan base-package="cn.qing.spring"/>
    
    <!-- 配置spring mvc的响应视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    	<!-- 配置响应视图的路径前缀 -->
    	<property name="prefix" value="/view/"/>
    	<!-- 配置响应视图的名称后缀 -->
    	<property name="suffix" value=".jsp"/>
    </bean>
</beans>

第四步:编写Controller控制层实现

当配置都完成后,需要编写具体的控制层实现,主要是业务处理,调用spring中定义的其它service服务完成业务操作,但另一个重点是在类或者方法或者方法请求参数上,配置响应的请求注解,下面的一个action类包含了通常会使用到的一些请求形式。

package cn.qing.spring.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.qing.spring.bean.Student;

@Controller
@RequestMapping("/student")
public class StudentAction {

	/**
	 * 没有入参的请求方法
	 * @return
	 * 访问格式:http://localhost:8080/spring/student/findStudentName
	 */
	@RequestMapping("/findStudentName")
	public ModelAndView findStudentName()
	{
		System.out.println("execute findStudentNameById method...");
		
		//返回一个ModelAndView对象,在其中封装业务数据以及视图名
		ModelAndView view = new ModelAndView();
		view.addObject("studentName", "xiaoming");
		view.setViewName("showStudent");
		return view;
	}
	
	/**
	 * 在请求地址中传递方法参数
	 * 使用@PathVariable注解获取请求路径中的参数值
	 * @param stuId
	 * @return
	 * 访问格式:http://localhost:8080/spring/student/findStudentById/100
	 */
	@RequestMapping("/findStudentById/{stuId}")
	public ModelAndView findStudentById(@PathVariable("stuId") Long stuId)
	{
		System.out.println("student Id:"+stuId);
		Student stu = new Student();
		stu.setId(stuId);
		stu.setName("zhangsan");
		stu.setAddr("中国");
		
		//返回一个ModelAndView对象,在其中封装业务数据以及视图名
		ModelAndView view = new ModelAndView();
		view.addObject("student", stu);	//将Student对象返回
		view.setViewName("showStudent");
		return view;
	}
	
	/**
	 * 使用指定HTTP请求方法method的形式访问方法,这里必须的和指定的method的值进行匹配
	 * method 的值可以为:GET、POST、DELETE、PUT等和http的请求方法是一致的
	 * 如果在方法中指定的是以GET进行请求,但实际请求时却是以其他的方式会无法访问到对应的请求
	 * @param stuName 这个参数还是通过从访问路径中获取传递的值
	 * @return
	 * 访问格式:http://localhost:8080/spring/student/findStudentByName/ding
	 * 说明:如果method设置为Post,则不能直接在浏览器中这样访问,必须以Http的POST形式进行访问
	 */
	@RequestMapping(value="/findStudentByName/{stuName}",method=RequestMethod.GET)
	public ModelAndView findStudentByName(@PathVariable("stuName") String stuName)
	{
		System.out.println("stuName:"+stuName);
		//返回一个ModelAndView对象,在其中封装业务数据以及视图名
		ModelAndView view = new ModelAndView();
		view.addObject("stuName", stuName);	//将传入的stuName直接返回
		view.setViewName("showStudent");
		return view;
	}
	
	/**
	 * 使用@RequestParam注解来获取请求时传递的参数,按照参数名进行对应
	 * @param id
	 * @param stuName
	 * @return	直接返回一个逻辑视图的名称
	 * 访问格式:http://localhost:8080/spring/student/findStuAddr?id=100&stuName=qing
	 */
	@RequestMapping(value="/findStuAddr")
	public String findStudentAddr(@RequestParam("id") Long id,
									@RequestParam("stuName") String stuName)
	{
		System.out.println("id:"+id+"\t sutName:"+stuName);
		//在这里直接返回要转向的view名称,并不绑定业务数据,所以返回类型可以直接使用String
		return "showStudent";
	}
	
	/**
	 * 使用@ModelAttribute注解将请求的参数直接封装到对象的属性中
	 * 也可以不使用@ModelAttribute直接以常规的方法定义也是可以的,如:createStudent(Student stu)
	 * @param stu
	 * @return
	 * 访问格式:http://localhost:8080/spring/student/createStu?name=ding&id=102
	 * 说明:这里直接传递参数时,不需要使用stu.name的形式,只需要用name的属性来填充参数值
	 */
	@RequestMapping("/createStu")
	public String createStudent(@ModelAttribute("stu") Student stu)
	{
		System.out.println(stu.toString());
		return "showStudent";
	}
	
	/**
	 * 可以在方法的入参中直接定义Servlet API中的对象,如:request、response对象
	 * spring MVC会自动将这些Servlet API中的对象注入到方法中
	 * @param id
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/updateStu/{id}")
	public String updateStudent(@PathVariable("id") Long id,HttpServletRequest request,HttpServletResponse response,HttpSession session)
	{
		System.out.println("request.getContextPath():"+request.getContextPath());
		System.out.println("request obj:"+request.getClass());
		System.out.println("response obj:"+response.getClass());
		System.out.println("session obj:"+session.getClass());
		return "showStudent";
	}
}

按照在类及方法上配置的注解的请求路径进行访问,就可以完成和struts一样的MVC功能,每个方法中返回的showStudent视图,都是对应/view/showStudent.jsp视图,这个是在前面的配置文件中指定的,视图解析器会对其进行封装和渲染,最后DispatcherServlet返回响应。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值