作者:何俊雨_127 | 来源:互联网 | 2023-09-17 13:28
创建Servlet配置new一个dynamic(动态)注意:version:一定择2.5不然不会自动创建web.xml好处:src下直接创建一个Servlet,会自动把web.xm
创建Servlet配置
new一个dynamic(动态)
注意:version:一定择 2.5 不然不会自动创建 web.xml
好处:src下直接创建一个Servlet,会自动把web.xml配好
缺点:只会自动创建web.xml,不会自动删除 。但如果把Servlet删除了,web.xml是不会自动删除,若在建一个同名的Servlet会冲突。
快捷键添加Servlet模板
windows--preferences--java--Editor--Templates--New
使用: 敲入 ser +alt+/
package ${enclosing_package};
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ${primary_type_name} extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("hello sensen...");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
JSP登录功能
步骤:
1.WebContent下new一个login.jsp
2.建包 dao、service、tools、web
3.导jar驱动包:WebContent--WEB-INF--lib
4.在web层,建一个名为LoginServlet,然后Ctrl+a 全删。输入Servlet模板
package com.oracle.web;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oracle.service.UserService;
public class LoginServlet extends HttpServlet {
private UserService userService=new UserService();
public void init() throws ServletException {
// 获取ServletContext对象
ServletContext cOntext=getServletContext();
// 定义计数器
int count=0;
// 将计数器存入ServletContext对象 中
context.setAttribute("count", count);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数
String uname=request.getParameter("username");
//获取密码
String pwd=request.getParameter("pwd");
//调用service登录方法
int row=userService.loginUser(uname, pwd);
if(row>0){
//登录成功
// 获取ServletContext对象
ServletContext cOntext=getServletContext();
int count=(int)context.getAttribute("count");
count++;
context.setAttribute("count",count);
response.getWriter().write("you are the person success");
}else{
//登录失败
response.getWriter().write("fail");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}