1.前言
最近在做一个项目,前台框架用的是EasyUI+SpringMVC,由于对SpringMVC不太了解,所以刚开始接触的时候有点吃力,在此通过一个EasyUi中的DataGrid表格来总结一下.
2.SpringMVC中的View向控制器传参
在SpringMVC中,View如何向控制器传参数呢?尤其是Form表单提交的时候,具体有如下几种方式
2.1 HttpServletRequest
可以通过getParameter()方法来获取前台传过来的参数
2.2 Form表单绑定
-
- public String queryPerson(person person){
- return "index";
- }
通过这样,就直接把前台参数封装成了person对象,这样就接收到了参数
2.3 随意参数设置
-
- public String queryPerson(String personId,String personName){
- return "index";
- }
通过在方法中设置参数,就可以在前台获取到传过来的参数,但要保证,参数名称要一致
3.SpringMVC中控制器向View视图传参数
3.1 Model传参数
-
- public String toPerson(Model model){
-
- model.addAttribute("p", "nihoama");
- return "index";
- }
才用这种方式,把参数封装到model中,然后在前台通过${key}值,就可以获取到控制器传过来的参数
3.2 map传参数
-
- protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
- HttpServletResponse arg1) throws Exception {
- System.out.println("hello springmvc");
- Map<String, String> map=new HashMap<String, String>();
- map.put("p", "nihaoma");
-
- return new ModelAndView("index",map);
- }
与model类似,把值放置到map中,然后在前台直接获取即可
3.3 PrintWriter对象输出内容
-
- public void outString(PrintWriter out){
- out.print("你好吗");
- }
通过PrintWriter对象,就可以直接把内容输出到页面上
3.4 @ResponseBody输出字符串
-
- @ResponseBody
- public String outString(){
- return "你好吗";
- }
如果在方法上放置此注解的话,那么返回的String值,就不在是视图,而将会是以流的形式返回字符串
4.SpringMVC异步提交表单
最近用到了异步提交表单的操作,下面展示一下
js操作
-
- function AddDictionaryType() {
-
- $('#AddDictionaryTypeForm').form('submit', {
- url : "addDictionaryType",
- onSubmit : function() {
- var isValid = $(this).form('validate');
- return isValid;
- },
- success : function(data) {
- if (data == "success") {
- $.messager.alert('提示', '添加成功!');
- $('#dg').datagrid('reload');
- $('#Addwin').window('close');
-
- } else {
- $.messager.alert('提示信息', '添加失败,请联系管理员!', 'warning');
- }
-
- }
- });
-
- }
异步调用的方法
-
-
-
-
-
-
-
-
-
- @RequestMapping("/addDictionaryType")
- public void add(HttpServletRequest request, HttpServletResponse response) {
-
-
- boolean result = false;
-
- DictionaryType dictionaryType = new DictionaryType();
- try {
-
-
- dictionaryType.setDictionaryTypeName(new String(request
- .getParameter("DictionaryTypeName").getBytes("iso-8859-1"),
- "UTF-8"));
- dictionaryType.setDictionaryTypeCode(new String(request
- .getParameter("DictionaryTypeCode").getBytes("iso-8859-1"),
- "UTF-8"));
- dictionaryType.setStatus(new String(request.getParameter("status")
- .getBytes("iso-8859-1"), "UTF-8"));
-
- dictionaryType.setOperator(new String(System.getProperty(
- "user.name").getBytes("iso-8859-1"), "UTF-8"));
- dictionaryType.setComment(new String(request
- .getParameter("comment").getBytes("iso-8859-1"), "UTF-8"));
-
-
- result = dictionaryTypeBean.saveEntity(dictionaryType);
-
- if (result) {
- outToJson.outJson(response, "success");
- } else {
-
- outToJson.outJson(response, "error");
- }
-
- } catch (Exception e) {
- System.out.println("添加字典类型失败");
- e.printStackTrace();
- }
-
- }
上面就直接通过PrintWriter对象来输出参数,然后在JS中异步获取来进行判断