1. 程式人生 > >什麼是SpringMVC?(三)springmvc快速入門(註解版本)

什麼是SpringMVC?(三)springmvc快速入門(註解版本)

一、springmvc快速入門(傳統版)

   步一:建立springmvc-day02這麼一個web應用

   步二:匯入springioc,springweb和springmvc相關的jar包

  ------------------------------------------------------springWEB模組
   org.springframework.web-3.0.5.RELEASE.jar
org.springframework.web.servlet-3.0.5.RELEASE.jar(mvc專用)
   ------------------------------------------------------springIOC模組
   org.springframework.asm-3.0.5.RELEASE.jar
   org.springframework.beans-3.0.5.RELEASE.jar
   org.springframework.context-3.0.5.RELEASE.jar
   org.springframework.core-3.0.5.RELEASE.jar
   org.springframework.expression-3.0.5.RELEASE.jar

步三:在/WEB-INF/下建立web.xml檔案

	<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:spring.xml</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>DispatcherServlet</servlet-name>
		<url-pattern>*.action</url-pattern>
	</servlet-mapping>

步四:建立HelloAction.java控制器類

@Controller
public class HelloAction{
	@RequestMapping(value="/hello")
	public String helloMethod(Model model) throws Exception{
		System.out.println("HelloAction::helloMethod()");
		model.addAttribute("message","這是我的第二個springmvc應用程式");
		return "/success.jsp";
	}	
}

步五:在/WebRoot/下建立success.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>這是我的第二個springmvc應用程式</title>
  </head>
  <body>
	success.jsp<br/>
	${message}
  </body>
</html>

步六:在/src/目錄下建立spring.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"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
	  xmlns:mvc="http://www.springframework.org/schema/mvc"
		
      xsi:schemaLocation="
	
	  http://www.springframework.org/schema/beans 
	  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	  
	  http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
    
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        
      ">
		

	  <!-- Action控制器 -->
	  <context:component-scan base-package="com.zc.javaee.springmvc.helloannotation"/>  	

      
      
      <!-- 基於註解的對映器(可選) -->
      <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
      
      <!-- 基於註解的介面卡(可選) -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
      
      <!-- 檢視解析器(可選) -->
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>
      	
</beans>

二、一個Action中,可以寫多個類似的業務控制方法

//增加使用者:http://127.0.0.1:8080/myspringmvc/user/add.action
//查詢使用者:http://127.0.0.1:8080/myspringmvc/user/find.action

@Controller
@RequestMapping(value="/user")
public class UserAction{
	@RequestMapping(value="/add")
	public String add(Model model) throws Exception{
		System.out.println("HelloAction::add()");
		model.addAttribute("message","增加使用者");
		return "/success.jsp";
	}
	@RequestMapping(value="/find")
	public String find(Model model) throws Exception{
		System.out.println("HelloAction::find()");
		model.addAttribute("message","查詢使用者");
		return "/success.jsp";
	}	
}

三、在業務控制方法中寫入普通變數收集引數

springmvc可以在業務控制方法中,以引數形式收集客戶端引數

@Controller
@RequestMapping(value="/user")
public class UserAction{
	@RequestMapping(value="/add")
	public String add(Model model,int id,String name,Double sal) throws Exception{
		System.out.println("HelloAction::add()");
		System.out.println(id + ":" + name + ":" + sal);
		model.addAttribute("message","增加使用者");
		return "/success.jsp";
	}	
}

四、限定某個業務控制方法,只允許GET或POST請求方式訪問

@Controller
@RequestMapping(value="/user")
public class UserAction{
	@RequestMapping(value="/add",method=RequestMethod.POST)   //預設都支援
	public String add(Model model,int id,String name,double sal) throws Exception{
		System.out.println("HelloAction::add()::POST");
		System.out.println(id + ":" + name + ":" + sal);
		model.addAttribute("message","增加使用者");
		return "/success.jsp";
	}	
}

五、在業務控制方法中寫入Request,Response等傳統web引數(不提倡,耦合)

@Controller
@RequestMapping(value="/user")
public class UserAction{
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public void add(HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println("HelloAction::add()::POST");
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		double sal = Double.parseDouble(request.getParameter("sal"));
		System.out.println(id + ":" + name + ":" + sal);
		request.getSession().setAttribute("id",id);
		request.getSession().setAttribute("name",name);
		request.getSession().setAttribute("sal",sal);
		response.sendRedirect(request.getContextPath()+"/register.jsp");
	}	
}

六、在業務控制方法中寫入模型變數收集引數,且使用@InitBind來解決字串轉日期型別

@Controller
@RequestMapping(value = "/user")
public class UserAction {
	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(int id, String name, double sal, Date hiredate,
			Model model) throws Exception {
		System.out.println("HelloAction::add()::POST");
		model.addAttribute("id", id);
		model.addAttribute("name", name);
		model.addAttribute("sal", sal);
		model.addAttribute("hiredate", hiredate);
		return "/register.jsp";
	}
}

七、在業務控制方法中寫入User,Admin多個模型收集引數

可以在業務控制方法中書寫1個模型來收集客戶端的引數,模型中的屬性名必須和客戶端引數名一一對應

