您的位置:首页 > 编程语言 > Java开发

工作笔记(三):SpringMVC入门实例--全注解方式

2013-03-05 12:37 483 查看
   由于以前各种配置文件弄得头晕眼花,故有人提出了约定优于配置的说法,及尽量少的减少需要配置的东西.而jdk1.5有了注解,so,终于可以摆脱那一堆配置文件啦.spring
2.5貌似就支持了,咱用最新的3.2~
   1.新建一个maven web工程,pom.xml修改如下:
 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>bo.mvc.maven</groupId>
<artifactId>maven-mvc-bo</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>maven-mvc-bo Maven Webapp</name>
<dependencies>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.9</version>
</dependency>
<!-- spring mvc核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<!-- springMVC注解所需依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.1.RELEASE</version>
</dependency>
<!-- jstl依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- ajax依赖 -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.9</version>
</dependency>
<!-- 如下2个依赖是为了在jsp页面使用java的代码提示 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
</dependencies>
<build>
<!--产生的构件的文件名,默认值是${artifactId}-${version}。 -->
<finalName />
<!--当filtering开关打开时,使用到的过滤器属性文件列表 -->
<filters />
<!--子项目可以引用的默认插件信息。该插件配置项直到被引用时才会被解析或绑定到生命周期。给定插件的任何本地配置都会覆盖这里的配置 -->
<pluginManagement>
<!--使用的插件列表 。 -->
<plugins>
<!--plugin元素包含描述插件所需要的信息。 -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.9.v20130131</version>
<configuration>
<webAppConfig>
<contextPath>/bo</contextPath>
</webAppConfig>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>


 2.修改web.xml文件如下:

 
<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"> 
<display-name>mvcbo</display-name>
<!-- spring 配置文件所在位置,如下是默认配置,可以不配 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<!-- spring 核心监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springMVC核心servlet, 这里在配成springmvc,为spring-servlet.xml的文件,主要用来配置它的controller -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/WEB-INF/view/test.jsp</welcome-file>
</welcome-file-list>
</web-app>


 3.创建并修改applicationContext.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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 
<!-- 向 Spring 容器注册 AutowiredAnnotationBeanPostProcessor(@Autowired)、CommonAnnotationBeanPostProcessor(@ Resource 、@ PostConstruct、@ PreDestroy)、 PersistenceAnnotationBeanPostProcessor(@PersistenceContext)
以及 RequiredAnnotationBeanPostProcessor(@Required) 这 4 个BeanPostProcessor。 注册这4个 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。 -->
<context:annotation-config />
<!-- 配置扫描包路径选项,该配置项其实也包含了context:annotation-config的功能,配置了这个,上面的配置可以不配置 -->
<context:component-scan base-package="*" />
<!-- Spring 3.0加入的对多个配置文件的加载 -->
<context:property-placeholder location="classpath:a.properties" ignore-unresolvable="true" />
<context:property-placeholder location="classpath:b.properties" ignore-unresolvable="true" />
</beans>


 4.创建并修改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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
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/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 http://www.springframework.org/schema/context http://www.springframework. 4000
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">

<context:component-scan base-package="*" />

<context:property-placeholder location="classpath:a.properties" ignore-unresolvable="true" />
<context:property-placeholder location="classpath:b.properties" ignore-unresolvable="true" />

<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp" />
<!-- 自动启动Spring MVC的注解功能 -->
<mvc:annotation-driven />
</beans>


4.最简单的TestController.java
@Controller
public class TestController {
/**
* http://localhost:8080/bo/test1.do */
@RequestMapping("/test1")
public ModelAndView test1() {
logger.info("TEST1 START!");
// 这里实际上是指向了前面配置的/WEB-INF/view/test.jsp
ModelAndView model = new ModelAndView("test");
// 将a参数带回页面
model.addObject("a", "test1A");
return model;
}
}


5.常用的注解@RequestMapping的几种用法,我会在方法头写上访问所需的url

   
/**
* http://localhost:8080/bo/test2.do *
* @param model
*            带回页面的model
* @return
*/
@RequestMapping("/test2")
public String test2(Model model) {
model.addAttribute("a", "test2A");
return "test";
}

/**
* http://localhost:8080/bo/test3.do 只拦截get请求
*/
@RequestMapping(value = "/test3", method = RequestMethod.GET)
public String test3(Model model) {
logger.info("TEST3 START!");
model.addAttribute("a", "test3A");
return "test";
}

