秀外慧中的springMVC(二)---springMVC的注解配置例子

注意:spring4.0之后增加了@RestController注解,它继承自@Controller注解,当使用@RestController时候默认将以resultful架构每次都默认加上@ResponseBodyer而不必每次都显示添加@ResponseBodyer注解来返回json字符串等。

1.web.xml文件

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringMvc</display-name>
    <!-- 使用ContextLoaderListener配置时,需要告诉它Spring配置文件的位置 -->  
    <!-- 如果没有指定,上下文载入器会在/WEB-INF/applicationContext.xml中找Spring配置文件 -->  
    <!-- 我们可以通过在Servlet上下文中设置contextConfigLocation参数,来为上下文载入器指定一个或多个Spring配置文件 -->  
    <!-- 注意:contextConfigLocation参数是一个用逗号分隔的路径列表,其路径是相对于Web系统的根路径的 -->
     <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>/WEB-INF/springmvc-servlet.xml, classpath:applicationContext-*.xml</param-value>  
    </context-param> 
  <!-- 中央控制器 -->
  <servlet>
     <servlet-name>springmvc</servlet-name>
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

    
      <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.springMVC的配置文件

<?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.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-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/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">	
        <!-- mvc注解驱动 当有扫描器时候component-scan此标签可以省略 
            <mvc:annotation-driven/>
        -->
        <!-- 扫描器 -->
        <context:component-scan base-package="org.senssic.springmvc"></context:component-scan>
    
    <!-- 如果web.xml中设置是:由SpringMVC拦截所有请求,于是在读取静态资源文件的时候就会受到影响(说白了就是读不到) -->  
    <!-- 经过下面的配置,该标签的作用就是:所有页面中引用"/css/**"的资源,都会从"/resources/styles/"里面进行查找 -->  
    <!-- 我们可以访问http://IP:8080/xxx/css/my.css和http://IP:8080/xxx/resources/styles/my.css对比出来 -->  
    <mvc:resources mapping="/css/**" location="/resources/styles/"/>  
      
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <!-- viewClass属性可以用来指定前台在解析数据时,所允许采用的手段。实际上其默认值就是JstlView -->  
        <!-- 将来有需要的话,就可以在这里把JstlView改成其它的,如FreeMarkerView,VelocityView,TilesView -->  
        <!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> -->  
  
        <!-- 若Controller的方法返回"user/addSuccess",则SpringMVC自动找/WEB-INF/jsp/user/addSuccess.jsp -->  
        <property name="prefix" value="/WEB-INF/jsp/"/>  
        <property name="suffix" value=".jsp"/>  
    </bean>
</beans>


3.实体类

package org.senssic.springmvc;

public class Person {
	private String name;
	private int age;

	@Override
	public String toString() {
		return "名字:" + name + "年龄:" + 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;
	};

}

4.注解类

package org.senssic.springmvc;


import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


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


import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.view.InternalResourceViewResolver;


@Controller
// 多了一层路径/sen/xxx
@RequestMapping("/sen")
// 只要下面的方法中执行model.addAttribute("loginUser","jadyer")那么"loginUser"便被自动放到HttpSession
@SessionAttributes("loginUser")
public class MyController {
	// 即访问"/sen/a.do"或者"/sen/hello.do",便自动访问该方法
	@RequestMapping(value = { "/a.do", "/hello.do" })
	public String hello() {
		System.out.println("ssss");
		return "main/helloworld";
	}


	// 可以直接使用HttpServletRequest
	@RequestMapping("/tRequest.do")
	public String tRequest(HttpServletRequest hRequest) {
		System.out.println(hRequest.getParameter("sen"));
		return "main/helloworld";
	}


	// 1.也可以直接使用参数传递:参数名字要一直,且可以相互转换,比如sring,int-integer 如果不能直接转换如(Date)需要写属性转换器
	// 2.可以使用@RequestParam注解参数要求必须传递(且可以指定参数名称)否则报400错误,如果不指定@RequestParam注解则可以不传递打印为null
	// 3.这里method=RequestMethod.GET用于指定需要以GET方式访问该方法,注意两个以上属性时就要明确value值了
	@RequestMapping(value = "/tRequestParam.do", method = RequestMethod.GET)
	public String tRequestParam(@RequestParam("sen") String sen, int age,
			@RequestParam Date date) {// 此处sen为前台传来的参数sen即/tRequestParam?sen=xxx
		System.out.println(sen + date);// 打印xxx
		return "main/helloworld";
	}


