首先建立servlet3.0 版的web.xml
因为servlet3.0支持注解开发
所以web.xml只保留个模板就好
也可以增加一个默认页的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" >
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
我在这里定义了一个login.jsp的默认页
之后不需要在这配置servlet及映射,直接在类上打注解
@WebServlet(name="LoginServlet",value="/LoginServlet")
public class LoginServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");//获取表单用户名密码
String password = req.getParameter("password");
if (username.equals("SoDa") && password.equals("SoDa")){
Double balance = new Double("0.0");//判定成功初始化存储session
HttpSession session = req.getSession();
session.setAttribute("balance",balance);//把初始化的session放进去
req.getRequestDispatcher("/index.jsp").forward(req,resp);
}else{
//验证失败放一个错误信息到前台显示
req.setAttribute("error","Your Username or Password is wrong!!");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
效果等同于在web.xml中定义
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>cn.edu.hyit.atm.web.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>