1、定义一个类实现servlet接口,和相关配置
- 在3.0之前需要配置web.xml,3.0和3.0之后就使用注解配置
<!--web.xml中-->
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>com.yj.servlet.ServletDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/demo1</url-pattern>
</servlet-mapping>
//3.0之后使用注解(推荐): @WebServlet("资源路径")
@WebServlet("/demo1")
public class ServletDemo implements Servlet{
//实现接口中的所有抽象方法: 5个
//getServletConfig()、getServletInfo()
/*
生命周期方法:
1、被创建:init()只执行一次
2、提供服务:service() 执行多次
3、被销毁:destroy() 服务器关闭时执行,执行一次
*/
}
- servlet 体系结构
graph LR
A[Servlet接口] -->B[GenericServlet抽象类]
B -->C[HttpServlet抽象类]
GenericServlet:将Servlet接口中其他的方法做了默认空实现,只将service()方法作为抽象
HttpServlet:对http协议的一种封装,简化操作,直接复写doGet/doPost方法即可
简化写法:
@WebServlet("/demo1")
public class ServletDemo extends GenericServlet{
//实现抽象方法 service:1个
}
最终写法:
@WebServlet("/demo1")
public class ServletDemo implements HttpServlet{
//重写方法:doGet/doPost
}
2、定义的Servlet如何在浏览器访问
- 配置好tomcat,如何配置:点击查看
- 上述的代码会找不到servlet相关的包,需要导入servlet-api
导入步骤:
1、在file菜单栏下找到project Structure
2、找到 Libraries,点击+号,选择java
3、找到 Tomcat的安装目录下的lib文件夹,下面有 servlet-api.jar,选择导入
- 运行tomcat,在打开的浏览器页面地址栏后添加/demo1路径就可以访问到了
3、登录案例
-
需求
-
项目目录结构
-
servlet部分代码
//LoginServlet
@WebServlet("/loginDemo")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码
req.setCharacterEncoding("utf-8");
//正常步骤:获取请求参数并封装user对象
// String username = req.getParameter("username");
// String password = req.getParameter("password");
//
// User loginUser = new User();
// loginUser.setName(username);
// loginUser.setPassword(password);
//使用BeanUtils,简化数据封装
/*
* 需要到入两个包:commons-beanutils-1.8.0.jar、commons-logging-1.2.jar
* */
Map<String, String[]> map = req.getParameterMap();
User loginUser = new User();
try {
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserDao userDao = new UserDao();
User user = userDao.login(loginUser);
if(user == null){
//登录失败转发
req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
//登录成功转发,并向reques域中共享user对象
req.setAttribute("user", user);
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
//SuccessServlet
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
User user = (User) req.getAttribute("user");
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("登录成功,欢迎"+ user.getName());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}