ssm+maven用拦截器实现登录小Demo
本人也是第一次学习ssm框架,所以简单写了个小Demo,本例结合ssm框架,和maven以及springMVC中的拦截器实现的登录:
- 项目的整体结构
pom.xml
根据给出的jar包很容易得知
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- spring配置文件加载 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mybatis.xml</param-value>
</context-param>
<!-- SpringMVC核心Servlet -->
<servlet>
<servlet-name>springMVC-config</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring ApplicationContext 载入 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 拦截所有请求 -->
<servlet-mapping>
<servlet-name>springMVC-config</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<display-name></display-name>
<!-- 编码过滤 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springmvc-config.xml
<!--spring可以自动去扫描base-pack下面或者子包下面的java文件,
如果扫描到有@Component @Controller@Service等这些注解的类,则把这些类注册为bean-->
<context:component-scan base-package="com.kze.controller">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
<!-- 加载注解驱动 -->
<mvc:annotation-driven />
<mvc:default-servlet-handler/>
<!-- 配置jsp文件的前后缀 “/”代表的是项目设定的Resource目录 -->
<bean id = "viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp" />
</bean>
<!-- 配置拦截器 -->
<mvc:interceptors>
<!--使用bean直接定义在<mvc:interceptors>下面的拦截器将拦截所有请求-->
<!-- <bean class="com.itheima.interceptor.CustomInterceptor"/> -->
<!-- 拦截器1 -->
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.kze.interceptor.loginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
spring-mybatis.xml
<!-- 自动搜索bean -->
<context:annotation-config/>
<!-- 扫描service -->
<context:component-scan base-package="com.kze" />
<bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/logindemo"/>
<property name="username" value="root"/>
<property name="password" value="kzw11"/>
</bean>
<!-- mybatis核心bean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<!-- 这句配置mapper配置文件的位置 如果采用注解的方式这句可以省去 -->
<!--<property name="mapperLocations" value="classpath:/WEB-INF/Mappers/*.xml" />-->
</bean>
<!-- 自动搜索mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.kze.mapper" />
</bean>
<!-- 事务处理 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"/>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="select*" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="serviceCut" expression="execution(* com.kze.service.*.*(..))" />
<aop:advisor pointcut-ref="serviceCut" advice-ref="txAdvice" />
</aop:config>
User.java
private int id;
private String username,password,slogan;
//getters,setters此处省略
userMapper
public interface UserMapper {
@Select("select * from user")
public List<User> selectAllUser();
@Select("select * from user where username = #{username}")
public List<User> selcetUserByName(@Param("username")String username);
}
userServiceImpl.java
@Service("userService")
public class UserServiceImpl implements Usersevice{
@Autowired
private UserMapper usermapper;
public void setUsermapper(UserMapper usermapper) {
this.usermapper = usermapper;
}
public User getUserByName(String name) {
return usermapper.selcetUserByName(name).get(0);
}
public boolean verify(String username, String pwd) {
if(usermapper.selcetUserByName(username).get(0).getPassword().equals(pwd)){
return true;
}else{
return false;
}
}
}
控制器Login.java
@Controller
public class Login {
@Autowired
private Usersevice userService;
public void setUserService(Usersevice userService) {
this.userService = userService;
}
@RequestMapping("/toindex")
public String toIndex(){
return "index";//这里index我作为了登录界面
}
@RequestMapping("/main")
public String main(){
return "main";//作为想要访问的目标界面
}
@RequestMapping("/logout")
public String logout(HttpSession session){
//清除session
session.invalidate();
return "redirect:index";
}
@RequestMapping("/login")
public String login(HttpServletRequest req, HttpServletResponse resp){
System.out.println("login 方法调用成功!");
String username=req.getParameter("username");
String pwd=req.getParameter("password");
System.out.println(username+"为用户名; 密码为:"+pwd);
if(userService.verify(username,pwd)){
req.getSession().setAttribute("user",userService.getUserByName(username));
return "main";
}else{
return "index";
}
}
}
loginInterceptor.java
public class loginInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2, ModelAndView arg3) throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
//获取请求的url
String url = request.getRequestURI();
//除了login.jsp是可以公开访问的,其余的URL都进行拦截
if(url.indexOf("/login")>=0){
return true;
}
//获取session
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
//判断session中是否有用户数据,如果有就返回true,继续向下执行
if(user!=null){
return true;
}
//给出提示信息,并转发至登录页面
request.setAttribute("msg", "你还有没有登录,请先登录!");
request.getRequestDispatcher("/WEB-INF/jsp/index.jsp").forward(request, response);
return false;
}
}
数据库设计
代码完毕
运行效果
登录成功过后
写到这里应该算结束了,兄dei我也是个新手哈,欢迎各位大神评论,赐教。不喜就勿喷哈···
demo下载地址:下载