您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
7-ssm整合-原始整合方式-测试(注解方式解决乱码问题)
发布时间:2025-02-08 19:04:06编辑:雪饮阅读()
-
在上篇中web.xml中用于处理乱码的配置filter与filter-mapping需要说明下,只是用于处理接收请求时候的乱码。而并不是处理响应?时候的乱码。而要处理响应时候的乱码在当前情况下最简单的就是注解RequestMapping中进行声明,该声明于我们上篇中的Account控制器,那么同样该控制器中对于findAll我们也漏掉一个就是url pattern的配置,我们也同时补齐pattern配置。
则如D:\os\SpringWebApp\SpringProject2Module10SSM\src\main\java\sp10\controller\AccountController.java:
package sp10.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sp10.domain.Account;
import sp10.service.AccountService;
import java.util.List;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
/*
通过@Autowired注解,自动注入AccountService接口的实现类
实现类中必须有Service注解标明为accountService
*/
private AccountService accountService;
//保存
@RequestMapping(value = "/save",produces="text/html;charset=UTF-8")
@ResponseBody
public String save(Account account){
accountService.save(account);
return "保存成功";
}
//查询
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Account> accountList=accountService.findAll();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("accountList",accountList);
modelAndView.setViewName("accountList");
return modelAndView;
}
}
接下来我们对accountList.jsp中数据列表展示进行完善,如D:\os\SpringWebApp\SpringProject2Module10SSM\src\main\webapp\pages\accountList.jsp:
<%@page contentType="text/html;charset=UTF-8" language="java"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>展示账户数据列表</h1>
<table>
<tr>
<th>账户id</th>
<th>账户名称</th>
<th>账户金额</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
还有一点就是前番的AccountMapper.xml中的insert标签的sql应该修改如:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="sp10.mapper.AccountMapper">
<insert id="save" parameterType="account">
insert into account(name,money) values(#{name},#{money})
</insert>
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
这样更安全,不然数据表的字段顺序不同也会导致数据添加失败。
最后配置tomcat进行测试访问如:
http://localhost:8080/SpringProject2Module10SSM_war_exploded/save.jsp
进行测试。
最后一点就是测试如
http://localhost:8080/SpringProject2Module10SSM_war_exploded/account/findAll
这个findAll的时候我们之前有个错误,就是pages目录应该在WEB-INF里面,而不是直接在webapp目录下面即webapp/WEB-INF/pages,弄成这样结构后就ok了。不然按照我们之前的配置这个findAll就成了404了。除非你再次修改spring-mvc.xml中如
<property name="prefix" value="/WEB-INF/pages/"/>
这个地方的配置或许可能也能解决404问题。
关键字词:ssm,原始,方式,测试,乱码,注解