@Controller
@RequestMapping(value = "/user")
public class UserAction {
	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(User user,Model model) throws Exception {
		System.out.println("HelloAction::add()::POST");
		model.addAttribute("user",user);
		return "/register.jsp";
	}
}

八、在業務控制方法中寫入包裝User的模型來收集引數

可以在業務控制方法中書寫0個或多個模型來收集客戶端的引數,當多個模型中有相同的屬性時,可以用user.name或admin.name來收集客戶端引數,解決方法是用一個新的模型將User和Admin再封裝一次

jsp頁面

<form action="${pageContext.request.contextPath}/person/add.action" method="POST">
		編號:<input type="text" name="user.id" value="${bean.user.id}"/><br/>
		姓名:<input type="text" name="user.name" value="${bean.user.name}"/><br/>
		薪水:<input type="text" name="user.sal" value="${bean.user.sal}"/><br/>
		入職時間:<input type="text" name="user.hiredate" value='<fmt:formatDate value="${bean.user.hiredate}" type="both" />'/><br/>
		<input type="submit" value="註冊"/>
	</form>
@Controller
@RequestMapping(value = "/person")
public class PersonAction {
	@InitBinder
	protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(
				Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
	}
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Bean bean,Model model) throws Exception {
		System.out.println(bean.getUser());
		System.out.println(bean.getAdmin());
		System.out.println("PersonAction::add()::POST");
		model.addAttribute("bean",bean);
		return "/register.jsp";
	}
}

九、在業務控制方法中收集陣列引數

@Controller
@RequestMapping(value="/user")
public class UserAction {
	@RequestMapping(value="/delete")
	public String deleteMethod(int[] ids,Model model) throws Exception{
		System.out.println("UserAction::deleteMethod()");
		System.out.println("需要刪除的id為:");
		for(int id : ids){
			System.out.print(id+" ");
		}
		model.addAttribute("message","批量刪除成功");
		return "/success.jsp";
	}
}

十、在業務控制方法中收集List<JavaBean>引數

//Bean.java
public class Bean {
	private List<User> userList = new ArrayList<User>();
	public Bean(){}
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
}
//registerAll.java
	<form action="${pageContext.request.contextPath}/user/addAll.action" method="POST"> 
		 
		姓名:<input type="text" name="userList[0].name" value="哈哈"/>
		性別:<input type="text" name="userList[0].gender" value="男"/>
		<hr/>
		
		姓名:<input type="text" name="userList[1].name" value="呵呵"/>
		性別:<input type="text" name="userList[1].gender" value="男"/>
		<hr/>

		姓名:<input type="text" name="userList[2].name" value="嘻嘻"/>
		性別:<input type="text" name="userList[2].gender" value="女"/>
		<hr/>
		
		<input type="submit" value="批量註冊"/>
		
	</form>
//UserAction.java
@Controller
@RequestMapping(value="/user")
public class UserAction {
	@RequestMapping(value="/addAll")
	public String addAll(Bean bean,Model model) throws Exception{
		for(User user : bean.getUserList()){
			System.out.println(user.getName()+":"+user.getGender());
		}
		model.addAttribute("message","批量增加使用者成功");
		return "/success.jsp";
	}
}

十一、結果的轉發和重定向

//在轉發情況下,共享request域物件,會將引數從第一個業務控制方法傳入第二個業務控制方法,
//反之,重定向則不行 
//刪除id=10號的使用者,再查詢使用者
@Controller
@RequestMapping(value="/user")
public class UserAction {

	@RequestMapping(value="/delete")
	public String delete(int id) throws Exception{
		System.out.println("刪除使用者->" + id);
		//轉發到find()
		return "forward:/user/find.action";
		//重定向到find()
		//return "redirect:/user/find.action";
	}
	
	@RequestMapping(value="/find")
	public String find(int id) throws Exception{
		System.out.println("查詢使用者->" + id);
		return "/success.jsp";
	}
	
}

十二、非同步傳送表單資料到JavaBean,並響應JSON文字返回

提交表單後,將JavaBean資訊以JSON文字形式返回到瀏覽器

    //bean2json.jsp
	<form>
		編號:<input type="text" name="id" value="1"/><br/>
		姓名:<input type="text" name="name" value="哈哈"/><br/>
		薪水:<input type="text" name="sal" value="5000"/><br/>
		<input type="button" value="非同步提交註冊"/>
	</form>
	
	<script type="text/javascript">
		$(":button").click(function(){
			var url = "${pageContext.request.contextPath}/user/add.action";
			var sendData = {
				"id":1,
				"name":"哈哈",
				"sal":5000
			};
			$.post(url,sendData,function(backData,textStatus,ajax){
				alert(ajax.responseText);
			});
		});
	</script>
//UserAction.java
@Controller
@RequestMapping(value="/user")
public class UserAction {

	@RequestMapping(value="/add")
	public @ResponseBody User add(User user) throws Exception{
		System.out.println(user.getId()+":"+user.getName()+":"+user.getSal());
		return user;
	}
	
}
     //spring.xml
	  <!-- Action控制器 -->
	  <context:component-scan base-package="com.zc.javaee.springmvc.app25"/>  	


  	  <!-- 介面卡 -->
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      		<property name="messageConverters">
      	   		<list>
      				<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
      	   		</list>
      		</property>
      </bean>