一、前后端数据交互
1、前台数据传输到后端
创建一个表单
<form action="/login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username" id="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td><input type="submit" value="提交"></td>
</tr>
</table>
</form>
后台获取前端的值有三种方式:
①、直接使用HttpServletRequest 作为参数,然后调用request的getParameter方法
@RequestMapping(value = "/login",method = RequestMethod.POST)
public void login(HttpServletRequest request) throws UnsupportedEncodingException {
System.out.println(request.getParameter("username") + " " + request.getParameter("password"));
}
②、使用@RequestParam注解
@RequestMapping(value = "/login",method = RequestMethod.POST)
public void login(@RequestParam(value = "username") String name, @RequestParam(value = "password") String pwd) throws UnsupportedEncodingException {
System.out.println(name + " " + pwd);
}
③、使用Javabean
首先创建一个User类,然后传值,注意User类的属性
@RequestMapping(value = "/login",method = RequestMethod.POST)
public void login(User user) throws UnsupportedEncodingException {
System.out.println(user.getUsername() + " " +user.getPassword());
}
2、后端数据传递到前台
后端数据传递到前台可以使用ModelAndView进行操作,然后再Jsp页面中使用EL表达式就可以获取到。
@RequestMapping(value = "/login",method = RequestMethod.POST)
public ModelAndView login() throws UnsupportedEncodingException {
ModelAndView modelAndView = new ModelAndView("success");
modelAndView.addObject("username","张三");
return modelAndView;
}
二、SpringMVC中使用Ajax
其实在SpringMVC中使用Ajax和在其他地方使用Ajax时,Ajax都是大致相同的,不同的是后端处理方式。以一个简单的登录例子进行说明:
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery+ajax实现登录</title>
<script type="text/javascript" src="jquery/jquery-3.2.1.js"></script>
<script type="text/javascript">
function check(id1,id2) {
if(document.getElementById(id1).value == null || document.getElementById(id1).value.trim(" ") == "")
document.getElementById(id2).innerHTML = id1 + '不能为空';
else
document.getElementById(id2).innerHTML ='';
}
$(function(){
$("#loginBtn").click(function(){
var username = $.trim($("#username").val());//取值
var password = $.trim($("#password").val());
var param = {"username":username,"password":password};
// alert(param);
$.post("/login",param,function(result){
if(result){
$("#id").html(result);
// window.location.href="/success.jsp";
}else{
alert("用户名或者密码错误!");
}
});
});
});
</script>
</head>
<body>
<form>
用户名:<input type="text" id="username" name="username" onblur="check('username','usernamespan')"><span id="usernamespan"></span><br/>
密码:<input type="text" id="password" name="password" onblur="check('password','passwordspan')"><span id="passwordspan"></span><br/>
<span id="id"></span><br>
<input type="button" value="登录" id="loginBtn">
</form>
</body>
</html>
后端代码:
@Controller
public class LoginController {
@RequestMapping(value = "/login")
@ResponseBody
public boolean login(String username,String password){
boolean flag = "admin".equals(username)&&"123456".equals(password) ? true : false;
System.out.println(flag);
return flag;
}
}
上述例子已测试过,可以使用。
Ajax还可以这样写:下面仅有JS代码,其余不变即可
<script type="text/javascript">
function check(id1,id2) {
if(document.getElementById(id1).value == null || document.getElementById(id1).value.trim(" ") == "")
document.getElementById(id2).innerHTML = id1 + '不能为空';
else
document.getElementById(id2).innerHTML ='';
}
$(function(){
$("#loginBtn").click(function(){
var username = $("#username").val();//取值
var password = $("#password").val();
if(!username || !password){
return ;
}
$.ajax({
type:"POST",
url:"/login",
data:{"username":username,"password":password},
dataType:"json",
timeout:1000,
error:function(){ //请求失败的回调方法
$("#id").css("color","red");
$("#id").html("报错");
},
success:function(result){
$("#id").css("color","red");
$("#id").html("Ajax使用成功,登录情况:" +result);
}
})
});
});
</script>
结果
三、SpringMVC文件上传
上传文件有三种方式:
1、使用采用multipart提供的file.transfer方法上传文件上传,将文件保存到服务器的webapps下自定义的文件夹中
upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
</body>
</html>
SpringMVCUpload
@Controller
public class SpringMVCUpload {
@RequestMapping(value = "/upload")
public String uploadTest(HttpServletRequest request, @RequestParam(value = "file") MultipartFile file) throws IOException {
if(file.isEmpty())
return null;
String fileName = file.getOriginalFilename();
System.out.println(fileName);
File file1 = new File(request.getServletContext().getRealPath("/"));
String path = file1.getParent() + "/static/upload/"; //保存在服务器中
System.out.println(path);
File file2 = new File(path,fileName);
file.transferTo(file2);
return "success2";
}
}
2、使用流的方式将文件保存在硬盘的指定地方:
后台处理方式
@RequestMapping("/fileUpload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
System.out.println("fileName:"+file.getOriginalFilename());
try {
//获取输出流
OutputStream os = new FileOutputStream("F:/upload/"+ new Date().getTime() + file.getOriginalFilename());
//获取输入流 CommonsMultipartFile 中可以直接得到文件的流
InputStream is=file.getInputStream();
int temp;
//一个一个字节的读取并写入
while((temp=is.read())!=(-1))
{
os.write(temp);
}
os.flush();
os.close();
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long endTime=System.currentTimeMillis();
return "success2";
}
3、采用spring提供的上传文件的方法
@RequestMapping("/springUpload")
public String springUpload(HttpServletRequest request) throws IllegalStateException, IOException
{
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
while(iter.hasNext())
{
//一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String path = "F:/upload/"+file.getOriginalFilename();
//上传
file.transferTo(new File(path));
}
}
}
return "success2";
}