MyBatis+Spring 集成完毕。
想实现与数据库用户的姓名密码对比的简单登录
单独写方法用Junit测试可以取到数据库里的数据。
测试读数据库代码如下:
ApplicationContext aContext =
new FileSystemXmlApplicationContext(
"WebRoot/WEB-INF/applicationContext.xml");
UserMapper userMapper = aContext.getBean(UserMapper.class);
//调用userMapper方法 按名字实现数据库查询
user = userMapper.getUser("beer");
System.out.println("---" +userName );
System.out.println("---" +userPsw );
可以取到数据库的数据 对应 beer 999
但是放在业务逻辑中或(我)放在servlet中 报org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:\Program Files\Java\Tomcat 6.0\bin\WebRoot\WEB-INF\applicationContext.xml]; nested exception is java.io.FileNotFoundException: WebRoot\WEB-INF\applicationContext.xml (系统找不到指定的路径。)
servlet中的代码如下:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.FileSystemXmlApplicationContext;
import com.sarnath.entity.User;
import com.sarnath.entity.UserMapper;
public class indexServlet extends HttpServlet {
private User user;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ApplicationContext aContext = new FileSystemXmlApplicationContext(
"WebRoot/WEB-INF/applicationContext.xml");
UserMapper userMapper = aContext.getBean(UserMapper.class);
//调用userMapper方法 按名字实现数据库查询
user = userMapper.getUser("beer");
String userName = user.getName().toString();
String userPsw = user.getPsw().toString();
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("userName");
String pwd = request.getParameter("psw");
// 生成页面的格式
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
if (userName.equals(name) && userPsw.equals(pwd)) {
// out.print("<script>alert('恭喜你');window.location.href='/Mybatis_spring/success.jsp';</script>");
// new一个输出的对象
out.print("username:" + name + "<br/>");
out.print("password:" + pwd + "<br/>");
//显示从数据库中读取的数据
// out.print("oralce" + userName);
out.flush();
out.close();
} else {
// out.print("对不起用户名或密码不正确");
out.print("<script>alert('对不起');window.location.href='/Mybatis_spring/index.jsp';</script>");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
很是郁闷,为什么单测并没有路径错误,放在业务逻辑中就找不到路径。
因为刚接触 所以求大虾指点一二。
最佳实践是spring配置文件放到classpath里,而不是WEB-INF下。
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:/applicationContext.xml");
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。