暑期实习Day10---SSM框架整合

ssm框架整合

SSM整合初试

1.新建maven项目

archetype-webapp maven项目
暑期实习Day10---SSM框架整合_第1张图片

2.在pom.xml中导入相关依赖

这里整理好一份ssm需要用到的maven依赖,可根据需要更换版本

3.新建工程目录及相关说明

暑期实习Day10---SSM框架整合_第2张图片

4.在resourses下新建各种各样的配置文件并进行相关配置db log4

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/easybuy?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=1111
# Global logging configuration
#\u5728\u5f00\u53d1\u73af\u5883\u4e0b\u65e5\u5fd7\u7ea7\u522b\u8981\u8bbe\u7f6e\u6210DEBUG\uff0c\u751f\u4ea7\u73af\u5883\u8bbe\u7f6e\u6210info\u6216error
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

5.利用generator 生成pojo,dao,mapping的源代码

详细步骤可参考Day1配置部分 点击此处跳转

6.配置mybatis.xml



<configuration>

    <properties resource="db.properties">properties>

    <typeAliases >
        <package name="com.xhy.pojo"/>
    typeAliases>

    
configuration>

7.配置spring.xml文件


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/aop
            https://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="com.xhy">context:component-scan>


    
    
    <context:property-placeholder location="classpath:db.properties" />
    

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <property name="maxActive" value="30" />
        <property name="maxIdle" value="5" />
    bean>
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource" />
        
        <property name="configLocation" value="classpath:mybatis.xml" />
        <property name="mapperLocations" value="classpath:mapping/*.xml"/>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="basePackage" value="com.xhy.dao">property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    bean>
    




    
    <mvc:annotation-driven>mvc:annotation-driven>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp"/>
    bean>

    
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>1048576value>
        property>
    bean>
    


    

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource"/>
    bean>

    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.xhy.service.Impl.*.*(..))"/>
    aop:config>

    


beans>

8.配置web.xml文件


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  
  <servlet>
    <servlet-name>springmvcservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:spring.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>


  <servlet-mapping>
    <servlet-name>springmvcservlet-name>
    <url-pattern>*.dourl-pattern>
  servlet-mapping>
web-app>

9.在service层新建对应的业务接口

public interface UserService {

    EasybuyUser getUser(int uid);

}

10.实现对应的业务逻辑层接口

@Service("userService")
public class UserServiceImpl implements UserService {
    //业务逻辑层需要调用数据访问层
    @Autowired
    private EasybuyUserMapper easybuyUserMapper;

    //根据id查询用户信息
    @Override
    public EasybuyUser getUser(int uid) {

        return easybuyUserMapper.selectByPrimaryKey(uid);
    }
}

11.写controller

@Controller
@RequestMapping("/User")
public class userController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/get.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    public @ResponseBody String getUser(@RequestParam(required = true) Integer uid){
        //1.取2.调3.转
        EasybuyUser user = userService.getUser(uid);
        return JSONObject.toJSONString(user);
    }
}

12.配置服务器

暑期实习Day10---SSM框架整合_第3张图片

实战案例:登录功能

1.在mapper.xml中写sql语句

<sql id="Base_Column_List2" >
    id, loginName, userName, sex, identityCode, email, mobile, type
  sql>

  <select id="selectByUnameAndPwd" resultMap="BaseResultMap" >
    select
    <include refid="Base_Column_List2" />
    from easybuy_user
    where loginName = #{uname} AND password=#{upwd}
  select>

2,在数据访问接口写对应的抽象方法

public interface EasybuyUserMapper {


    int deleteByPrimaryKey(Integer id);

    int insert(EasybuyUser record);

    int insertSelective(EasybuyUser record);

    EasybuyUser selectByPrimaryKey(Integer id);

    //登录模块添加的
    EasybuyUser   selectByUnameAndPwd(@Param("uname") String uname,@Param("upwd") String upwd);

    int updateByPrimaryKeySelective(EasybuyUser record);

    int updateByPrimaryKey(EasybuyUser record);
}

3.在业务逻辑层写相关抽象方法

public interface UserService {

    EasybuyUser getUser(int uid);

    EasybuyUser getUser(String uname,String upwd);
}

4.在实现类实现相关业务逻辑,并调用数据访问层获取数据

@Service("userService")
public class UserServiceImpl implements UserService {
    //业务逻辑层需要调用数据访问层
    @Autowired
    private EasybuyUserMapper easybuyUserMapper;


    //根据id查询用户信息
    @Override
    public EasybuyUser getUser(int uid) {

        return easybuyUserMapper.selectByPrimaryKey(uid);
    }

    @Override
    public EasybuyUser getUser(String uname, String upwd) {
        upwd = MD5Util.MD5(upwd);
        return easybuyUserMapper.selectByUnameAndPwd(uname,upwd);
    }
}

数据库中密码设计MD5的加密因此需要写方法类并调用

public class MD5Util {

