springmvc入门二

 

回顾什么是springmvc,它与spring有什么关系

springmvc属于spring框架的后续产品,用在基于MVC的表现层开发,类似于struts2框架

参见<<springmvc与spring的关系.JPG>>

 

 

回顾springmvc工作流程

参见<< springmvc工作流.JPG>>

 

 

第十四章 springmvc快速入门(注解版本)

1)springmvc快速入门(注解版)

   步一:创建javaee-springmvc-day02这么一个web应用

   步二:导入springioc,springweb和springmvc相关的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="cn.itcast.javaee.springmvc.helloannotation"/> 

       

</beans>

步七:部署web应用到tomcat中,通过浏览器访问如下URL:

       http://127.0.0.1:8080/ javaee-springmvc-day02/hello.action

 

 

第十五章一个Action中,可以写多个类似的业务控制方法

1)通过模块根路径 + 功能子路径 = 访问模块下子功能的路径

@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";

    }  

}

增加用户:http://127.0.0.1:8080/myspringmvc-day02/user/add.action

查询用户:http://127.0.0.1:8080/myspringmvc-day02/user/find.action

 

 

第十六章在业务控制方法中写入普通变量收集参数

1)可以在业务控制方法中,以参数形式收集客户端参数,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";

    }  

}

    http://127.0.0.1:8080/myspringmvc-day02/user/add.action?id=1&name=zhaojun&sal=5000

  

 

第十七章限定某个业务控制方法,只允许GETPOST请求方式访问

1)可以在业务控制方法前,指明该业务控制方法只能接收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";

    }  

}

    如果不书写method=RequestMethod.POST的话,GET和POST请求都支持

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

        <input type="text" name="empno" value="1111"/><br/>

        <input type="text" name="ename" value="思思"/><br/>

        <input type="text" name="sal" value="8000"/><br/>

        <input type="submit" value="提交"/>

    </form>

 

 

第十八章在业务控制方法中写入RequestResponse等传统web参数

1)可以在业务控制方法中书写传统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来解决字符串转日期类型

1)  在默认情况下,springmvc不能将String类型转成java.util.Date类型,所以我们只能在Action

中自定义类型转换器

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

       编号:<input type="text" name="id" value="${id}"/><br/>

        姓名:<input type="text" name="name" value="${name}"/><br/>

       薪水:<input type="text" name="sal" value="${sal}"/><br/>

       入职时间:<input type="text" name="hiredate" value='<fmt:formatDate value="${hiredate}" type="date"/>'/><br/>

       <input type="submit" value="注册"/>

    </form>

 

@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";

    }

}

 

 

第二十章在业务控制方法中写入UserAdmin多个模型收集参数

1)  可以在业务控制方法中书写1个模型来收集客户端的参数

2)  模型中的属性名必须和客户端参数名一一对应,且提供set/get方法

3)  这里说的模型不是Model对象,Model是向视图中封装的数据

    User:<br/>

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

        <input type="text" name="empno" value="1111"/><br/>

        <input type="text" name="ename" value="思思"/><br/>

        <input type="text" name="sal" value="8000"/><br/>

        <input type="submit" value="提交"/>

    </form>

    <hr/>

    Admin:<br/>

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

        <input type="text" name="empno" value="2222"/><br/>

        <input type="text" name="ename" value="大大"/><br/>

        <input type="text" name="tel" value="13512341234"/><br/>

        <input type="submit" value="提交"/>

    </form>

 

public class User {

    private int empno;

    private String ename;

    private int sal;

public class Admin {

    private int empno;

    private String ename;

    private int tel;

 

@Controller

@RequestMapping(value="/user")

public class UserAction {

    @RequestMapping(value="/add",method=RequestMethod.POST)

    public String add(User user,Admin admin,Model model) throws Exception{

        model.addAttribute("user",user);

        model.addAttribute("admin",admin);

        model.addAttribute("message","增加成功");

        return "/jsp07/success.jsp";

    }  

}

 

 

第二十一章在业务控制方法中写入包装User的模型来收集参数

可以在业务控制方法中书写0个或多个模型来收集客户端的参数

1)  如果多个模型中有相同的属性时,可以用user.name或admin.name来收集客户端参数

2)  用一个新的模型将User和Admin再封装一次

