前文:
手把手教你整合ssm框架(一)创建maven工程:https://blog.csdn.net/wh456413/article/details/106434125
手把手教你整合ssm框架(二)开始整合框架:
https://blog.csdn.net/wh456413/article/details/106437090
接上一步骤,通过mybatis generator反向生成代码,已生成dao层,mapper层,module层代码,
接下来需要自定义controller(控制层),service,service.Impl(实现层)代码
如下;
1.先建立对应包
2.service
该层放接口,代码内容直接拷贝dao层代码
3.service.impl
实现service层对应接口
在类前添加@Service注解,引入dao层对象,如:
@Service
public class userServiceImpl implements UserService{
@Autowired
private UserMapper um;
实现类实现方法设置调用dao层对应方法,dao层会调用mapper层映射文件中id对应sql语句
如:
@Override
public int insert(User record) {
int num=um.insert(record);
return num;
}
4.controller层
控制层,在类前添加@Controller注解,建议添加@RequestMapping注解,设置类映射路径;
注入service.Impl实现层类对象
在方法前添加@RequestMapping注解,设置方法映射路径,不跳转页面,返回参数时,在方法前再添加@ResponseBody注解,如:
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private userServiceImpl userImpl;
@RequestMapping("/selectByPrimaryKey")
@ResponseBody
public User selectByPrimaryKey(Integer id){
User u=userImpl.selectByPrimaryKey(id);
return u;
}
}
debug run启动工程
测试该接口结果:
跳转页面时,设置返回结果为String类型
在springMVC的配置文件spring-mvc.xml中有一个视图解析器的配置,详情见手把手教你整合ssm框架(二):
<!-- 配置视图解释器ViewResolver -->
<bean id="jspViewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 以下部分是拼接jsp文件路径 -->
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
当返回为String类型时,会被自动拼接为webapp/view/*.jsp,如:
@RequestMapping("/hellojsp")
public String hello(){
return "hello";
}
访问效果:
打开的是如图文件:
通过request.getSession().setAttribute()使后端向前端传递参数
如:
@RequestMapping("/hellojsp")
public String hello(HttpServletRequest request){
request.getSession().setAttribute("dm", "hello123456");
return "hello";
}
hello.jsp代码:
<body>
${dm}
</body>
访问效果:
建议测试接口使用postman测试,浏览器一般只支持get类型请求访问
下载链接:https://pan.baidu.com/s/1FJt1Y7bKjMpr3767a57v_w
提取码:qm49
压缩包解压即可使用