/**
* http://localhost:8080/bo/test4/name/key.do * 这个方法可以将页面的参数当成url拼接,个人觉得这个方法有容易造成url混乱,逻辑能力不好的慎用
*/
@RequestMapping("/test4/{name}/{key}")
public String test4(@PathVariable("name") String name, @PathVariable("key") String key, Model model) {
logger.info("TEST4 START!");
model.addAttribute("a", name + key + "test4");
return "test";
}

/**
* http://localhost:8080/bo/test5.do?myParam=myValue * 只拦截带有myParam=myValue参数的url
*/
@RequestMapping(value = "/test5", params = "myParam=myValue")
public String test5(Model model) {
logger.info("TEST5 START!");
model.addAttribute("a", "test5");

return "test";
}

/**
* post提交
*/
@RequestMapping(value = "/testPost")
public String testPost(TestBean testBean, Model model) {
logger.info(testBean.getId() + testBean.getName());
testBean.setName("postyunlei");
testBean.setId("post102");
model.addAttribute("testBean", testBean);
return "test";
}

/**
* ajax调用
*/
@RequestMapping(value = "/testAjax")
@ResponseBody
public TestBean testAjax(@RequestBody TestBean testBean) {
logger.info("testAjax:" + testBean.getId() + testBean.getName());
testBean.setName("ajaxyunlei");
testBean.setId("ajaxid");
return testBean;
}


 
 

 
6.常用的注解@ModelAttribute, 被@ModelAttribute注释的方法会在此controller每个方法执行前被执行
  
/**
* 被@ModelAttribute注释的方法会在此controller每个方法执行前被执行
*
* 该方法实际上在controller每个方法执行前执行,并将a=modelAttributeName传回页面,等同于每段方法里加上model.
* addAttribute("a", "modelAttributeName");
*/
@ModelAttribute("a")
public String initName() {
logger.info("initName!");
return "modelAttributeName";
}


7.jsp页面post以及ajax写法.test.jsp、

<!DOCTYPE>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!-- c标签库 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- jquery -->
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery-ui-1.10.1.custom.min.js"></script>
<head>
<!-- 修改head显示的图片,自定义的哟 -->
<link rel="shortcut icon" href="<%=request.getContextPath()%>/ico/2.ico">
<link href="<%=request.getContextPath()%>/css/smoothness/jquery-ui-1.10.1.custom.css" rel="stylesheet">
<title>maven-mvc-bo</title>
</head>
<body>

<form id="form1" method="post">
<h2>前台获取值的方式:</h2>
<h2>${testBean.id}</h2>
<table>
<tr>
<td>id</td>
<td><input id="id" value="${testBean.id==null?100:testBean.id}" name="id" /></td>
</tr>
<tr>
<td>name</td>
<td><input id="name" value="${testBean.name==null?'tianxiawudi':testBean.name}" name="name" /></td>
</tr>

<tr>
<td><input type="button" id="post" value="post-test" /></td>
<td><input type="button" id="ajax" value="ajax-test" /></td>
</tr>
</table>
</form>
</body>

<script type="text/javascript" language="javascript">
//页面加载后执行的js
$(document).ready(function() {
//绑定事件
$("#ajax").click(function() {
ajax();
});
//绑定事件
$("#post").click(function() {
post();
});
});

function post() {
$("#form1").attr('action', '/bo/testPost.do')
$("#form1").submit();
}

function ajax() {
//这个拼接容易出错
var para = '{"name":"' + $('#name').val() + '","id":"' + $('#id').val()
+ '"}';
$.ajax({
type : 'POST',
//默认值: "application/x-www-form-urlencoded"。发送信息至服务器时内容编码类型。
contentType : 'application/json',
url : '/bo/testAjax.do',
//默认值: true。默认情况下,通过data选项传递进来的数据
processData : false,
//默认值: true。默认设置下,所有请求均为异步请求。
async : false,
dataType : 'json',
//发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式
data : para,
//默认值: true,dataType 为 script 和 jsonp 时默认为 false。设置为 false 将不缓存此页面。
cache : false,
success : function(data) {
$("#id").val(data.id);
$("#name").val(data.name)
},
error : function(XMLHttpRequest, error, errorThrown) {
alert('Err...' + error + errorThrown);
}
});
}
</script>
</html>


 

7.启动工程,输入http://localhost:8080/bo

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  SpringMVC