02基于注解开发SpringMVC项目(jar包,异步,request,参数传递,多选的接收,Model传参,map传参,model传参,ajax,重定向,时间日期转换)

简介:  1 所需jar包 项目结构如下: 2 web.xml配置文件的内容如下: <?xmlversion="1.0"encoding="UTF-8"?> <web-appversion="2.5"    xmlns="http://java.sun.com/xml/ns/javaee"    xm


1 所需jar

项目结构如下:

2 web.xml配置文件的内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<web-appversion="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">

 <servlet>

   <servlet-name>springmvc</servlet-name>

   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>springmvc</servlet-name>

   <!-- struts/*,springmvc不能用/*方式,配置的url-pattern如:*.xxx -->

   <url-pattern>*.do</url-pattern>

 </servlet-mapping>

</web-app>

3 springmvc-servlet.xml的内容如下:

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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 ">

   <context:component-scanbase-package="com.rl.controller"/>

   <bean

       class="org.springframework.web.servlet.view.InternalResourceViewResolver">

      <propertyname="prefix"value="/WEB-INF/jsp/"/>

      <propertyname="suffix"value=".jsp"/>

   </bean>

 

   <!--文件上传的视图解析器 id一定是multipartResolver,不能随便定义 -->

   <beanid="multipartResolver"

   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

      <!--文件上传的最大值,以字节为单位 -->

      <propertyname="maxUploadSize"value="1024000"></property>

   </bean>

 

   <mvc:interceptors>

      <mvc:interceptor>

          <!-- path:指定要拦截的范围。语法:/(根目录)test/**,所有拦截/** -->

          <mvc:mappingpath="/**"/>

          <beanclass="com.rl.interceptor.MyInterceptor"/>

      </mvc:interceptor>

   </mvc:interceptors>

</beans>

4 Test1Controller.java的内容如下:

package com.rl.controller;

 

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

 

@Controller

@RequestMapping("/test1") //当前Controllernamespace,防止不同的Controller中方名重复的问题

public class Test1Controller {

        

        /**

         * 浏览器中的访问地址是:http://localhost:8080/springmvc2/test1/toAjax.do

         * @return

         */

        @RequestMapping("/toAjax.do")

        public String toAjax() {

                  return "ajax";

        }

}

5 TestController的内容如下:

package com.rl.controller;

 

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Date;

import java.text.SimpleDateFormat;

import java.util.HashMap;

import java.util.Map;

 

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.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

 

import com.rl.model.Person;

import com.rl.model.User;

 

@Controller

@RequestMapping("test")

//当前Controllernamespace,防止不同Controller中方法名重复的问题

public class TestController {

 

        public TestController() {

                  System.out.println("Controller被创建....");

        }

 

        /**

         * desc:返回值类型是String,含义是ModelAndView中的viewname

         *

         * @RequestMapping:请求方法的映射,内容最好和方法名称一致

         * @author 涂作权

         * @return

         */

        @RequestMapping("/hello.do")

        public String hello() {

                  return "index";

        }

 

        /**

         * desc:HttpServletRequest可以直接定义在方法的参数列表中来使用

         *

         * @param request

         * @author 涂作权

         * @return

         */

        @RequestMapping("/getParam.do")

        public String getParam(HttpServletRequest request) {

                  String name = request.getParameter("name");

                  System.out.println(name);

                  return "index";

        }

 

        /**

         * desc:在参数的列表中来直接定义要接收的参数,参数名(形象)一定要

         *             和请求中传递的参数名(实参)一致,数据类型会自动的转换,如果数据

         *             类型转换出错会报400错误???

         *

         * @param name

         * @param id

         * @param age

         * @param address

         * @param birthday

         * @author 涂作权

         * @return

         */

        @RequestMapping("/getParam1.do")

        public String getParam1(String name, Integer id, Integer age,

                           String address, Date birthday) {

                  System.out.println("姓名:" + name + " id" + id.getClass() + " 年龄:"

                                    + age + " 地址: " + address + "生日:" + birthday);

                  return "index";

        }

 

