(三)登录功能
由于我的web.xml文件件中没有配置默认访问界面,tomcat会自动寻找index.html,但发现index.html也没有,就会访问index.jsp界面了
1. 编写index.jsp界面,令其自动访问登录界面:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- Created by IntelliJ IDEA. User: Joker Date: 2019/8/11 0011 Time: 20:55 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <c:redirect url="login?method=getjsp"/> <%-- <html> <head> <title>Title</title> </head> <body> <h1>Hello world!</h1> </body> </html> --%>
2. 在com.fitsoft.shop.action包下新建LoginServlet类,接收处理请求
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private HttpServletRequest request;
private HttpServletResponse response;
//定义业务层对象
@Resource
private ShopService shopService;
@Override
public void init() throws ServletException {
super.init();
//获取Spring的容器,然后从容器中获取业务层对象
ServletContext servletContext = this.getServletContext();
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
shopService = (ShopService) context.getBean("shopService");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//跳转到登录界面
String method = req.getParameter("method");
if(method.equals("getjsp")){
req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
}
}
}
利用@Resource注解来获取业务层对象,但是由于Servlet是没有交由Spring管理的,Spring是不会把对象注入给它的,所以@Resource注解并没有生效,因此我们在初始化的方法中根据Servlet的上下文对象获取Spring的上下文对象,然后根据name("shopService")来获取业务层对象,并且此时业务层对象中应该加入注解:
![]()
来保证这个对象被扫描,这时我们还用不到这个shopService,然后处理我们的请求,判断method中的值是不是index.jsp界面传过来的,如果是,就将请求转发至登录界面:


浙公网安备 33010602011771号