SpringMvc
contextConfigLocation
/WEB-INF/springmvc-servlet.xml, classpath:applicationContext-*.xml
springmvc
org.springframework.web.servlet.DispatcherServlet
springmvc
*.do
index.html
index.htm
index.jsp
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;
};
}
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 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";
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
你好!世界!
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 lang = new HashMap();
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 getLang() {
return lang;
}
public void setLang(Map lang) {
this.lang = lang;
}
}
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);
}
});
}
本来是这样的:
解析后传输参数为这样的:
然后后台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
2.对应的请求为:
3.经过springmvc的处理就会自动注入到里面了
这样我们不用通过json而是serialize from表单传入如图上图所示的字符串就可以直接注入到springmvc相应的对象中!