SpringMVC(13):使用springmvc优化订单管理系统的示例(登陆和注销的简单实现)

本文介绍了一个基于SpringMVC的订单管理系统实战案例,详细展示了系统各层的设计与实现过程,包括控制器、业务层、DAO层等,并配置了Spring、SpringMVC相关组件。

18/1/15

对于springmvc的学习过了很长时间了,下面做个阶段性的总结。

小项目demo:

 springmvc5 : 改造订单管理系统,
1、spring配置文件,加入<context:component-scan/>
2、SpringMVC配置文件,加入View层的静态文件访问配置,
3、web.xml配置文件,加入spring字符编码过滤器,
3、Dao层:UserDao+UserDaoImpl,
4、Service层:UserService+UserServiceImpl,
5、Controller层:Usercontroller:
login--页面跳转到登录面;
doLogin--实现登陆,成功后把用户存入session,完成登陆,否则跳转登录面,带出错误提醒;
main--页面跳转到系统首页(session是否为空);
logout--注销,session失效,跳转到系统登陆面;

【0】文件框架与jar包


图1


图2



【1】控制器层:/com/User/Controller/UserController.java,添加控制器代码:

package com.User.Controller;

import java.sql.SQLException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.User.Service.UserService;
import com.User.entities.User;

@Controller
@RequestMapping("/user")
public class UserController {
	private Logger log = Logger.getLogger(UserController.class.getName());
	
	@Autowired
	private UserService userService ;
	
	@RequestMapping(value="/login")
	public String login(){
		log.debug("UserController welcome SMBMS============" );
		return "login";//页面跳转到登录面;
	}
	
	@RequestMapping(value="/dologin",method=RequestMethod.POST)
	public String doLogin(@RequestParam String userName,
			               @RequestParam String userPassword,
			               HttpSession session,
			               HttpServletRequest req) throws SQLException{
		User user = userService.login(userName,userPassword);
		log.info("后台找一下有没有这个username和password: "+user);
		if(null == user.getId()){
//			return "redirect:login";
			throw new RuntimeException("用户名或者密码不正确!");
		}else{
			log.info("user.toString(): "+user.toString());
			user.setUserName(userName);
			user.setUserPassword(userPassword);
			session.setAttribute("currentUser", user);
			log.info("刚刚存入了一个session对象:"+session.getAttribute("currentUser"));
			return "sys";
		}
	}
	
	@RequestMapping("/sys")
	public String main(HttpSession session){
		if(session.getAttribute("currentUser") == null){
			return "redirect:login";
		}
		return "sys";
	}
	
	//局部异常,使用全局时,要记得注释掉这个方法,不然会导致异常
	@ExceptionHandler(value={RuntimeException.class})
	public String handlerException(RuntimeException e, HttpServletRequest req){
		log.info("进入异常处理..");
		req.setAttribute("e", e);
		return "login";
	}
	
	//注销
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest req,HttpSession session){
		// 清除session
        Enumeration<String> em = req.getSession().getAttributeNames();
        while (em.hasMoreElements()) {
            req.getSession().removeAttribute(em.nextElement().toString());
        }
        log.info("已经删除session内容");
        log.info("查看存入的session对象还在不在:"+session.getAttribute("currentUser"));
        return "login";
	}
}

解释:(1)局部异常出处理;

(2)session入参;


【2】业务层:\com\User\Service\UserServiceImpl.java 和 接口 UserService.java :

 接口 UserService.java :

package com.User.Service;

import java.sql.SQLException;

import com.User.entities.User;

public interface UserService {
	public User login(String userCode,String userPassword) throws SQLException;
}

UserServiceImpl.java:

package com.User.Service;

import java.sql.SQLException;

import org.springframework.stereotype.Service;

import com.User.Dao.UserDao;
import com.User.Dao.UserDaoImpl;
import com.User.entities.User;

@Service("userService")
public class UserServiceImpl implements UserService {
	private UserDao userDao = new UserDaoImpl();
	@Override
	public User login(String userName, String userPassword) throws SQLException {
		return userDao.loginMatch(userName,userPassword);
	}

}

【3】Dao层:com\User\Dao\UserDaoImpl.java  和 接口UserDao.java:

 接口UserDao.java:

package com.User.Dao;

import java.sql.SQLException;

import com.User.entities.User;

public interface UserDao {
	public User loginMatch(String userName, String userPassword) throws SQLException;
}

UserDaoImpl.java:

package com.User.Dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.User.BaseDao.ConfigManager;
import com.User.Controller.UserController;
import com.User.entities.User;

@Component("userDao")
public class UserDaoImpl implements UserDao {
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private String sql;
	@Override
	public User loginMatch(String userName, String userPassword) throws SQLException {
		Logger log = Logger.getLogger(UserController.class.getName());
		User user = new User();
		log.info("UserDaoImpl.loginMatch");
		sql = "select * from smbms_user"
				+ " where userName='"+ userName+"' and userPassword='"+userPassword+"';";
		System.out.println("sql: "+sql);
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/test";
		String username = "root";
		String password = "";
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url,username,password);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		stmt = conn.createStatement();
		rs = stmt.executeQuery(sql);
		while(rs.next()){
			System.out.println("8888");
			user.setId(rs.getInt(1));
			System.out.println(rs.getInt("id"));
			user.setUserCode(rs.getString(2));
			user.setUserName(rs.getString(3));
			user.setUserPassword(rs.getString(4));
			user.setGender(rs.getInt(5));
			user.setBirthday(rs.getDate(6));
			user.setPhone(rs.getString(7));
			user.setAddress(rs.getString(8));
			user.setUserRole(rs.getInt(9));
			user.setCreatedBy(rs.getInt(10));
			user.setCreationDate(rs.getDate(11));
		}
		if(stmt!=null){
			stmt.close();
		}
		if(rs!=null){
			rs.close();
		}
		return user;
	}

}

