spring mvc 外部开发
需要
解决乱码,修改回显,json数据传输,根据出生日期计算年龄
在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">
<!-- 配置spring mvc -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 如果放在WEB-INF文件下则不用此配置-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/mvc-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 编码过滤器 --><!-- 解决乱码 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
mvc-servlet.xml配置<mvc:annotation-driven/>
<?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:context="http://www.springframework.org/schema/context"
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.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 配置扫描 -->
<mvc:annotation-driven/><!--需要controller返回一个map的json对象时,可以设定 头文件里面要有xmlns:mvc-->
<context:component-scan base-package="com.hw.controller"></context:component-scan>
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property> <!-- 前缀 -->
<property name="suffix" value=".jsp"></property><!-- 后缀 -->
</bean>
</beans>
在这里我解释一下为什么要用<mvc:annotation-driven />
<mvc:annotation-driven /> 是一种简写形式,完全可以手动配置替代这种简写形式,
简写形式可以让初学都快速应用默认配置方案。<mvc:annotation-driven /> 会自动
注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个
bean,是spring MVC为@Controllers分发请求所必须的。
并提供了:数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat
支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
后面,我们处理响应ajax请求时,就使用到了对json的支持。
后面,对action写JUnit单元测试时,要从spring IOC容器中取DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter
两个bean,来完成测试,取的时候要知道是<mvc:annotation-driven />这一句注册的这两个bean。
修改页面回显 用model存储对象 可以实现回显
package com.hw.controller;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.ResponseBody;
import com.hw.entity.Person;
import com.hw.entity.Person1;
import com.hw.service.impl.PersonServiceImpl;
import com.hw.utils.PageUtils;
@Controller
@RequestMapping("per")
public class PersonController {
private PersonServiceImpl db = new PersonServiceImpl();
@RequestMapping("listJson")//per/listJson.do
@ResponseBody//生成json格式,表中所有内容,集合
public List<Person> listJson(){
List<Person> list = db.listAll();
return list;
}
@RequestMapping("perJson")// per/perJson.do
@ResponseBody//生成json格式的单个对象
public Person perJson(int id){
Person list = db.getPerson(id);
return list;
}
@RequestMapping("addJson")//per/addJson.do
public String addJson() {
return "addJson";
}
@RequestMapping("addajax")
public void addajax(Person per,HttpServletResponse response) throws IOException {
db.addPerson(per);
PrintWriter out = response.getWriter();
out.print("1");
out.flush();
out.close();
}
@RequestMapping("toadd")
public String toAdd() {
return "add";
}
@RequestMapping("add")
public String add(Person per) {
db.addPerson(per);
return "redirect:list.do";
}
@RequestMapping("toupdate")
public String toUpdate(Model mod, int id) {// 一般用HttpServletRequest
Person person = db.getPerson(id);
mod.addAttribute("per", person);//用model存储对象 可以实现回显 只需要在修改页面对象.属性(el表达式)
return "update";
}
@RequestMapping("update")
public String update(Person per) {
db.updatePerson(per);
return "redirect:list.do";
}
@RequestMapping("del")
public String del(int id) {// 一般用HttpServletRequest
db.delPerson(id);
return "redirect:list.do";
}
@RequestMapping("delall")
public String delall(String id) {// 一般用HttpServletRequest
db.delAllPerson(id);
return "redirect:list.do";
}
@SuppressWarnings("deprecation")
@RequestMapping("list")
public String show(HttpServletRequest request) {// 一般用HttpServletRequest
int pageSize = 3;
String page = request.getParameter("currentPage") == null ? "1"
: request.getParameter("currentPage");// 取传过来的页数
int currentPage = Integer.parseInt(page);// 转让为整型
List<Person> list = db.list(currentPage, pageSize);
int dataCount = db.getCount();
PageUtils.page(request, currentPage, pageSize, list, dataCount);
/*Date dd=new Date();
List<Person1> list1=new ArrayList<Person1>();
for(Person per:list){
Person1 pp=new Person1();
pp.setId(per.getId());
pp.setName(per.getName());
pp.setBirthday(per.getBirthday());
pp.setAge(dd.getYear()-per.getBirthday().getYear());
list1.add(pp);
}
request.setAttribute("list", list1);*/
request.setAttribute("list", list);
return "list";
}
@SuppressWarnings("unused")
@InitBinder// spring mvc中对时间进行处理
private void InitBinder(HttpServletRequest request,
ServletRequestDataBinder binder) {
// spring mvc中对时间进行处理
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
在修改页面uodate.jsp 对象.属性名
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"
src="<%=request.getContextPath()%>/js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/My97DatePicker/WdatePicker.js"></script>
</head>
<body>
<form action="<%=request.getContextPath() %>/per/update.do" method="post" name="kk">
<table align="center" width="460px" border="0">
<input type="hidden" name="id" value="${per.id}">
<tr>
<td>姓名:</td><td><input type="text" name="name" value="${per.name}"></td></tr>
<tr>
<td>出生日期:</td><td><input type="text" value="${per.birthday}" name="birthday" onclick="WdatePicker()"></td></tr>
<tr align="center">
<td colspan="12"><br> <input type="submit" value="会员修改"
id="btn"> <input type="reset" value="清除">
</td>
</tr>
</table>
</form>
</body>
</html>
根据出生日期计算年龄 用当前时间减去出生日期的时间
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'list.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet"
href="<%=request.getContextPath()%>/styles/index.css" type="text/css"></link>
<link rel="stylesheet"
href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript"
src="<%=request.getContextPath()%>/js/jquery-1.8.2.js"></script>
<script type="text/javascript"
src="<%=request.getContextPath()%>/js/my.js" charset="gbk"></script>
<script type="text/javascript">
function del(a){
if(confirm("确认删除吗?")){
location="per/del.do?id="+a;
}
}
</script>
<script type="text/javascript">
$(function() {
$("#json").click(function(){
location="per/addJson.do";
});
});
</script>
<style type="text/css">
th {
text-align: center
}
td {
text-align: center
}
</style>
</head>
<body>
<center>
<h2>用户管理</h2>
<table align="center">
<tr>
<th>用户编号 <input type="checkbox" id="check">
</th>
<th>姓名</th>
<th>出生日期</th>
<th>年龄</th>
<th>操作(<a href="per/toadd.do">添加</a>)</th>
<th><input type="button" value="json添加" id="json"></th>
</tr>
<c:forEach items="${list}" var="list">
<tr>
<td><input type="checkbox" name="sem" value="${list.id}">${list.id}</td>
<td>${list.name}</td>
<td>${list.birthday}</td>
<td>${list.age} </td>
<td>
<!-- 用当前时间减去出生日期的时间 -->
<script type="text/javascript">
var a=new Date();
var b=new Date("${list.birthday}");
document.write(a.getYear()-b.getYear());
</script>
</td>
<td>
<a href="per/toupdate.do?id=${list.id}">修改</a> <a
href="javascript:void" onclick="del(${list.id})">删除</a>
</td>
</tr>
</c:forEach>
<tr>
<td colspan="20" align="center"><input type="button" value="全选" id="btn1">
<input type="button" value="全不选" id="btn2"> <input
type="button" value="删除全部" id="btn4"> <input type="button"
value="删除所选" id="btn5"> <br> ${group} <br></td>
</tr>
</table>
</center>
</body>
</html>
用ajax异步请求controller传过来的json数据
首先必须要有spring mvc的json的jar包
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript"
src="<%=request.getContextPath()%>/js/jquery-1.8.2.js"></script>
<script type="text/javascript"
src="<%=request.getContextPath()%>/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript">
$(function() {
$.post("per/listJson.do", function(msg) {
for (i = 0; i < msg.length; i++) {
$("#show").append(
"<tr><td>" + msg[i].id + "</td><td>" + msg[i].name
+ "</td><td>" + msg[i].birthday
+ "</td><td>删除 修改</td></tr>");
}
});
$("#addbtn").click(function() {
if ($("input[name='name']").val().trim() == "") {
alert("姓名不能为空!!!");
} else if ($("input[name='birthday']").val().trim() == "") {
alert("出生日期不能为空!!!");
}else{
$.post("per/addajax.do", {
name : $("input[name='name']").val(),
birthday : $("input[name='birthday']").val()
}, function(msg) {
alert(eval(msg));
if (msg == 1) {
location.reload(true);
}
});
}
});
});
</script>
</head>
<body>
<form action="<%=request.getContextPath()%>/per/add.do" method="post"
name="kk">
<table align="center" width="460px" border="0">
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>出生日期:</td>
<td><input type="text" name="birthday" onclick="WdatePicker()">
</td>
</tr>
<tr align="center">
<td colspan="12"><br> <input type="button" value="会员注册"
id="addbtn"> <input type="reset" value="清除">
</td>
</tr>
</table>
</form>
<table align="center">
<tr>
<th><input type="checkbox" id="check">用户编号</th>
<th>姓名</th>
<th>出生日期</th>
<th>操作(<a href="per/toadd.do">添加</a>)</th>
</tr>
<tbody id="show"></tbody>
</table>
</body>
</html>