前段时间学习了springmvc的使用,用得不是很熟,这几天又使用了一下,感觉还是写篇日记记录一下,以免生疏。
第一步:新建工程,我的目录大概如下,然后导入相关的包(暂没用maven,最好使用maven吧,找包很累);
第二步:编辑web.xml文件。如下;
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>DemoSmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!--配置Sring MVC的核心控制器DispatcherServlet -->
<!-- 这样配置把所有.do的请求转发到DispatcherServlet控制中心,DispatcherServlet会默认加载 wib-inf
下的 dispatcherServlet-servlet.xml,根据里面的配置再到相应的controller -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 修改了加载xml的位置 -->
<param-value>classpath:spring-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!--为DispatcherServlet建立映射 -->
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
第三步:编辑spring-servlet.xml文件,这个比较重要(需要多查查资料理解面的各种配置意思);
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
">
<!--use-default-filters="false 把标记了@Controller,Service,Repository,Component注解的类转换为bean
use-default-filters="true" 才会扫描包下的所有路径, false不会,只扫描指定的类include-filter指定的类,包含相关注解的类 -->
<mvc:annotation-driven />
<context:component-scan base-package="com.complaints"
use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller"
type="annotation" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Service" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Component" />
</context:component-scan>
<!--配置视图 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
第四步:去包下面写类吧。
1.主要action类:
package com.complaints.action;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.complaints.pojo.User;
import com.complaints.service.TestService;
import com.complaints.service.TestServiceInte;
@Controller
public class AuthorAction {
// 跳转页面
@RequestMapping("/login")
public String loginView() {
System.out.println("oh shit!");
return "login";
}
// 通过ModelAndView跳转并附带数据到页面
@RequestMapping(value = "/index1", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView modelAndView = new ModelAndView("index");
modelAndView.addObject("name", "yinqianhui");
return modelAndView;
}
// 通过Map将数据带到页面
@RequestMapping(value = "/index2", method = RequestMethod.GET)
public String index2(Map<String, Object> map) {
map.put("name", "lei tow");
return "index";
}
// 通过Model将数据带到相应页面
@RequestMapping(value = "/index3", method = RequestMethod.GET)
public String index3(Model model) {
model.addAttribute("name", "bear tow");
return "index";
}
// 通过配合@ResponseBody 以json数据返回(适合做即时校验);记得添加jackson-core-lgpl-1.8.5.jar
// 和jackson-mapper-lgpl-1.8.5.jar
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public Map test() {
System.out.println("test");
Map map = new HashMap();
map.put("name", "yinzai");
return map;
}
// ajax post 返回对象
@RequestMapping(value = "/test3", method = RequestMethod.POST)
@ResponseBody
public Map test3() {
System.out.println("test3");
Map map = new HashMap();
map.put("name", "XXOO");
return map;
}
@RequestMapping(value = "/test4", method = RequestMethod.POST)
@ResponseBody
public Map test4(@RequestBody User user) {
System.out.println("test4");
System.out.println("user:" + user.getUserName() + "=="
+ user.getUserPwd());
Map map = new HashMap();
map.put("name", "参数已经传到");
return map;
}
// 接受参数以Pojo形式
@RequestMapping(value = "/showUser", method = RequestMethod.POST)
public String showUser(@ModelAttribute(" pojo ") User user, Model model) {
System.out.println(user.getUserName() + "==" + user.getUserPwd());
model.addAttribute("user", user);
return "index";
}
// request获取参数
@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response,
Model model) {
System.out.println(request.getParameter("userName") + "=="
+ request.getParameter("userPwd"));
User user = new User();
user.setUserName(request.getParameter("userName"));
user.setUserPwd(request.getParameter("userPwd"));
model.addAttribute("user", user);
return "index";
}
/*
* 用注解@RequestParam绑定请求参数a到变量a 当请求参数a不存在时会有异常发生,可以通过设置属性required=false解决,
* 例如: @RequestParam(value="userName", required=false)
*/
@RequestMapping(value = " /requestParam ", method = RequestMethod.GET)
public String setupForm(@RequestParam("userName") String userName,
@RequestParam("userPwd") String userPwd, Model model) {
System.out.println(userName + "==" + userPwd);
User user = new User();
user.setUserName(userName);
user.setUserPwd(userPwd);
model.addAttribute("user", user);
return "index";
}
// redirect:/index "forward:/hello
/* 测试@Autowired 和 @Resource */
// @Qualifier("testService")
// @Resource
@Autowired(required = true)
private TestServiceInte testService;
// test auto 测试自动注入功能
@RequestMapping("/login2")
public String loginView2() {
System.out.println("oh shit!");
testService.test();
return "login";
}
// 测试用Map 来接收ajax传过来的json数据;
// data:JSON.stringify({userName:"yiner",userPwd:"123456"}),
@RequestMapping(value = "test8", method = RequestMethod.POST)
@ResponseBody
public Map test8(@RequestBody Map maps) {
System.out.println("tes8");
System.out.println("name=====" + maps.get("userName"));
Map map = new HashMap();
map.put("name", "test8");
return map;
}
// 用字符创变量接收ajax传过来的json数据;data:{userName:"yiner"},
@RequestMapping(value = "test9", method = RequestMethod.GET)
@ResponseBody
public Map test9(HttpServletRequest request,
@RequestParam("userName") String userName) {
System.out.println("tes9");
System.out.println("name=====" + userName);
Map map = new HashMap();
map.put("name", "test9");
return map;
}
// 用字符创变量接收ajax传过来的 ;data:'userName=yiner',
@RequestMapping(value = "test10", method = RequestMethod.POST)
@ResponseBody
public Map test10(HttpServletRequest request,
@RequestParam("userName") String userName) {
System.out.println("tes10");
System.out.println("name=====" + request.getParameter("userName"));
System.out.println("name22===" + userName);
Map map = new HashMap();
map.put("name", "test10");
return map;
}
}
2.一个普通bean,这里是User:
package com.complaints.pojo;
public class User {
private String userName;
private String userPwd;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
}
3.再写个service类(接口就没写出了),测试一下自动注入:
package com.complaints.service;
import org.springframework.stereotype.Service;
@Service("testService")
public class TestService implements TestServiceInte{
public void test() {
System.out.println("This is TestService!!!");
}
}
第五步:骚年,可以写个测试页面看看效果了!
test1.html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
function test() {
$.get("test.do", {
Action : "get"
//传递的参数
}, function(data) {
// data 可以是 xmlDoc, jsonObj, html, text, 等等.
alert(data.name);
//$("#roleName").val(member.yin);//获取map里面的数据
//从list里面获取map,在获取map里面的数据
}, "json");
}
function test4() {
jQuery.ajax({
type : 'POST',
contentType : 'application/json;charset=UTF-8',
url : 'test4.do',
dataType : 'json',
data : JSON.stringify({
userName : "yiner",
userPwd : "123456"
}),
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
function test3() {
$.post("test3.do", {
Action : "post"
//传递的参数
}, function(data) {
// data 可以是 xmlDoc, jsonObj, html, text, 等等.
alert(data.name);
//$("#roleName").val(member.yin);//获取map里面的数据
//从list里面获取map,在获取map里面的数据
}, "json");
}
function test8() {
jQuery.ajax({
type : 'POST',
contentType : 'application/json;charset=UTF-8',
url : 'test8.do',
dataType : 'json',
data : JSON.stringify({
userName : "yiner",
userPwd : "123456"
}),
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
//传输json对象
function test9() {
jQuery.ajax({
type : 'GET',
contentType : 'application/json;charset=UTF-8',
url : 'test9.do',
dataType : 'json',
data : {
userName : "yiner"
},
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
//传输字符对象
function test10() {
jQuery.ajax({
type : 'post',
url : 'test10.do',
dataType : 'json',
data : 'userName=yiner',
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
</script>
</head>
<body>
<a href="login.do">页面跳转到login.jsp</a>
<br>
<a href="index1.do">go index</a>
<br>
<a href="index2.do">index2</a>
<br>
<a href="index3.do">index3</a>
<br>
<a href="login2.do">login2.do测试Autowired</a>
<br>
<a href="#" οnclick="test()">AJAX</a>
<br>
<a href="test.do">test 返回json数据</a>
<br>
<a href="#" οnclick="test3()">POST-AJAX(ajax post方式发送与接收数据)</a>
<br>
<a href="#" οnclick="test4()">GET-AJAX json传参数</a>
<br>
<a href="#" οnclick="test8()">test8<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
function test() {
$.get("test.do", {
Action : "get"
//传递的参数
}, function(data) {
// data 可以是 xmlDoc, jsonObj, html, text, 等等.
alert(data.name);
//$("#roleName").val(member.yin);//获取map里面的数据
//从list里面获取map,在获取map里面的数据
}, "json");
}
function test4() {
jQuery.ajax({
type : 'POST',
contentType : 'application/json;charset=UTF-8',
url : 'test4.do',
dataType : 'json',
data : JSON.stringify({
userName : "yiner",
userPwd : "123456"
}),
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
function test3() {
$.post("test3.do", {
Action : "post"
//传递的参数
}, function(data) {
// data 可以是 xmlDoc, jsonObj, html, text, 等等.
alert(data.name);
//$("#roleName").val(member.yin);//获取map里面的数据
//从list里面获取map,在获取map里面的数据
}, "json");
}
function test8() {
jQuery.ajax({
type : 'POST',
contentType : 'application/json;charset=UTF-8',
url : 'test8.do',
dataType : 'json',
data : JSON.stringify({
userName : "yiner",
userPwd : "123456"
}),
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
//传输json对象
function test9() {
jQuery.ajax({
type : 'GET',
contentType : 'application/json;charset=UTF-8',
url : 'test9.do',
dataType : 'json',
data : {
userName : "yiner"
},
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
//传输字符对象
function test10() {
jQuery.ajax({
type : 'post',
url : 'test10.do',
dataType : 'json',
data : 'userName=yiner',
success : function(data) {
alert(data.name);
},
error : function() {
alert("error");
}
});
}
</script>
</head>
<body>
<a href="login.do">页面跳转到login.jsp</a>
<br>
<a href="index1.do">go index 通过ModelAndView跳转并附带数据到页面</a>
<br>
<a href="index2.do">index2 通过Map将数据带到页面</a>
<br>
<a href="index3.do">index3 通过Model将数据带到相应页面</a>
<br>
<a href="login2.do">login2.do测试Autowired</a>
<br>
<a href="#" οnclick="test()">AJAX 接收数据</a>
<br>
<a href="test.do">test 后台返回json数据</a>
<br>
<a href="#" οnclick="test3()">POST-AJAX</a>
<br>
<a href="#" οnclick="test4()">GET-AJAX json传参数</a>
<br>
<a href="#" οnclick="test8()">test8 测试用Map 来接收ajax传过来的json数据</a>
<br>
<a href="#" οnclick="test9()">test9 用字符创变量接收ajax传过来的json数据</a>
<br>
<a href="#" οnclick="test10()">test10 用字符创变量接收ajax传过来的 </a>
<br>
</body>
</body>
</html>
还有个配合测试的页面(主要是表单数据提交例子):
login.jsp
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Insert title here</title>
</head>
<body>
<f:view>
1.pojo形式提交参数
<form method="post" action="showUser.do">
name: <input id="a" type="text" name="userName" /> pwd: <input id="b"
type="password" name="userPwd" /> <input type="submit"
value="Submit" />
</form>
</f:view>
<br></br> 2.普通方式提交,通过request方式接受
<form method="get" action="get.do">
name: <input id="a" type="text" name="userName" /> pwd: <input id="b"
type="password" name="userPwd" /> <input type="submit" value="Submit" />
</form>
<br></br> 3.与参数绑定的方式
<form method="get" action="requestParam.do">
name: <input id="a" type="text" name="userName" /> pwd: <input id="b"
type="password" name="userPwd" /> <input type="submit" value="Submit" />
</form>
</body>
</html>
第六步:将其添加到tomcat启动应该就大功告成了!点击相应的链接可以测试不同的后台业务,刚刚浏览器崩溃了,差点要重写,还好博客还有自动保存。
因时间问题,本文没有详细分析里面的内容,等下次再细分吧.今天就只搭个测试环境玩玩了!
下载链接(比较旧了的,但能用!):http://download.csdn.net/detail/yinqianhui1990/9073409