【4】实体类:com\User\entities\User.java:

package com.User.entities;

import java.util.Date;
import java.util.List;

public class User {
	private Integer id;
	private String userCode;
	private String userName;
	private String userPassword;
	private Integer gender;
	private Date birthday;
	private String phone;
	private String address ;
	private Integer userRole;
	private Integer createdBy;
	private Date creationDate;
	private Integer modifyBy;
	private Date modifyDate;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
	public User(Integer id, String userCode, String userName, String userPassword, Integer gender, Date birthday,
			String phone, String address, Integer userRole, Integer createdBy, Date creationDate, Integer modifyBy,
			Date modifyDate) {
		super();
		this.id = id;
		this.userCode = userCode;
		this.userName = userName;
		this.userPassword = userPassword;
		this.gender = gender;
		this.birthday = birthday;
		this.phone = phone;
		this.address = address;
		this.userRole = userRole;
		this.createdBy = createdBy;
		this.creationDate = creationDate;
		this.modifyBy = modifyBy;
		this.modifyDate = modifyDate;
	}
	public User() {
		super();
		// TODO 自动生成的构造函数存根
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userCode=" + userCode + ", userName=" + userName + ", userPassword=" + userPassword
				+ ", gender=" + gender + ", birthday=" + birthday + ", phone=" + phone + ", address=" + address
				+ ", userRole=" + userRole + ", createdBy=" + createdBy + ", creationDate=" + creationDate
				+ ", modifyBy=" + modifyBy + ", modifyDate=" + modifyDate + "]";
	}
	
}

【5】spring的配置文件 applicationContext-jdbc.xml 添加以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 	xmlns:context="http://www.springframework.org/schema/context"
 	xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
			http://www.springframework.org/schema/beans/spring-beans.xsd
			http://www.springframework.org/schema/context 
        	http://www.springframework.org/schema/context/spring-context-4.0.xsd
        	http://www.springframework.org/schema/aop
        	http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        ">
	<context:component-scan base-package="com.User.Dao"></context:component-scan>
	<context:component-scan base-package="com.User.Service"></context:component-scan>

</beans>

【6】springmvc 的配置文件 springmvc-servlet.xml 添加以下内容:

<?xml version="1.0" encoding="UTF-8"?>  
<beans  xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:mvc="http://www.springframework.org/schema/mvc"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd  
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">  
    
    <mvc:annotation-driven></mvc:annotation-driven>  
    
   	<!-- 配置静态资源访问 -->
  	 <mvc:resources location="/static/" mapping="/static/**"/>
     <mvc:resources mapping="/resources/**" location="/resources/" />
     <mvc:resources mapping="/images/**" location="/images/" />
     <mvc:resources mapping="/js/**" location="/js/" />
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->

   	<!-- 一键式配置 -->  	
    <context:component-scan base-package="com.User"></context:component-scan>  
    
    <!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->  
    <!--prefix 前缀+suffix 后缀  -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/jsp/"></property>  
        <property name="suffix" value=".jsp"></property>  
    </bean>         
  	
  	<!-- 全局异常处理 -->
  	<!-- 
  	<bean class="org.springframework.web.servlet.handler.SimpleMapperExceptionResolver">
  		<property name="exceptionMappings">
  			<props>
  				<prop key="java.lang.RuntimeException">login</prop>
  			</props>
  		</property>
  	</bean>
  	 -->
</beans> 


【7】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"  
    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">  
  
      <!-- 这个指定了log4j.xml放置的目录 -->
    <context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value> 
	</context-param>
	 <!-- 一定要加上这个listener -->
	<listener>  
	    <listener-class>  
	        org.springframework.web.util.Log4jConfigListener 
	    </listener-class>  
	</listener> 
  
    <!-- 配置 DispatcherServlet -->
    <servlet>  
        <servlet-name>springmvc</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>
            <param-name>contextConfigLocation</param-name>  
            <param-value>classpath:springmvc-servlet.xml</param-value>  
        </init-param>  
        <!--容器启动时就被加载了    -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>springmvc</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  
           	
   	<filter>
		<filter-name>springUtf8Encoding</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>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>springUtf8Encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

    <welcome-file-list>
    	<welcome-file>/WEB-INF/jsp/login.jsp</welcome-file>
    </welcome-file-list>
    
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>
    <!-- 配置Spring的ContextLoaderListener监听器,初始化spring容器 -->
    <listener>
    	<listener-class>
    	 	org.springframework.web.context.ContextLoaderListener
    	</listener-class>
    </listener>

</web-app>  

【8】输出结果:

8.1 欢迎页:


8.2 输入正确的 userName 和 userPassword 后,跳转(静态资源调用出了错..后面继续改进):{原因已经找到,参考《SpringMVC(10):配置静态资源访问(前端页面的元素显示)及实例》}



8.3 点击注销,跳转回到原始页面:


8.4 输入错误的 userName 和 userPassword 后,跳转 和提示:



以上是博文的全部内容。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

后台技术汇

对你的帮助,是对我的最好鼓励。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值