0
我正在使用spring mvc。要攔截我使用servlet過濾器的url。我試圖通過「login.jsp」來驗證用戶。但是,當我輸入用戶名和密碼,然後再次提交it.It 指導我爲 「login.jsp」Servlet過濾器不能正常工作
我的Servlet過濾器:
@WebFilter(urlPatterns={"/*"})
public class MyFilter implements Filter {
private ServletContext context;
public MyFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpServletRequest request1 = (HttpServletRequest)request;
HttpServletResponse response1 = (HttpServletResponse)response;
HttpSession session = request1.getSession(false);
String uri = request1.getRequestURI();
if((session==null || session.getAttribute("users")==null)&& (!uri.endsWith("login.jsp") && !uri.endsWith("record/authenticate"))){
request1.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request1, response1);
}
else{
chain.doFilter(request,response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
this.context = fConfig.getServletContext();
}
}
我的控制器:
@Controller
@RequestMapping("/record")
public class MainController {
@Resource(name="userService")
private UserService userService;
@Resource(name="roleService")
private RoleService roleService;
@RequestMapping(value="/login")
public String GetFront(Model model){
return "login";
}
@RequestMapping(value="/authenticate",method = RequestMethod.POST)
public String authenticate(@RequestParam("uname")String userName,@RequestParam("pass")String password,
HttpSession session,HttpServletRequest request,Model model){
boolean success = userService.validate(userName,password);
User user = userService.getuserByName(userName);
Set<Role> roles = user.getRole();
//String role = null;
/*
for (Role role1: roles) {
if(role1.getRoleName().equalsIgnoreCase("admin")){
role = "admin";
}
}
*/
if(success){
session = request.getSession();
session.setAttribute("users",userName);
session.setAttribute("role", roles);
return "Hello";
}
else{
return "error";
}
}
}
我的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Project1</display-name>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>Filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>