public class User {

    private int empno;

    private String ename;

    private int sal;

public class Admin {

    private int empno;

    private String ename;

    private int tel;

public class Bean {

    private User user;

    private Admin admin;

    UserAction.java

@Controller

@RequestMapping(value="/user")

public class UserAction {

    @RequestMapping(value="/add",method=RequestMethod.POST)

    public String add(Bean bean,Model model) throws Exception{

        model.addAttribute("bean",bean);

        model.addAttribute("message","增加成功");

        return "/jsp08/success.jsp";

    }  

}

    user.jsp

    User:<br/>

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

        <input type="text" name="user.empno" value="1111"/><br/>

        <input type="text" name="user.ename" value="思思"/><br/>

        <input type="text" name="user.sal" value="8000"/><br/>

        <input type="submit" value="提交"/>

    </form>

    <hr/>

    Admin:<br/>

    <form action="${pageContext.request.contextPath}/user/add.action" method="POST">

        <input type="text" name="admin.empno" value="2222"/><br/>

        <input type="text" name="admin.ename" value="大大"/><br/>

        <input type="text" name="admin.tel" value="135"/><br/>

        <input type="submit" value="提交"/>

    </form>

    success.jsp

    ${requestScope.message}<p/>

    <hr/>

    User:<br/>

    ${requestScope.bean.user.empno}<p/>

    ${requestScope.bean.user.ename}<p/>

    ${requestScope.bean.user.sal}<p/>

    <hr/>

    Admin:<br/>

    ${requestScope.bean.admin.empno}<p/>

    ${requestScope.bean.admin.ename}<p/>

    ${requestScope.bean.admin.tel}<p/>

   

 

第二十二章在业务控制方法中收集数组参数

批量删除用户

@Controller

@RequestMapping(value="/user")

public class UserAction {

    @RequestMapping(value="/add")

    public String add(int[] ids,Model model) throws Exception{

        model.addAttribute("message","批量删除用户成功");

        model.addAttribute("ids",ids);

        return "/jsp09/success.jsp";

    }  

}

    success.jsp

    ${requestScope.message}<br/>

    删除员工的编号分别为:

    <c:forEach var="id" items="${ids}">

        ${id}&nbsp;&nbsp;&nbsp;

    </c:forEach>

    http://127.0.0.1:8080/javaee-springmvc-day02/user/add.action?ids=1&ids=2&ids=3

 

 

第二十三章在业务控制方法中收集List<JavaBean>参数

批量注册用户

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";

    }

}

    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>

 

 

第二十四章结果的转发和重定向

1)  在转发情况下,共享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";

    }

   

}

   

@Controller

@RequestMapping(value="/user")

public class UserAction {

    @RequestMapping(value="/addAll")

    public String add(Bean bean,Model model) throws Exception{

        model.addAttribute("message","批量注册用户成功");

        model.addAttribute("bean",bean);

        return "redirect:/jsp11/success.jsp";

        //return "forward:/jsp11/success.jsp";

    }  

}

 

 

第二十五章异步发送表单数据到JavaBean,并响应JSON文本返回

1)  提交表单后,将JavaBean信息以JSON文本形式返回到浏览器

user.jsp

<form>

        <input type="text" name="empno" value="1111"/><br/>

        <input type="text" name="ename" value="思思"/><br/>

        <input type="text" name="sal" value="8000"/><br/>

        <input type="button" value="提交"/>

    </form>

    <script type="text/javascript">

        $(":button").click(function(){

            var empno = $("input[name='empno']").val();

            var ename = $("input[name='ename']").val();

            var sal = $("input[name='sal']").val();

            var url = "${pageContext.request.contextPath}/user/add.action?id="+new Date().getTime();

            var sendData = {

                "empno":empno,

                "ename":ename,

                "sal":sal

            };

            $.post(url,sendData,function(backData){

                alert(backData.empno+"#"+backData.ename+"#"+backData.sal);

            });

        });

    </script>

    User.java

public class User {

    private Integer id;

    private String name;

    private Double sal;

    public User(){}

    public Integer getId() {

       return id;

    }

    public void setId(Integer id) {

       this.id = id;

    }

    public String getName() {

       return name;

    }

    public void setName(String name) {

       this.name = name;

    }