    /**
     * MD5 32位加密
     * @param sourceStr
     * @return
     */
    public static String MD5(String sourceStr) {
        String result = "";//通过result返回结果值
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");//1.初始化MessageDigest信息摘要对象,并指定为MD5不分大小写都可以
            md.update(sourceStr.getBytes());//2.传入需要计算的字符串更新摘要信息,传入的为字节数组byte[],将字符串转换为字节数组使用getBytes()方法完成
            byte b[] = md.digest();//3.计算信息摘要digest()方法,返回值为字节数组

            int i;//定义整型
            //声明StringBuffer对象
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];//将首个元素赋值给i
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");//前面补0
                buf.append(Integer.toHexString(i));//转换成16进制编码
            }
            result = buf.toString();//转换成字符串
//            System.out.println("MD5(" + sourceStr + ",32) = " + result);//输出32位16进制字符串
//            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));//输出16位16进制字符串
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;//返回结果
    }

5.前端页面


<html>
<head>
    <meta charset="utf-8">
    <title>title>
    <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
head>
<body>
<form class="container form-horizontal" id="" name=""
      action="/user/loginservice.do" method="post"
      onsubmit="return submitFrm();">

    <div class="form-group">
        <label for="uname">用户名:label>
        <input id="uname" name="uname" class="form-control" type="text"
               onblur="checkInputforReg(this.id,regUserName,'您输入的用户名格式不正确,用户名为xxx')"/>
        <span id="unameTip">span>
    div>

    <div class="form-group">
        <label for="upwd">密码:label>
        <input id="upwd" name="upwd" class="form-control" type="password"
               onblur="checkInputforReg(this.id,regPwd,'您输入的密码格式不正确,用户名为xxx')"/>
        <span id="upwdTip">span>
    div>

    <div class="form-group">
        <button type="submit">Loginbutton>
    div>
form>
body>
html>
<script>
    //正则表达式
    var regUserName=/^[a-z]\w{1,11}$/;
    var regPwd=/^\d{5,11}$/;

    function $(id){
        return document.getElementById(id);
    }

    //(元素的id,验证的正则表达式,错误提示信息)
    function checkInputforReg(id,reg,msg){
        var input=$(id);
        if(!reg.test(input.value)){
            $(id+"Tip").innerHTML=msg;
            $(id+"Tip").className="text-danger";
            return false;
        }
        else{
            $(id+"Tip").innerHTML="√ ok";
            $(id+"Tip").className="text-success";
            return true;
        }
    }

    function submitFrm(){
        if(checkInputforReg("uname",regUserName,'您输入的用户名格式不正确,用户名为xxx')&&
            checkInputforReg("upwd",regPwd,'您输入的密码格式不正确,用户名为xxx'))
        {
            return true;
        }
        else{
            return false;
        }
    }

script>


6.控制层

@Controller
@RequestMapping("/User")
public class userController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/get.do",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
    public @ResponseBody String getUser(@RequestParam(required = true) Integer uid){
        //1.取2.调3.转
        EasybuyUser user = userService.getUser(uid);
        return JSONObject.toJSONString(user);
    }

    @RequestMapping(value = "/login.do",method = RequestMethod.POST)
    public void login(@RequestParam(required = true)String uname,
                        @RequestParam(required = true)String upwd,
                        HttpSession session, HttpServletResponse response) throws IOException {
        //1.取参数

        //2.调用业务
        EasybuyUser user = userService.getUser(uname, upwd);
        if(user!=null){

            //存储在服务器端
            session.setAttribute("user",user);

            //存储在客户端  不安全
            Cookie cookie=new Cookie("userId",String.valueOf(user.getId()));
            Cookie cookie2=new Cookie("userName",user.getLoginname());
            cookie.setMaxAge(300);
            cookie2.setMaxAge(300);

            response.addCookie(cookie);
            response.addCookie(cookie2);

            response.sendRedirect("/index.jsp");

        }
        else {
            response.sendRedirect("/login.html");
        }


    }
	//目前基本上不这么写,不安全
    @RequestMapping("/index")
    public String userLoginForCookie(HttpServletRequest request,
                                     HttpServletResponse response,
                                     HttpSession session) throws IOException {
        Cookie[] cookies=request.getCookies();
        Integer uid=0;
        if(cookies!=null)
            for (Cookie cookie:cookies) {
                if("userId".equals(cookie.getName())){
                    uid=Integer.parseInt(cookie.getValue());
                    break;
                }
            }

        if(uid==0) {
            return "redirect:/login.html";
        }

        EasybuyUser user=userService.getUser(uid);
        if(user!=null){
            //记录登录状态 让后面访问的页面都知道我已登录
            // 将用户信息存放入session中
            // session对象存储在服务端
            session.setAttribute("user",user);
            return "redirect:/index.jsp";
        }
        else
        {
            return "redirect:/login.html";
        }

    }

    @RequestMapping("/logout")
    public String logOut(HttpSession session){
        session.invalidate();
        return "redirect:/index.jsp";
    }
}

你可能感兴趣的:(暑期实习)