码迷,mamicode.com
首页 > 编程语言 > 详细

02基于注解开发SpringMVC项目

时间:2015-01-04 21:26:35      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:



1  所需jar

技术分享

项目结构如下:

技术分享

技术分享

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

  <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的内容如下:

<?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: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-scan base-package="com.rl.controller" />

    <bean

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

       <property name="prefix" value="/WEB-INF/jsp/" />

       <property name="suffix" value=".jsp" />

    </bean>

 

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

    <bean id="multipartResolver"

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

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

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

    </bean>

 

    <mvc:interceptors>

       <mvc:interceptor>

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

           <mvc:mapping path="/**" />

           <bean class="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;

 

public class Person {

    Integer id;

    String name;

    Integer age;

    String address;

    Date birthday;

   

    /**

     * @return the id

     */

    public Integer getId() {

       return id;

    }

   

    /**

     * @param id the id to set

     */

    public void setId(Integer id) {

       this.id = id;

    }

   

    /**

     * @return the name

     */

    public String getName() {

       return name;

    }

   

    /**

     * @param name the name to set

     */

    public void setName(String name) {

       this.name = name;

    }

   

    /**

     * @return the age

     */

    public Integer getAge() {

       return age;

    }

   

    /**

     * @param age the age to set

     */

    public void setAge(Integer age) {

       this.age = age;

    }

   

    /**

     * @return the address

     */

    public String getAddress() {

       return address;

    }

   

    /**

     * @param address the address to set

     */

    public void setAddress(String address) {

       this.address = address;

    }

   

    /**

     * @return the birthday

     */

    public Date getBirthday() {

       return birthday;

    }

   

    /**

     * @param birthday the birthday to set

     */

    public void setBirthday(Date birthday) {

       this.birthday = birthday;

    }

}

9 User的内容如下

package com.rl.model;

 

public class User {

    Integer id;

    String name;

    /**

     * @return the id

     */

    public Integer getId() {

       return id;

    }

    /**

     * @param id the id to set

     */

    public void setId(Integer id) {

       this.id = id;

    }

   

    /**

     * @return the name

     */

    public String getName() {

       return name;

    }

    /**

     * @param name the name to set

     */

   

    public void 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+"/";

%>

 

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

<html>

  <head>

    <base href="<%=basePath%>">

   

    <title>My JSP ‘index.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="js/jquery.js"></script>

    <script type="text/javascript">

    $(function(){

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

           console.log("test");

           var mytext = $("#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>

   <input type="text" id="mytext"/>

   <input id="mybutton" type="button" value="click"/>

  </body>

</html>

11 form.jsp的内容如下:

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

 

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

<html>

  <head>

   

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

   

  </head>

 

  <body>

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

    id<input name="id" type="text"/><br>

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

    age<input name="age" type="text"/><br>

    address<input name="address" type="text"/><br>

    birthday<input name="birthday" type="text"/><br>

    pic:<input type="file" name="pic"/><br>

    <input value="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"%>

 

<!DOCTYPE HTML 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:formatDate value="${person.birthday }" pattern="yyyy-MM-dd"/></h1>

    <h1>${test }</h1>

  </body>

</html>

13 success.jsp的内容如下:

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

 

<!DOCTYPE HTML 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项目

标签:

原文地址:http://blog.csdn.net/tototuzuoquan/article/details/42397283

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!