	// 注册时间类型的属性编辑器,可以接受tRequestParam?date=2014-05-20并转换为date类
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				new SimpleDateFormat("yyyy-MM-dd"), true));
	}


	// 接受实体类,传递的参数要与实体的set后面字符串匹配(首字母大小写不区分)一直才能接受到参数并注入到实体类中
	// 如果有多个实体接受,且字段一样,则分别注入到各个实体类中属性值一样,即若多一个User且里面也有个name字段则
	// 两个实体类都会被创建且值都一样
	@RequestMapping("/person.do")
	public String getPseron(Person person) {
		System.out.println(person);
		return "main/helloworld";
	}


	// 接受数组
	@RequestMapping("/array.do")
	public String getArray(String[] str) {
		for (int i = 0; i < str.length; i++) {
			System.out.println(str[i]);
		}
		return "main/helloworld";
	}


	/**
	 * 返回参数给前台,以及前台如何获取参数
	 */
	@RequestMapping("/rSen.do")
	public String rSen(String userName, Map<String, Object> map) {
		map.put("username", "username"); // 此时前台使用${username}即可取值
		return "paramlist";
	}


	@RequestMapping("/rmodel.do")
	public String rmodel(String userName, Model model) {
		model.addAttribute("rmodel", "rmodel"); // 此时前台使用${rmodel}即可取值
		model.addAttribute("loginUser", "username"); // 由于@SessionAttributes,故loginUser会被自动放到HttpSession中
		return "paramlist";
	}


	@RequestMapping("/rmodelnop.do")
	public String rmodelnop(String userName, Model model) {
		model.addAttribute("rmodelnop"); // 此时默认以Object类型作为key,即String-->string,故前台使用${string}即可取值
		return "paramlist";
	}


	/**
	 * 获取javax.servlet.http.HttpServletRequest、HttpServletResponse、HttpSession
	 */
	@RequestMapping("/getall.do")
	public String getall(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		System.out.println("===============" + request.getParameter("myname"));
		System.out.println("===============" + request.getLocalAddr());
		System.out.println("===============" + response.getLocale());
		System.out.println("===============" + session.getId());
		return "addSuccess";
	}


	// ajax常规请求,不建议使用
	@RequestMapping("/ajax.do")
	public void ajax(String name, HttpServletResponse response) {
		String reString = "hello" + name;
		try {
			response.getWriter().write(reString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	// ajax建议使用 直接在参数列表上定义PrintWriter
	@RequestMapping("/ajaxgood.do")
	public void ajaxgood(String name, PrintWriter response) {
		String reString = "hello" + name;
		response.write(reString);
	}


	/**
	 * 简述客户端跳转时,传参的传递 注意:即先访问/mydemo/sleep之后,再直接访问/mydemo/eat
	 */
	@RequestMapping("/sleep.do")
	public String sleep(Model model) {
		model.addAttribute("username", "大官人");// 因为是客户端跳转两次请求,所以此参数无法获取到
		// 等同于return "redirect:/mydemo/eat.do";
		// 两种写法都要写绝对路径,而SpringMVC都会为其自动添加应用上下文
		// 如果是本类中的请求跳转则直接写成eat.do即可
		return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/sen/eat.do";
	}


	@RequestMapping("/eat.do")
	public String eat(Model model) {
		// model.addAttribute("username", "大官人");//可以访问到
		return "main/helloworld";
	}
}

5.返回页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
你好!世界!
</body>
</html>

6.高级进阶接受实体实体里面传入map和list

1.实体类1含有map

package com.senssic.vo;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;


public class BrandManageVo {

	private String logo;

	private String hasBrandPage;

	private BigDecimal sort;

	private Map<String, BrandManageLangVo> lang = new HashMap<String, BrandManageLangVo>();

	public String getLogo() {
		return logo;
	}

	public void setLogo(String logo) {
		this.logo = logo;
	}

	public String getHasBrandPage() {
		return hasBrandPage;
	}

	public void setHasBrandPage(String hasBrandPage) {
		this.hasBrandPage = hasBrandPage;
	}

	public BigDecimal getSort() {
		return sort;
	}

	public void setSort(BigDecimal sort) {
		this.sort = sort;
	}

	public Map<String, BrandManageLangVo> getLang() {
		return lang;
	}

	public void setLang(Map<String, BrandManageLangVo> lang) {
		this.lang = lang;
	}

}

2.含有map中的实体

package com.senssic.vo;

public class BrandManageLangVo {

	private String brandName;

	private String description;

	public String getBrandName() {
		return brandName;
	}

	public void setBrandName(String brandName) {
		this.brandName = brandName;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}
3.ajax实例化form对象并传送

// 将form序列化结果转为json
$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [ o[this.name] ];
			}
			o[this.name].push($.trim(this.value) || '');
		} else {
			o[this.name] = $.trim(this.value) || '';
		}
	});
	return o;
};

function doSave() {
	var postData = $("#addForm").serializeObject();
	alert(JSON.stringify($("#addForm").serializeObject()));
	$.ajax({
		type : "POST",
		url : ctx + "/brandmanage/save.ajax",
		data : postData,
		success : function(data) {
			//$("#searchResult").html(data);
			alert(data);
		}
	});
}



4.其实传送的json对象会被浏览传输参数解析为这样的

本来是这样的:


解析后传输参数为这样的:


然后后台spring会根据对应的name注入了,其中lang即为map的lang  而里面的[‘xxx’]即为对应每个map中的对应的key  相同的key表示一个BrandManageLangVo 对象切记名字一定要对应

springmvc处理方法

	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	public @ResponseBody
	String save(HttpServletRequest request, HttpServletResponse response,
			BrandManageVo brandManageVo) {

		brandManageService.save(brandManageVo);
		return "";
	}


而对于注入list其实和map差不多,唯一的区别是注入的时候将map的key换成list的索引,比如注入list中的第一个对象中的第一个属性,则为lang['1'].brandname,依次类推

其实仔细想想,万物皆通,比如list可以将其索引看出是map中的key这样list和map就一样了,世界就和平了

1.将map换成list别忘了写setter和getter方法

private final List<BrandManageLangVo> brandManageLang = new ArrayList<BrandManageLangVo>();

2.对应的请求为:


3.经过springmvc的处理就会自动注入到里面了


这样我们不用通过json而是serialize from表单传入如图上图所示的字符串就可以直接注入到springmvc相应的对象中!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值