当前位置: 首页 > 工具软件 > Web-Return > 使用案例 >

SpringMVC下在Controller层重定向到WEB-INF目录下的JSP页面

穆博简
2023-12-01

今天在写页面的登陆成功之后的跳转,想使用重定向跳转到首页。
直接在service里面写

    return "admin/main";

可以运行,不过是forward方式。
我改成

	return "redirect:/admin/main";

就出现了404错误。
原因:
重定向是客户端的,而转发是服务端内部的。
重定向是让客户端去访问重定向的地址,而WEB-INF下的文件是不能通过外部访问的!

于是,
我就想到在Controller层多加一个方法:

	@RequestMapping("/toMain")
	public String toMain() {
		return "admin/main";
	}

然后service中返回:

	return "redirect:/admin/toMain";

这样就顺利重定向到WEB-INF中的main.jsp页面

代码如下:
AdminServiceImpl

package priv.service.admin.impl;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import priv.dao.admin.AdminDao;
import priv.dao.admin.AdminTypeDao;
import priv.model.po.Auser;
import priv.service.admin.IAdminService;


@Service("adminService")

/**
 * 
 * @author pitt
 * @Explain Basic Operations for Administrators
 * 
 */

public class AdminServiceImpl implements IAdminService{
	@Autowired
	private AdminDao admindao;
	@Autowired
	private AdminTypeDao adminTypeDao;
	
	/**
	 * @explain 判断用户是否登陆成功,成功一并返回商品列表。
	 */
	@Override
	public String login(Auser auser, Model model, HttpSession session) {
		Auser interimUser = admindao.exactQuery(auser.getAname());
		if( interimUser == null )
		{
			session.setAttribute("msg", "用户名错误!");
			return "admin/login";
		}
		else{
			if(interimUser.getApwd().equals(auser.getApwd())) {
				session.setAttribute("auser", auser);
				session.setAttribute("goodsType", adminTypeDao.selectGoodsType());
				return "redirect:/admin/toMain";
			}
			else {
				session.setAttribute("msg", "密码错误!");
				return "admin/login";
			}
			
		}
	}

}

AdminController :

package priv.controller.admin;

import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import priv.model.po.Auser;
import priv.service.admin.IAdminService;

@Controller

@RequestMapping("/admin")
public class AdminController {
	@Autowired
	private IAdminService adminService;
	
	@RequestMapping("/toLogin")
	public String toLogin(@ModelAttribute Auser auser) {
		return "admin/login";
	}
	
	@RequestMapping("/toMain")
	public String toMain() {
		return "admin/main";
	}
	
	@RequestMapping("/login")
	public String login(@ModelAttribute Auser auser, Model model, HttpSession session) {
		return adminService.login(auser, model, session);
	}
	@RequestMapping("/exit")
	public String exit(@ModelAttribute Auser auser,HttpSession session) {
		session.invalidate();
		return "admin/login";
	}
}

 类似资料: