首页 > 代码库 > 02基于注解开发SpringMVC项目

02基于注解开发SpringMVC项目



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 = http://www.mamicode.com/"/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>

 

02基于注解开发SpringMVC项目