        /**

         * desc:多选的接收在参数列表中定义数组来接收,参数名(形参)一定要和请求中传递的参数名(实参)一致,数据类型会自动的转换,

         * 如果以字符串来接收的话会接收到一个以逗号分隔的一个字符串

         *

         * @author 涂作权

         * @param favor

         * @return

         */

        @RequestMapping("/getParam2.do")

        public String getParam2(String[] favor) {

                  System.out.println(favor);

                  for (String fa : favor) {

                           System.out.println(fa);

                  }

                  return "index";

        }

 

        /**

         * desc:接收实体对象,直接在参数列表中定义要接收的实体类就可以了,每次访问的时候springmvc会自动创建相关参数的实体对象,对象中

         * 的属性值是通过请求传递过来并且注入到对象中

         *

         * @author 涂作权

         * @param person

         * @param user

         * @param name

         * @return

         */

        @RequestMapping("/getParamByObj.do")

        public String getParamByObj(Person person, User user, String name) {

                  System.out.println(person);

                  System.out.println(user);

                  return "index";

        }

 

        /**

         * 不建议使用 desc:返回值类型定义成ModelAndView,把数据和视图注入到ModelAndView中返回即可

         *

         * @return

         * @author 涂作权

         * @throws Exception

         */

        @RequestMapping("/returnData.do")

        public ModelAndView returnData() throws Exception {

                  Person p = new Person();

                  p.setId(1);

                  p.setName("zhangsan");

                  p.setAge(22);

                  p.setAddress("beijing");

                  p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05"));

                  Map<String, Object> map = new HashMap<String, Object>();

                  // 相当于request.setAttribute("person", p);

                  map.put("person", p);

 

                  return new ModelAndView("index", map);

        }

 

        /**

         * 不建议使用 desc:返回值是String类型:viewName,参数是map,ModelAndView map,不是接收参数的。

         *

         * @author 涂作权

         * @param map

         * @return

         * @throws Exception

         */

        @RequestMapping("/returnData1.do")

        public String returnData1(Map<String, Object> map) throws Exception {

                  Person p = new Person();

                  p.setId(1);

                  p.setName("zhangsan");

                  p.setAge(22);

                  p.setAddress("beijing");

                  p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05"));

                  // 相当于request.setAttribute("person", p);

                  map.put("person", p);

                  return "index";

        }

 

        /**

         * 在参数列表中定义Model来给页面返回数据 desc:建议使用

         *

         * @author 涂作权

         * @param model

         * @return

         * @throws Exception

         */

        @RequestMapping("/returnData2.do")

        public String returnData2(Model model) throws Exception {

                  Person p = new Person();

                  p.setId(1);

                  p.setName("zhangsan");

                  p.setAge(22);

                  p.setAddress("beijing");

                  p.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse("2013-08-05"));

                  // 相当于request.setAttribute("person", p);

                  model.addAttribute("person", p);

                  return "index";

        }

 

        /**

         * descmethod=RequestMethod.POST该方法只能使用method指定的请求方式来指定

         */

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

        public String getParamByObjWithMethod(Person person) {

                  System.out.println(person);

                  return "success";

        }

 

        /**

         * desc:在参数列表中直接来定义HttpServletResponse并且方法的返回值要定义voidajax提供调用

         *

         * @author 涂作权

         * @param name

         * @param response

         */

        @RequestMapping("/ajax.do")

        public void ajax(String name, HttpServletResponse response) {

                  String result = "hello" + name;

                  try {

                           response.getWriter().write(result);

                  } catch (IOException e) {

                           e.printStackTrace();

                  }

        }

 

        /**

         * desc:直接在参数列表中来定义PrintWriter建议使用

         *

         * @param name

         * @param out

         */

        @RequestMapping("/ajax1.do")

        public void ajax1(String name, PrintWriter out){

                  String result = "hello " + name;

                  out.write(result);

        }

 

        @RequestMapping("/toAjax.do")

        public String toAjax(){

                  return "ajax";

        }

 

        /**

         * 在同一个Controller中重定向语法 return后面 redirect:当前

         *           Controller中方法的@RequestMapping的值

         *

         * @return

         */

        @RequestMapping("/redirectToAjax.do")

        public String redirectToAjax(){

                  return "redirect:toAjax.do";

        }

 

        /**

         * controller之间的重定向redirect:后面要有"/",代表从项目的根目录开始

         *

         * @return

         * @author 涂作权

         */

        @RequestMapping("/redirectToAjax1.do")

        public String redirectToAjax1(){

                  return "redirect:/test1/toAjax.do";

        }

 

        /**

         * 单纯的转发

         *

         * @author 涂作权

         * @return

         */

        @RequestMapping("/toForm.do")

        public String toForm(){

                  return "form";

        }

 

        /**

         * 用于转换数据类型

         * @param binder

         */

        @InitBinder

        public void initBinder(ServletRequestDataBinder binder){

                  binder.registerCustomEditor(Date.class,

                                    new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));

        }

}

6 UploadController的内容如下:

package com.rl.controller;

 

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Random;

 

import javax.servlet.http.HttpServletRequest;

 

import org.springframework.beans.propertyeditors.CustomDateEditor;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.ServletRequestDataBinder;

import org.springframework.web.bind.annotation.InitBinder;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.multipart.MultipartHttpServletRequest;

 

import com.rl.model.Person;

 

@Controller

@RequestMapping("/upload")

//当前Controllernamespace,防止不同Controller中方法名重复的问题

public class UploadController {

 

        @RequestMapping("/uploadPic.do")

        public String uploadPic(Person person, HttpServletRequest request)

                           throws Exception {

                  // request转换成MultipartHttpServletRequest

                  MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;

                  // 获得文件,这里的pic是表单中的file字段对应的属性名称

                  MultipartFile mf = mr.getFile("pic");       

                  // 获得文件的字节数组

                  byte[] fbyte = mf.getBytes();

                  // 获得当前时间的最小精度

                  String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS")

                                    .format(new Date());

                  // 追加三位随机数

                  Random random = new Random();

                  for (int i = 0; i < 3; i++) {

                           fileName = fileName + random.nextInt(10);

                  }

                  // 获得原始文件名

                  String oriFileName = mf.getOriginalFilename();

                  // 获得后缀名

                  String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));

                  // 拿到服务器的根目录

                  String realPath = request.getSession().getServletContext()

                                    .getRealPath("/");

                  // 创建文件输出流

                  OutputStream out = new FileOutputStream(new File(realPath + "/upload/"

                                    + fileName + suffix));

                  out.write(fbyte);

                  out.flush();

                  out.close();

                  return "success";

        }

 

        @InitBinder

        public void initBinder(ServletRequestDataBinder binder) {

                  binder.registerCustomEditor(Date.class, new CustomDateEditor(

                                    new SimpleDateFormat("yyyy-MM-dd"), true));

        }

}

7 MyInterceptor的内容如下:

package com.rl.interceptor;

 

import java.util.Map;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView;

 

public class MyInterceptor implements HandlerInterceptor{

 

        /**

         * 执行时机:在视图解析器解析完毕之后,页面一旦报错异常会抛到该方法中,

         * try{}catch后面的finally,用于系统监控

         */

        public void afterCompletion(HttpServletRequest arg0,

                           HttpServletResponse arg1, Object arg2, Exception ex)

                           throws Exception {

                  System.out.println("afterCompletion...................");

                  System.out.println("----------------------------------");

                  ex.printStackTrace();

                  System.out.println("----------------------------------");

        }

 

        /**

         * 执行时机:Controller执行完毕,视图解析器解析之前来执行

         * 注意:此案例中如果是测试异步,这里的mvnull,此处会报错。

         * 解决办法是注释掉springmvc-servlet.xml中的拦截器的配置内容

         */

        public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,

                           Object arg2, ModelAndView mv) throws Exception {

                  Map<String, Object> map = mv.getModel();

                  map.put("test", "append something...");

                  System.out.println("postHandle...");

        }

 

        /**

         * 返回值数据类型是布尔类型:true放行, false是阻止访问

         * 执行时机:Controller执行之前

         *

         * 最常用的应用场景就是权限的拦截

         */

        public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,

                           Object obj) throws Exception {

                  System.out.println("preHandle...");

                  System.out.println(obj.getClass().getName());

                  return true;

        }

}