    public Double getSal() {

       return sal;

    }

    public void setSal(Double sal) {

       this.sal = sal;

    }

}

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

    <context:component-scan base-package="cn.itcast.javaee.springmvc.app12" />

 

    <!-- 配适器 -->

    <bean

        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

        <property name="messageConverters">

            <list>

                <bean

                    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

            </list>

        </property>

    </bean>

 

 

第二十六章上传单个中文名文件

1)  上传本质是文件从客户端复制到服务器端的过程

upload.jsp

    <form

        action="${pageContext.request.contextPath}/upload.action"

        method="POST"

        enctype="multipart/form-data">

        <input type="file" name="uploadFile"/>

        <input type="submit" value="上传"/>

    </form>

    success.jsp

上传成功<br/>

    UploadAction.java

@Controller

public class UploadAction {

 

    @RequestMapping(value = "/upload")

    public String uploadMethod(@RequestParam("uploadFile") MultipartFile uploadFile) throws Exception{

        System.out.println("上传文件");

        if(!uploadFile.isEmpty()){

            String uploadFileName = uploadFile.getOriginalFilename();

            byte[] data = uploadFile.getBytes();

            OutputStream os = new FileOutputStream("E:/upload/"+uploadFileName);

            os.write(data);

            os.flush();

            os.close();

        }

        return "/jsp13/success.jsp";

    }

}

 

 

第二十七章上传多个中文名文件

1)作业题

 

 

第二十八章下载中文名文件

1)下载本质上是文件从服务器端复制到客户端的过程

@Controller

public class DownloadAction {

    @RequestMapping(value="/download")

    public void downloadMethod(HttpServletRequest request,HttpServletResponse response){

        try {

            String fileName = "问题解答.txt";

            String fileNameEncoder = URLEncoder.encode(fileName,"UTF-8");

           

            response.setContentType("application/x-msdownload");

            response.setHeader("content-disposition","attachment;filename="+fileNameEncoder);

           

            InputStream is = request.getSession().getServletContext().getResourceAsStream("/jsp14/download/问题解答.txt");

            OutputStream os = response.getOutputStream();

           

            copy(is,os);

           

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    private void copy(InputStream is,OutputStream os){

        try{

            byte[] buf = new byte[1024];

            int len = 0;

            while((len=is.read(buf))>0){

                os.write(buf,0,len);

            }

        }catch(Exception e){

            e.printStackTrace();

        }finally{

            if(is!=null){

                try {

                    is.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if(os!=null){

                try {

                    os.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

}

 

 

第二十九章表单手工验证

    <form action="${pageContext.request.contextPath}/login.action" method="POST">

        编号:<input type="text" name="empno" value=""/>${requestScope.errorMap.empno_is_null}<br/>

        姓名:<input type="text" name="ename" value=""/>${requestScope.errorMap.ename_is_null}<br/>

        薪水:<input type="text" name="sal" value=""/>${requestScope.errorMap.sal_is_null}<br/>

        <input type="submit" value="登录"/>

    </form>

   

public class User {

    private Integer empno;

    private String ename;

    private Integer sal;

   

@Controller

public class UserAction {

   

    @RequestMapping(value="/login")

    public String loginMethod(User user,Model model) throws Exception{

        Map<String,String> errorMap = validateUser(user);

        if(errorMap.size()>0){

            model.addAttribute("errorMap",errorMap);

            return "/jsp15/user.jsp";

        }else{

            model.addAttribute("message","验证成功");

            return "/jsp15/success.jsp";

        }

    }

   

    private Map<String,String> validateUser(User user){

        Map<String,String> errorMap = new LinkedHashMap<String, String>();

        if(user.getEmpno()==null){

            errorMap.put("empno_is_null","编号不能为空");

        }

        if(user.getEname()==null || user.getEname().trim().length()==0){

            errorMap.put("ename_is_null","姓名不能为空");

        }

        if(user.getSal()==null){

            errorMap.put("sal_is_null","薪水不能为空");

        }

        return errorMap;

    }

}

 

 

第三十章员工管理系统--查询员工

1)EasyUI + Springmvc + Spring + Jdbc + Oracle

 

posted @ 2016-02-19 01:28  帅如风  阅读(134)  评论(0编辑  收藏  举报