spring简单MVC实现方法(URL映射及其参数使用、查询(id、其他参数)、增加)
作者:怎么肥四嘞
一、方法参数使用
1.在无注解下获取参数
在没有注解的情况下,Spring MVC 也可以获取参数,且参数允许为空,唯一的要求是参
数名称和 HTTP 请求的参数名称保持一致。
@Controller @RequestMapping("/my") public class MyController{ @GetMapping("/no/annotation") @ResponseBody public Map<String,Object> noAnnotation(Integer intVal,Long longVal,String str){ Map<String,Object> map = new HashMap(); map.put("intVal",intVal); map.put("longVal",longVal); map.put("str",str); return map; }}
2. 使用@RequestParam 获取参数
在方法参数中使用了注解@RequestParam,其目的是指定 HTTP 参数和方法的映射关系,这样处理器会按照其配置的映射关系来得到参数,然后调用控制器的方法。
注意:如果把 3 个 HTTP 参数中的任意一个删去,就会得到异常报错的信息。
@RequestMapping("annotation") @ResponseBody public Map<String,Object> requestParam(@RequestParam("int_Val") Integer intVal,@RequestParam("long_Val") Long longVal,@RequestParam("str_Val") String str){ Map<String,Object> map = new HashMap(); map.put("intVal",intVal); map.put("longVal",lngVal); map.put("str",str); return map; }
3.传递数组
@RequestMapping("/requestArray") @ResponseBody public Map<String, Object> requestArray(Integer [] intArr, Long [] longArr, String [] strArr) { Map<String, Object> paramsMap = new HashMap(); paramsMap.put("intArr", intArr); paramsMap.put("longArr", longArr); paramsMap.put("strArr", strArr); return paramsMap; }
4.格式化获取参数
/WEB-INF/jsp/format/formatter.jsp
<%@ page pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>格式化</title> </head> <body> <form action="./commit" method="post"> <table> <tr> <td>日期(yyyy-MM-dd)</td> <td><input type="text" name="date" value="2017-08-08" /></td> </tr> <tr> <td>金额(#,###.##)</td> <td><input type="text" name="number" value="1,234,567.89" /></td> </tr> <tr> <td colspan="2" align="right"><input type="submit" value=" 提交" /> </td> </tr> </table> </form> </body> </html>
controller.java
@PostMapping("/format/commit") @ResponseBody public Map<String, Object> format( @DateTimeFormat(iso=ISO.DATE) Date date, @NumberFormat(pattern="#,###.###") Double number ){ Map<String, Object> dataMap=new HashMap(); dataMap.put("date", date); dataMap.put("number", number); return dataMap; }
二、MVC的增、查
1.pom.xml
加入parent、web、jstl、servlet、tomcat、jasper坐标(可以参考我之前写过的pom.xml)
这次再写入热部署:当项目启动状态时,修改静态文件并保存后,不需要重启项目来达到使静态文件生效的目的。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency>
2.jsp
这次需要用到js和easyui框架(见文章末尾源码),我们就可以在此基础上添加jsp,展现更漂亮的前端
src/main/webapp/WEB-INF/jsp/user/XXX.jsp
add.jsp
<%@ page pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>新增用户</title> <!-- 加载Query文件--> <script type="text/javascript" src="/js/jquery-3.2.1.js"> </script> <script type="text/javascript"> $(document).ready(function(){ $("#submit").click(function() { var id=$("#id").val(); var userName=$("#userName").val(); var note=$("#note").val(); if ($.trim(userName)=='') { alert("用户名不能为空!"); return; } var params = { id:id, userName:userName, note:note }; $.post({ url:"./insert", // 此处需要告知传递参数类型为JSON,不能缺少 contentType:"application/json", // 将JSON转化为字符串传递 data:JSON.stringify(params), // 成功后的方法 success:function(result){ if(result==null||result.id==null) { alert("插入失败"); return; } alert("插入成功"+result.userName+">>"+result.note); window.location.href="./details1" rel="external nofollow" ; } }); }); }); </script> </head> <body> <div style="margin: 20px 0;"></div> <form id="insertForm"> <table> <tr> <td>id编号:</td> <td><input id="id" name="id"></td> </tr> <tr> <td>用户名称:</td> <td><input id="userName" name="userName"></td> </tr> <tr> <td>备注</td> <td><input id="note" name="note"></td> </tr> <tr> <td></td> <td align="right"><input id="submit" type="button" value="提交" /></td> </tr> </table> </form> </body>
details1.jsp
<%@ page pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>用户详情</title> </head> <body> <div align="center"> <table border="1"> <tr> <td>用户编号</td> <td>用户姓名</td> <td>备注信息</td> </tr> <c:forEach items="${users1}" var="user"> <tr> <td><c:out value="${user.id}"/></td> <td><c:out value="${user.userName}"/></td> <td><c:out value="${user.note}"/></td> </tr> </c:forEach> </table> </div> </body> </html>
details.jsp
<%@ page pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <head> <title>用户详情</title> </head> <body> <div align="center"> <table border="1"> <tr> <td>标签</td> <td>值</td> </tr> <tr> <td>用户编号</td> <td><c:out value="${user.id}"></c:out></td> </tr> <tr> <td>用户名称</td> <td><c:out value="${user.userName}"></c:out></td> </tr> <tr> <td>用户备注</td> <td><c:out value="${user.note}"></c:out></td> </tr> </table> </div> </body> </html>
table.jsp
<%@ page pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用户列表</title> <link rel="stylesheet" type="text/css" href="../../easyui/themes/default/easyui.css" rel="external nofollow" > <link rel="stylesheet" type="text/css" href="../../easyui/themes/icon.css" rel="external nofollow" > <link rel="stylesheet" type="text/css" href="../../easyui/demo/demo.css" rel="external nofollow" > <script type="text/javascript" src="../../easyui/jquery.min.js"></script> <script type="text/javascript" src="../../easyui/jquery.easyui.min.js"></script> <script type="text/javascript"> // 定义事件方法 function onSearch() { // 指定请求路径 var opts = $("#dg").datagrid("options"); opts.url = "./list3"; // 获取查询参数 var userName = $("#userName").val(); var note = $("#note").val(); // 组织参数 var params = {}; if (userName != null && userName.trim() != '') { params.userName = userName; } if (note != null && note.trim() != '') { params.note = note; } // 重新载入表格数据 $("#dg").datagrid('load', params); } </script> </head> <body> <div style="margin: 20px 0;"></div> <div class="easyui-layout" style="width: 100%; height: 350px;"> <div data-options="region:'north'" style="height: 50px"> <form id="searchForm" method="post"> <table> <tr> <td>用户名称:</td> <td><input id="userName" name="userName" class="easyui-textbox" data-options="prompt:'输入用户名称...'" style="width: 100%; height: 32px"></td> <td>备注</td> <td><input id="note" name="note" class="easyui-textbox" data-options="prompt:'输入备注...'" style="width: 100%; height: 32px"> </td> <td><a href="#" rel="external nofollow" class="easyui-linkbutton" data-options="iconCls:'icon-search'" style="width: 80px" onclick="onSearch()">查询</a></td> </tr> </table> </form> </div> <div data-options="region:'center',title:'用户列表',iconCls:'icon-ok'"> <table id="dg" class="easyui-datagrid" data-options="border:false,singleSelect:true, fit:true,fitColumns:true"> <thead> <tr> <th data-options="field:'id'" width="80">编号</th> <th data-options="field:'userName'" width="100">用户名称</th> <th data-options="field:'note'" width="80">备注</th> </tr> </thead> <tbody> <!--使用forEache渲染数据模型--> <c:forEach items="${userList}" var="user"> <tr> <td>${user.id}</td> <td>${user.userName}</td> <td>${user.note}</td> </tr> </c:forEach> </tbody> </table> </div> </div> </body>
3.实体pojo类
public class User { private Integer id; private String userName; private String note; get、set方法 }
4.Dao层
IUserDao.java
public interface IUserDao { public User getUserById(Integer id);//通过id查找 public User getUserByName(String uname);//通过用户名查找 public Boolean insertUser(User user);//增加用户 public List<User> findAllUser();//查找 public List<User> findUsers(String userName,String note);//通过用户名和备注查找 }
UserDaoImpl.java
@Repository public class UserDaoImpl implements IUserDao { public List<User> users=new ArrayList<User>(); public UserDaoImpl() { super(); users.add(new User(1,"user_name_1","note1")); users.add(new User(2,"user_name_2","note2")); users.add(new User(3,"user_name_3","note3")); } @Override public User getUserByName(String uname) { // TODO Auto-generated method stub System.out.println(uname); for(User user:users) { if(user.getUserName().equals(uname)) { return user; } } return null; } @Override public Boolean insertUser(User user) { // TODO Auto-generated method stub Boolean flag=false; System.out.println(user.getUserName()+">>"+user.getNote()); users.add(user); flag=true; return flag; } ...... }
5.service层
IUserService.java
public interface IUserService { public User getUserById(Integer id); public Boolean insertUser(User user); public List<User> findAllUser(); public List<User> findUsers(String userName,String note); }
UserServiceImpl.java
@Service public class UserServiceImpl implements IUserService { @Autowired private IUserDao userDao; @Override public User getUserById(Integer id) { // TODO Auto-generated method stub return userDao.getUserById(id); } @Override public List<User> findAllUser() { // TODO Auto-generated method stub return userDao.findAllUser(); } @Override public Boolean insertUser(User user) { Boolean flag=false; System.out.println(user.getUserName()+">>"+user.getNote()); flag=userDao.insertUser(user); return flag; } ...... }
6.UserController.java
@Controller @RequestMapping("user") public class UserController { @Autowired private IUserService userService; //1.按ID查询,显示结果JSON格式 @RequestMapping("/getUser1") @ResponseBody public User getUser(Integer id) { User user = userService.getUserById(id); return user; } //2.按ID查询,显示结果JSP @RequestMapping("getUser3") public ModelAndView getUser3(Integer id) { User user1 = userService.getUserById(id); ModelAndView mv = new ModelAndView(); mv.setViewName("user/details"); mv.addObject("user", user1); return mv; } /** * 3.新增用户,添加信息页面 */ @GetMapping("add") public String add() { return "/user/add"; } /** * 4. 新增用户 处理 * * @param user 通过@RequestBody注解得到JSON参数 * @return 返回添加的用户信息 */ @PostMapping("/insert") @ResponseBody public User insert(@RequestBody User user) { userService.insertUser(user); return user; } /* * 5. 查询多个用户数据 jsp显示 */ @RequestMapping("/details1") public ModelAndView findAllUsers() { List<User> users = new ArrayList<User>(); users = userService.findAllUser(); ModelAndView mv = new ModelAndView(); mv.setViewName("user/details1"); mv.addObject("users1", users); return mv; } /* * 6. 查询多个用户数据 JSON格式显示 */ @RequestMapping("/list") @ResponseBody public List<User> list() { List<User> users = new ArrayList<User>(); users = userService.findAllUser(); return users; //7. 通过URL传递参数,{ ...}表明参数的位置和名称。该例指定名称为id @RequestMapping("/{id}") // 响应为JSON数据集 @ResponseBody // @PathVariable 通过参数名称获取参数 public User getUser1(@PathVariable("id") Integer id) { return userService.getUserById(id); } /** 8. URL路径匹配:多个参数查询 * 注解 @PathVariable 用于从请求URL中获取参数并映射到方法参数中 * @param userName * @param note * @return */ @RequestMapping("/list1/{userName}/{note}") @ResponseBody public List<User> getUserByNameAndNote(@PathVariable("userName") String userName,@PathVariable("note") String note){ return userService.findUsers(userName, note); } /** 9.EasyUI框架 ——进入首页面,查询所有的用户 * @return table.jsp页面 */ @RequestMapping("table") public ModelAndView table() { List<User> users=userService.findAllUser(); ModelAndView mv = new ModelAndView(); mv.setViewName("/user/table"); mv.addObject("userList", users); return mv; } /** 10. EasyUI框架 ——按条件查询用户信息 * 注意@RequestParam(value="userName",required=false)的使用 * @param userName * @param note * @return */ @RequestMapping("list3") @ResponseBody public List<User> list3( @RequestParam(value="userName",required=false) String userName, @RequestParam(value="note",required=false) String note) { List<User> users=userService.findUsers(userName, note); return users; } }
7.App.java
略
8.src/main/resources/application.properties
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
9.成果展示
源码:http://xiazai.jb51.net/202401/yuanma/chapter_jb51.rar
到此这篇关于spring-简单MVC实现(URL映射及其参数使用、查询(id、其他参数)、增加)的文章就介绍到这了,更多相关spring MVC实现内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!