8 Person的内容如下:

package com.rl.model;

 

import java.util.Date;

 

publicclass Person {

   Integer id;

   String name;

   Integer age;

   String address;

   Date birthday;

   

   /**

    * @return the id

    */

   public Integer getId() {

      returnid;

   }

   

   /**

    * @param id the id to set

    */

   publicvoid setId(Integer id) {

      this.id = id;

   }

   

   /**

    * @return the name

    */

   public String getName() {

      returnname;

   }

   

   /**

    * @param name the name to set

    */

   publicvoid setName(String name) {

      this.name = name;

   }

   

   /**

    * @return the age

    */

   public Integer getAge() {

      returnage;

   }

   

   /**

    * @param age the age to set

    */

   publicvoid setAge(Integer age) {

      this.age = age;

   }

   

   /**

    * @return the address

    */

   public String getAddress() {

      returnaddress;

   }

   

   /**

    * @param address the address to set

    */

   publicvoid setAddress(String address) {

      this.address = address;

   }

   

   /**

    * @return the birthday

    */

   public Date getBirthday() {

      returnbirthday;

   }

   

   /**

    * @param birthday the birthday to set

    */

   publicvoid setBirthday(Date birthday) {

      this.birthday = birthday;

   }

}

9 User的内容如下

package com.rl.model;

 

publicclass User {

   Integer id;

   String name;

   /**

    * @return the id

    */

   public Integer getId() {

      returnid;

   }

   /**

    * @param id the id to set

    */

   publicvoid setId(Integer id) {

      this.id = id;

   }

   

   /**

    * @return the name

    */

   public String getName() {

      returnname;

   }

   /**

    * @param name the name to set

    */

   

   publicvoid setName(String name) {

      this.name = name;

   }

   

   @Override

   public String toString() {

      return"User [id=" +id +", name=" +name +"]";

   }

}

10 ajax.jsp的内容如下:

<%@page language="java"import="java.util.*"pageEncoding="utf-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

 

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   <basehref="<%=basePath%>">

   

   <title>My JSP 'index.jsp' starting page</title>

   <metahttp-equiv="pragma"content="no-cache">

   <metahttp-equiv="cache-control"content="no-cache">

   <metahttp-equiv="expires"content="0">   

   <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

   <metahttp-equiv="description"content="This is my page">

   <scripttype="text/javascript"src="js/jquery.js"></script>

   <scripttype="text/javascript">

   $(function(){

      $("#mybutton").click(function(){

          console.log("test");

          varmytext = $("#mytext").val();

          $.ajax({

             url:"test/ajax1.do",

             type:"post",

             dataType:"text",

             data:{

                 name:mytext

             },

             success:function(responseText){

                 alert(responseText);

             },

             error:function(){

                 alert("system error");

             }

          });

      });

   });

      

   </script>

 </head>

 

 <body>

  <inputtype="text"id="mytext"/>

  <inputid="mybutton"type="button"value="click"/>

 </body>

</html>

11 form.jsp的内容如下:

<%@page language="java"import="java.util.*"pageEncoding="utf-8"%>

 

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   

   <title>My JSP 'form.jsp' starting page</title>

   

 </head>

 

 <body>

   <formaction="upload/uploadPic.do"method="post"enctype="multipart/form-data">

   id<inputname="id"type="text"/><br>

   name<inputname="name"type="text"/><br>

   age<inputname="age"type="text"/><br>

   address<inputname="address"type="text"/><br>

   birthday<inputname="birthday"type="text"/><br>

   pic:<inputtype="file"name="pic"/><br>

   <inputvalue="submit"type="submit"/>

   </form>

 </body>

</html>

12 index.jsp的内容如下:

<%@page language="java"import="java.util.*"pageEncoding="utf-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/fmt"prefix="fmt"%>

 

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   

   <title>My JSP 'index.jsp' starting page</title>

   

 </head>

 

 <body>

   <h1>${person.id}</h1>

   <h1>${person.name}</h1>

   <h1>${person.age}</h1>

   <h1>${person.address}</h1>

   <h1><fmt:formatDatevalue="${person.birthday }"pattern="yyyy-MM-dd"/></h1>

   <h1>${test }</h1>

 </body>

