servlet是Server let:小服务。能够处理网络请求。完成通过互联网为用户提供服务的一个服务程序。
web开发里,servlet和图片,视频等一样,都是一个网络资源。如何访问这个网络资源?
需要一个网络上可以定位的地址:URL。
用户有了url就可以无忧无虑的访问自己的目标地址。
那么有了url点开之后没有任何的数据,就没有任何的意义,那么如何添加相关数据呢?
首先我们要有实体对象,没有实体对象的话我们的一切操作都是无效的。
public class CompanyEntity {
private Long id;
private String introduction;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
}
然后呢就可以创建第一个servlet文件了。
@WebServlet("/index")
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
String name = req.getParameter("username");
String password = req.getParameter("password");
String result = name + "-" + password;
// 2. 处理完成后,要把这个数据交给第二个servlet,让他把密码找出来,并输出到浏览器端。
//http://localhost:8080/test/index2
//localhost:8080/index2
// 请求转发
// 把数据放入到session里
// HttpSession session = req.getSession();
// session.setAttribute("rs",result);
ServletContext application = req.getServletContext();
application.setAttribute("rs",result);
resp.sendRedirect("index2");
// req.getRequestDispatcher("index2").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 想浏览器输出一句话hell servelt!
// 输出:输出流
resp.getOutputStream().print("hell servlet!");
}
}
/index 就是这个FirstSevelt的网络上的名字。 要访问它只需要通过http/https协议+服务器地址(ip)+端口号+/index
之后不要忘记在Dao层里面封装好自己需要的方法哦!
下一步需要在service层里面实现自己的方法
public boolean login(String username,String password){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
IUserDao userDao = sqlSession.getMapper(IUserDao.class);
UserEntity userEntity = new UserEntity();
userEntity.setUsername(username);
userEntity.setPassword(password);
userEntity = userDao.findByNameAndPassword(userEntity);
return userEntity != null;
}
这样就可以从数据库里面调用数据进行比对。