JavaEE_Mybatis_SpringMVC_整合开发_Controller的返回值

本文详细解释了Spring MVC Controller中的三种返回类型及其实际应用:返回ModelAndView、返回字符串视图名、redirect和forward跳转,以及返回void的情况。通过具体代码示例,帮助开发者更好地理解和运用这些返回类型。

Controller方法的返回值有三种

1.返回ModeAndView  注意:此时形参可以为空,

2.返回String

(1)返回逻辑视图名    如:“items/editItem”   真正的视图(JSP路径)= 前缀+逻辑视图名+后缀(通过设置视图解析器)

(2)redirect重定向      如:“redirect:queryItem.action”

(3)forward页面转发  如:"forward:queryItem.action"  

  redirect 与 forward 配置的是action,不是jsp路径,若在同一个类中不需要配置全路径

3.返回void     注意:此时需要设置HttpServletRequest  request, HttpServletResponse response 两个形参,此时类似于原始的Servlet 开发。



1.返回ModeAndView  注意:此时形参可以为空,

示例:

	 //形参为空, 返回值为ModeAndView的Controller
	 @RequestMapping("/queryItems")
	 public ModelAndView queryItems() throws Exception {
	
	 ItemsEx itemsEx = new ItemsEx();
	 ItemsExVo itemsExVo = new ItemsExVo();
	 itemsExVo.setItemsEx(itemsEx);
	 List<ItemsEx> itemsList = itemsService.findItemsExList(itemsExVo);
	
	 // 新建ModelAndView
	 ModelAndView modelAndView = new ModelAndView();
	 // 相当于request 的 setAttribute, 在 jsp 页面中通过 itemList 取数据
	 modelAndView.addObject("itemsList", itemsList);
	 // 指定视图
	 modelAndView.setViewName("items/itemsList");
	
	 return modelAndView;
	 }






2.返回String

(1)返回逻辑视图名    如:“items/editItem”   真正的视图(JSP路径)= 前缀+逻辑视图名+后缀(通过设置视图解析器)

	// 形参为Model, 返回值为String的ModeAndView的Controller
	@RequestMapping("/queryItems")
	public String queryItems(Model model) throws Exception {

		ItemsEx itemsEx = new ItemsEx();
		// itemsEx.setName("本");
		// itemsEx.setPrice(20.0f);
		ItemsExVo itemsExVo = new ItemsExVo();
		itemsExVo.setItemsEx(itemsEx);
		List<ItemsEx> itemsList = itemsService.findItemsExList(itemsExVo);

		model.addAttribute("itemsList", itemsList);

		return "items/itemsList";
	}


(2)redirect重定向      如:“redirect:queryItem.action”

	// 返回String,利用redirect:queryItems.action,进行redirect进行跳转的形式
	@RequestMapping("/editItemsSubmit")
	public String editItemSubmit() throws Exception {
		// 调用service更新商品信息。页面需要将商品信息传到此方法中
		// ...

		// 相当于HttpServletRequest中的redirect方法,地址栏的信息不会发生变化
		// 如此例中变为http://localhost:8080/Web_SSM_test/items/queryItems.action
		return "redirect:queryItems.action";
	}


(3)forward页面转发  如:"forward:queryItem.action"  

	 // 返回String,利用forward:queryItems.action,进行forward进行跳转的形式
	 @RequestMapping("/editItemsSubmit")
	 public String editItemSubmit() throws Exception {
	 // 调用service更新商品信息。页面需要将商品信息传到此方法中
	 // ...
	
	 // 相当于HttpServletRequest中的request方法,地址栏的信息不会发生变化
	 // 如此例中仍为http://localhost:8080/Web_SSM_test/items/editItemsSubmit.action
	 return "forward:queryItems.action";
	 }


 redirect 与 forward 配置的是action,不是jsp路径,若在同一个类中不需要配置全路径







3.返回void     

注意:此时需要设置HttpServletRequest  request, HttpServletResponse response 两个形参,此时类似于原始的Servlet 开发。

(1)使用request 转向页面,如下

 request.getRequestDispatcher("页面路径").forward(request,response)


(2)通过response 页面重定向

response.sendRedirect("url")


(3)也可以通过response指定响应结果,例如响应Json数据如下

response.setCharacterEncoding("utf-8");

response.setContentType("application/json;charset=utf-8");

response.getWriter().write("json串")



整体的Controller代码

package cn.itcast.ssm.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import cn.itcast.ssm.po.ItemsEx;
import cn.itcast.ssm.po.ItemsExVo;
import cn.itcast.ssm.service.ItemsService;

//限制Http请求方法
//@RequestMapping(value = "/items", method = { RequestMethod.POST,RequestMethod.GET })
@Controller
@RequestMapping(value = "/items", method = { RequestMethod.POST,
		RequestMethod.GET })
public class ItemsController {

	@Autowired
	ItemsService itemsService;

	// //形参为空, 返回值为ModeAndView的Controller
	// @RequestMapping("/queryItems")
	// public ModelAndView queryItems() throws Exception {
	//
	// ItemsEx itemsEx = new ItemsEx();
	// ItemsExVo itemsExVo = new ItemsExVo();
	// itemsExVo.setItemsEx(itemsEx);
	// List<ItemsEx> itemsList = itemsService.findItemsExList(itemsExVo);
	//
	// // 新建ModelAndView
	// ModelAndView modelAndView = new ModelAndView();
	// // 相当于request 的 setAttribute, 在 jsp 页面中通过 itemList 取数据
	// modelAndView.addObject("itemsList", itemsList);
	// // 指定视图
	// modelAndView.setViewName("items/itemsList");
	//
	// return modelAndView;
	// }