</html>

13 success.jsp的内容如下:

<%@page language="java"import="java.util.*"pageEncoding="utf-8"%>

 

<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

 <head>

   

   <title>My JSP 'success.jsp' starting page</title>

   

 </head>

 

 <body>

   success<br>

 </body>

</html>

 

目录
相关文章
SpringMVC入门到实战------5、域对象共享数据 Request、Session、Application、Model、ModelAndView、Map、ModelMap的详细使用及代码实例
这篇文章详细解释了在IntelliJ IDEA中如何使用Mute Breakpoints功能来快速跳过程序中的后续断点,并展示了如何一键清空所有设置的断点。
SpringMVC入门到实战------5、域对象共享数据 Request、Session、Application、Model、ModelAndView、Map、ModelMap的详细使用及代码实例
|
1月前
|
存储 分布式计算 Java
Stream很好,Map很酷,但答应我别用toMap():Java开发中的高效集合操作
在Java的世界里,Stream API和Map集合无疑是两大强大的工具,它们极大地简化了数据处理和集合操作的复杂度。然而,在享受这些便利的同时,我们也应当警惕一些潜在的陷阱,尤其是当Stream与Map结合使用时。本文将深入探讨Stream与Map的优雅用法,并特别指出在使用toMap()方法时需要注意的问题,旨在帮助大家在工作中更高效、更安全地使用这些技术。
38 0
域对象共享数据model、modelAndView、map、mapModel、request。从源码角度分析
这篇文章详细解释了在IntelliJ IDEA中如何使用Mute Breakpoints功能来快速跳过程序中的后续断点,并展示了如何一键清空所有设置的断点。
域对象共享数据model、modelAndView、map、mapModel、request。从源码角度分析
|
4月前
|
Java
[JarEditor]可直接修改jar包的IDEA插件
### 修改JAR包变得更简单:JarEditor插件简介 **背景:** 开发中常需修改JAR包中的class文件,传统方法耗时费力。JarEditor插件让你一键编辑JAR包内文件,无需解压。 **插件使用:** 1. **安装:** 在IDEA插件市场搜索JarEditor并安装。 2. **修改class:** 打开JAR文件中的class,直接编辑,保存后一键构建更新JAR。 3. **文件管理:** 右键菜单支持在JAR内新增/删除/重命名文件等操作。 4. **搜索:** 使用内置搜索功能快速定位JAR包内的字符串。
455 2
[JarEditor]可直接修改jar包的IDEA插件
|
4月前
|
弹性计算 Java Serverless
Serverless 应用引擎操作报错合集之上传自定义JAR包,启动时报错,是什么导致的
Serverless 应用引擎(SAE)是阿里云提供的Serverless PaaS平台,支持Spring Cloud、Dubbo、HSF等主流微服务框架,简化应用的部署、运维和弹性伸缩。在使用SAE过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
|
4月前
|
关系型数据库 Java 分布式数据库
PolarDB产品使用问题之部署到服务器上的Java应用(以jar包形式运行)无法连接,如何解决
PolarDB产品使用合集涵盖了从创建与管理、数据管理、性能优化与诊断、安全与合规到生态与集成、运维与支持等全方位的功能和服务,旨在帮助企业轻松构建高可用、高性能且易于管理的数据库环境,满足不同业务场景的需求。用户可以通过阿里云控制台、API、SDK等方式便捷地使用这些功能,实现数据库的高效运维与持续优化。
|
3月前
|
Java Serverless Go
Golang 开发函数计算问题之在 Golang 中避免 "concurrent map writes" 异常如何解决
Golang 开发函数计算问题之在 Golang 中避免 "concurrent map writes" 异常如何解决
|
4月前
|
Java 应用服务中间件
tomcat7 与 tomcat8 加载 jar包的顺序
tomcat7 与 tomcat8 加载 jar包的顺序
162 0
|
4月前
|
Java 应用服务中间件 API
java 启动查看jar包加载顺序并设置classpath
java 启动查看jar包加载顺序并设置classpath
368 0

热门文章

最新文章