SpringMVC的五种常见表单页面模板,controller及响应页面相关实现
1.登陆表单
- 页面效果
- jsp 页面实现
<%--
Created by IntelliJ IDEA.
User: 云梦归遥
Date: 2022/4/28
Time: 17:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<h1 style="color: #050a7a;text-align: center">云梦归遥的SpringMVC复习之旅</h1>
<div id="basicContent" style="display: block">
<div style="width: 300px;background-color: pink">
<form action="${pageContext.request.contextPath}/form/simpleLogin" method="post">
登陆表单:
<br>
<label>username:
<input type="text" name="username">
</label><br>
<label>password:
<input type="password" name="password">
</label><br>
<input type="reset" value="reset" style="float: left;background-color: aquamarine">
<input type="submit" value="login" style="float: right;background-color: aqua">
</form>
</div>
- 对应的后端 controller
特色之处在于在登陆的时候还增加了身份验证与状态管理,本处使用的是 cookie 和 session共同操作,来进行校验
/**
* @author 云梦归遥
* @date 2022/4/28 19:52
* @description
*/
@Controller
@RequestMapping("/form")
public class FormController {
// 前端登录
@RequestMapping("/simpleLogin")
public String simpleLogin(@RequestHeader("cookie") String cookie, @CookieValue("JSESSIONID") String JSESSIONID, String username, String password, Model model, HttpServletRequest request, HttpServletResponse response){
System.out.println("cookie: " + cookie);
System.out.println("JSESSIONID: " + JSESSIONID);
System.out.println("username: " + username + ", password: " + password);
// 为了实验 拦截器的功能,在登陆之后在 session 中添加用户校验字段,在 cookie中添加校验字段
HttpSession session = request.getSession();
String uuidForUser = UUID.randomUUID().toString();
session.setAttribute(username + "-auth", uuidForUser); // 向 session 中对应用户名设置 UUID 字符串
// 响应内容添加新的 cookie 字段
Cookie cookieForUser = new Cookie(username + "-auth", uuidForUser);
cookieForUser.setMaxAge(86400); // 如果身份校验通过,一天内免登陆
response.addCookie(cookieForUser);
System.out.println("新添加的 cookie ===> " + username + "-auth" + ": " + uuidForUser);
model.addAttribute("username", username);
model.addAttribute("password", password);
return "forward:/page/simpleLoginResult.jsp";
}
}
- 如果登陆成功会跳转到对应的信息页面
<%--
Created by IntelliJ IDEA.
User: 云梦归遥
Date: 2022/4/28
Time: 20:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>returnResult</title>
</head>
<body>
<p style="color: chartreuse"><input type="button" value="< 返回" onclick="backLastPage()"></p>
<div style="color: green;">
<p style="color: red">获取登录信息:</p>
<p>username:${username}</p>
<p>password:${password}</p>
</div>
</body>
<script>
function backLastPage() {
history.go(-1);
}
</script>
</html>
-
启动项目,使用 maven进行项目管理,运行的容器是 tomcat
-
浏览器进行登录测试
-
响应的信息页面
-
登陆成功之后,查看浏览器的 cookie信息
2.问卷调查表单(个人信息表单)
- 页面效果
- jsp 页面实现
<div style="width: 300px;background-color: aquamarine">
<form action="${pageContext.request.contextPath}/form/questionnaireSurvey" method="post">
问卷调查:
<br>
<label>gender:
<input type="radio" name="gender" value="man">man
<input type="radio" name="gender" value="women">women
</label><br>
<label>skill:
<input type="checkbox" name="skill" value="Java">Java
<input type="checkbox" name="skill" value="Python">Python
<input type="checkbox" name="skill" value="Linux">Linux
</label><br>
<input type="reset" value="reset" style="float: left;background-color: aquamarine">
<input type="submit" value="submit" style="float: right;background-color: aqua">
</form>
</div>
- 对应的后端 controller
// 问卷调查
@RequestMapping("/questionnaireSurvey")
public ModelAndView questionnaireSurvey(@RequestParam("gender") String gender, @RequestParam("skill") String[] skill) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("gender", gender);
modelAndView.addObject("skill", Arrays.toString(skill));
// 编写逻辑视图名即可
modelAndView.setViewName("questionnaireSurveyResult");
return modelAndView;
}
- submit 提交之后跳转到对应的问卷调查信息页面
<%--
Created by IntelliJ IDEA.
User: 云梦归遥
Date: 2022/4/28
Time: 20:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>returnResult</title>
</head>
<body>
<p style="color: chartreuse"><input type="button" value="< 返回" onclick="backLastPage()"></p>
<div style="color: green;">
<p style="color: red">获取问卷调查:</p>
<p>gender:${gender}</p>
<p>skill:${skill}</p>
</div>
</body>
<script>
function backLastPage() {
history.go(-1);
}
</script>
</html>
-
浏览器进行问卷调查填写
-
响应的信息页面
3.日期格式转换
- 前端页面的 input 类型为 date 时,我们后端想要转化为 Java 的 Date 类型对象
<div style="width: 300px;background-color: aliceblue">
<form action="${pageContext.request.contextPath}/form/dateConverter" method="post">
时间转换表单:
<br>
<label>time:
<input type="date" name="date">
</label><br>
<input type="reset" value="reset" style="float: left;background-color: aquamarine">
<input type="submit" value="convert" style="float: right;background-color: aqua">
</form>
</div>
- 后端 controller 实现
// 时间格式转换
@RequestMapping("/dateConverter")
public String dateConverter(@RequestHeader("cookie") String cookie, String date, Model model){
System.out.println("cookie: " + cookie);
System.out.println("date: " + date);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date newDate = simpleDateFormat.parse(date);
System.out.println(newDate);
model.addAttribute("oldDate", date);
model.addAttribute("newDate", newDate);
} catch (ParseException e) {
e.printStackTrace();
}
return "forward:/page/dateConverterResult.jsp";
}
- 日期转换之后跳转的信息页面
<%--
Created by IntelliJ IDEA.
User: 云梦归遥
Date: 2022/4/28
Time: 20:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>returnResult</title>
</head>
<body>
<p style="color: chartreuse"><input type="button" value="< 返回" onclick="backLastPage()"></p>
<div style="color: green;">
<p style="color: red">获取时间格式:</p>
<p>原时间内容:${oldDate}</p>
<p>更新时间内容:${newDate}</p>
</div>
</body>
<script>
function backLastPage() {
history.go(-1);
}
</script>
</html>
-
浏览器进行时间的选择
-
响应的信息页面
4.Ajax 异步提交数据
- Ajax 异步提交表单是前端很多时候要用到的一个技术
div id="strengthContent" style="display: block">
<div style="width: 300px;background-color: aliceblue">
<div>
<p>进行ajax异步提交:</p>
<input id="btn1" type="button" value="ajax-submit" style="float: right;background-color: aqua">
</div>
<p id="text1" style="color: chartreuse"></p>
</div>
</div>
<script src="${pageContext.request.contextPath}/js/jquery-3.6.0.js"></script>
<script>
$("#btn1").click(function () {
let url = '${pageContext.request.contextPath}/form/ajaxReturnResult';
let data = '[{"id": 1, "username": "Mike"}, {"id": 2, "username": "Jack"}]';
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: 'application/json;charset=utf-8',
success: function (res) {
console.log(res);
$("#text1").text(res);
},
error: function (error) {
console.log(error);
}
})
});
</script>
- 后端进行处理 Ajax 的异步请求,获取到对应的请求数据,以及响应对应的数据
// 测试 ajax 异步请求
@RequestMapping("ajaxReturnResult")
@ResponseBody
public String ajaxReturnResult(@RequestBody List<User> userList){
System.out.println(userList);
return userList.toString();
}
-
浏览器进行异步提交 Ajax 请求
-
提交之后的效果
5.文件上传与个人信息上传表单,同时文件保存到服务器端
- 当我们有表单既要提交个人信息,还要提交文件还要将文件保存到服务器端时该怎么处理呢?
<div style="width: 300px;background-color: darkcyan">
<form action="${pageContext.request.contextPath}/form/fileUpload" method="post" enctype="multipart/form-data">
<label>username:
<input type="text" name="username" style="width: 150px">
</label><br>
img:
<input type="file" name="filename"><br>
<input type="reset" value="reset" style="float: left;background-color: aquamarine">
<input type="submit" value="submit" style="float: right;background-color: aqua">
</form>
</div>
- 后端的 controller 实现逻辑
// 文件上传
@RequestMapping("fileUpload")
public ModelAndView fileUpload(@RequestParam("username") String username, @RequestParam("filename") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
System.out.println("username: " + username);
String filename = multipartFile.getOriginalFilename();
String newFileName = System.currentTimeMillis() + "_" + filename;
String path = request.getSession().getServletContext().getRealPath("/");
// \\ 其实是一个 \,否则不符合正则语法
path = path.replaceAll("\\\\", "/");
// 真正的tomcat服务器 img 文件上传的位置
String imgUploadPath = path + "img/" + newFileName; // 时间戳 + 文件名(防止同名文件覆盖)
multipartFile.transferTo(new File(imgUploadPath)); // 直接拷贝上传(上传到了tomcat中项目部署的位置)
System.out.println(imgUploadPath);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("newImg", newFileName);
modelAndView.setViewName("fileUploadResult");
return modelAndView;
}
- 文件上传成功之后的相应信息页面(会显示图片的名字,以及展示图片)
<%--
Created by IntelliJ IDEA.
User: 云梦归遥
Date: 2022/4/29
Time: 18:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>fileUpload</title>
</head>
<body>
<p style="color: chartreuse"><input type="button" value="< 返回" onclick="backLastPage()"></p>
<div style="color: green;">
<p style="color: red">上传图片名称: ${newImg}</p>
<img src="${pageContext.request.contextPath}/img/${newImg}" style="width: 300px;height: 300px" title="图片展示" alt="图片加载失败">
</div>
</body>
<script>
function backLastPage() {
history.go(-1);
}
</script>
</html>
-
浏览器进行表单的提交
-
提交之后的信息页面
-
查看 tomcat 服务器上是否有我们上传的图片