	// 形参为Model, 返回值为String的ModeAndView的Controller
	@RequestMapping("/queryItems")
	public String queryItems(Model model) throws Exception {

		ItemsEx itemsEx = new ItemsEx();
		// itemsEx.setName("本");
		// itemsEx.setPrice(20.0f);
		ItemsExVo itemsExVo = new ItemsExVo();
		itemsExVo.setItemsEx(itemsEx);
		List<ItemsEx> itemsList = itemsService.findItemsExList(itemsExVo);

		model.addAttribute("itemsList", itemsList);

		return "items/itemsList";
	}

	@RequestMapping("/editItems")
	public ModelAndView editItems(HttpServletRequest request) throws Exception {

		Integer id = Integer.parseInt(request.getParameter("id"));
		System.out.println(id);

		ItemsEx itemsEx = itemsService.findItemsById(id);

		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("itemsEx", itemsEx);

		// 相当于froward(response,request)
		modelAndView.setViewName("items/editItems");

		return modelAndView;
	}

	// //返回ModeAndView的Controller
	// @RequestMapping("/editItemsSubmit")
	// public ModelAndView editItemSubmit(HttpServletRequest request)
	// throws Exception {
	//
	// // 得到form表单的数据
	// System.out.println(request.getParameter("name"));
	// System.out.println(request.getParameter("price"));
	// System.out.println(request.getParameter("detail"));
	//
	// // 调用service更新商品信息。页面需要将商品信息传到此方法中
	// // ...
	// ModelAndView modelAndView = new ModelAndView();
	// // 若修改成功,返回成功的页面
	// modelAndView.setViewName("success");
	//
	// return modelAndView;
	// }

	// // 返回String,利用forward:queryItems.action,进行forward进行跳转的形式
	// @RequestMapping("/editItemsSubmit")
	// public String editItemSubmit() throws Exception {
	// // 调用service更新商品信息。页面需要将商品信息传到此方法中
	// // ...
	//
	// // 相当于HttpServletRequest中的request方法,地址栏的信息不会发生变化
	// // 如此例中仍为http://localhost:8080/Web_SSM_test/items/editItemsSubmit.action
	// return "forward:queryItems.action";
	// }

	// 返回String,利用redirect:queryItems.action,进行redirect进行跳转的形式
	@RequestMapping("/editItemsSubmit")
	public String editItemSubmit() throws Exception {
		// 调用service更新商品信息。页面需要将商品信息传到此方法中
		// ...

		// 相当于HttpServletRequest中的redirect方法,地址栏的信息不会发生变化
		// 如此例中变为http://localhost:8080/Web_SSM_test/items/queryItems.action
		return "redirect:queryItems.action";
	}

}




### Java EE 中 MyBatis 实验模块缺失解决方案 在处理 Java EE 的 MyBatis 实验过程中,如果遇到模块丢失的问题,通常可以从以下几个方面进行排查和修复: #### 1. **确认项目依赖配置** 确保项目的 `pom.xml` 文件(如果是 Maven 项目)或者 Gradle 构建文件中已经正确引入了 MyBatis 及其相关依赖项。以下是典型的 Maven 配置示例[^1]: ```xml <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> ``` 如果没有正确配置上述依赖,则可能导致 MyBatis 功能无法正常加载。 --- #### 2. **检查实验环境设置** 验证当前使用的开发工具是否支持所需的 MyBatis 版本以及对应的 JDK 和服务器版本。例如,在 Eclipse 开发环境中,需确保已安装并启用了必要的插件,比如 MyBatis Generator 插件或类似的辅助工具[^3]。 此外,还需注意以下几点: - 数据库驱动程序是否匹配目标数据库类型。 - 是否存在路径错误或其他外部资源配置问题。 --- #### 3. **分析日志信息** 当运行应用程序时发生异常,应仔细查看控制台输出的日志消息。通过捕获到的关键字定位具体原因。例如,某些情况下可能是由于 SQL 映射文件未被识别而导致的功能失效[^4]。 对于此类情况,建议重新整理 Mapper 接口及其 XML 文件之间的关联关系,并按照如下方式注册至 Spring 容器中: ```java @Configuration @MapperScan(basePackages = "com.example.mapper") // 替换为实际包名 public class MyBatisConfig { } ``` --- #### 4. **恢复缺失的模块** 如果确实发现某个特定功能模块遗失,可以通过以下途径尝试找回: - 查阅官方文档获取最新版教程资料; - 对比其他成功案例寻找差异之处; - 利用版本控制系统(如 Git),回滚至上一次稳定状态后再逐步调整修改部分直至满足需求为止。 同时提醒开发者定期备份重要代码片段以防意外删除操作带来的不便影响整体进度安排。 --- #### 5. **测试与调试** 最后一步便是执行全面详尽的功能性检测工作流程以确保存在的所有潜在隐患均已被妥善消除掉之后再提交最终成果物给相关人员审阅批准发布上线投入使用环节当中去吧! ```java // 测试样例 @Test void testMyBatisFunctionality() { SqlSession session = sqlSessionFactory.openSession(); try { User user = session.selectOne("getUser", 1); assertNotNull(user); // 断言对象不为 } finally { session.close(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值