框架第十四天

spring mvc 外部开发
需要


在原来的spring jar包的基础上添加两个jia包.png

解决乱码,修改回显,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包


spring mvc json jar.png
<%@ 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>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,367评论 6 343
  • 这个10天,发生了一件大事。就是我发现自己怀孕了。 我想,群里的妈妈们,都知道那种刚怀孕的惊喜与惊恐。 一方面惊喜...
    祘末酱阅读 107评论 1 0
  • 我们常说“陪伴是最长情的告白”,其实用在父母对孩子身上也是合适的。大人都知道陪孩子不就是给他做饭洗衣监督学习上兴趣...
    乔妹读书阅读 227评论 2 1
  • 雨给了春的生命,让春有了想葫动的心怀, 雨给了夏的力量,让复有了想要生长的冲动! 雨给了秋的成熟,让秋有了想要收获...
    风曰云语阅读 355评论 0 0