欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

实习六 ssm实现登陆界面

程序员文章站 2024-01-15 23:34:46
...

先上效果图:
登陆界面
实习六 ssm实现登陆界面
主界面(简单一个模板而已)
实习六 ssm实现登陆界面
点了链接后的界面(没什么布局)
实习六 ssm实现登陆界面
接下来就是修改删除之类的
实习六 ssm实现登陆界面

结构如下
实习六 ssm实现登陆界面
实习六 ssm实现登陆界面
先写pom

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zhongruan</groupId>
  <artifactId>web_demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>web_demo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <!-- spring版本号 -->
    <spring.version>5.0.2.RELEASE</spring.version>
    <!-- mybatis版本号 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.version>
    <c3p0.version>0.9.5.2</c3p0.version>
    <taglibs.version>1.1.2</taglibs.version>
  </properties>

  <dependencies>
    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- 导入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>

    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- JSTL标签类 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>


    <!-- 数据连接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>${c3p0.version}</version>
    </dependency>

    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>${taglibs.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <!-- 导入servlet-api/jsp -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>
  <build>
    <finalName>web_demo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

再写配置文件(根据情况自己改一下)
db.properties(数据库)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/people_manage
jdbc.username=root
jdbc.password=1234

数据库自己建立
实习六 ssm实现登陆界面
spring-mvc.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"
       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
      ">

    <!-- 1.注解扫描位置-->
    <context:component-scan base-package="com.zhongruan.web_demo.controller" />

    <!-- 2.配置映射处理和适配器-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!-- 3.视图的解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
```xml
applicationContext.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"
       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/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 1.配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:properties/db.properties"/>

    <!-- 2.配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="2"/>
    </bean>

    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 扫描bean包 使用别名 -->
        <property name="typeAliasesPackage" value="com.zhongruan.web_demo"/>

        <!--配置加载映射文件 UserMapper.xml-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>

        <!--配置mybatis配置文件位置-->
        <!--        <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>-->

    </bean>

    <!-- 自动生成dao,mapper-->
    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.zhongruan.web_demo.dao"/>
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>



    <!--自动扫描-->
    <context:component-scan base-package="com.zhongruan.web_demo"/>


    <!-- 配置事务-->
    <!-- 5.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 6.开启事务注解-->
    <tx:annotation-driven/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_3_1.xsd"
         version="3.1">

  <!-- 配置加载类路径的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:spring/applicationContext.xml</param-value>
  </context-param>

  <!-- 配置监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>

  <!-- 解决中文乱码过滤器 -->
  <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>

  <!-- 前端控制器(加载classpath:spring-mvc.xml 服务器启动创建servlet) -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-mvc.xml</param-value>
    </init-param>
    <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

然后开始写功能
先写jsp
index.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/jsp/taglibs.jsp" %>

<html>
<body>
<h2>Hello World!</h2>
<a href="${basePath}/product/toList">产品管理系统</a>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/jsp/taglibs.jsp" %>


<html>
<head>
    <title>${basePath}</title>
</head>
<body>
<form style="width: 300px;margin: 200px auto 0;" method="post" action="${basePath}/testLogin">
    账号:<input type="text" name="username" value="${user.username}">
    <br>
    密码:<input type="password" name="password" value="${user.password}">
    <br>
    <input type="submit" value="登录">
    <br>
    <span style="color: red;">${msg}</span>
</form>
</body>
</html>

taglibs.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8"%>
<c:set var="basePath" value="${pageContext.request.contextPath}" />

product-list.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/jsp/taglibs.jsp" %>
<html>
<head>
    <title>产品管理界面</title>
</head>
<body>
<c:forEach var="item" items="${products}">
    <tr>
        <td>${item.id}</td>
        <td>${item.name}</td>
        <td>${item.desc}</td>
        <td><a href="${basePath}/product/toEdit?productId=${item.id}">修改</a> </td>
        <td><a href="#">删除</a> </td>
    </tr>
</c:forEach>
</body>
</html>

product-edit.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/jsp/taglibs.jsp" %>

<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="${basePath}/product/edit">
    <input type="text" name="id"  value="${product.id}" readonly="readonly">
    <input type="text" name="name" value="${product.name}">
    <input type="text" name="desc" value="${product.desc}">
    <input type="submit" value="保存修改">
    <span style="color: red;">${msg}</span>
</form>
</form>
</body>
</html>

补充下类
Controller
ProductController

package com.zhongruan.web_demo.controller;

import com.zhongruan.web_demo.dao.ProductDao;
import com.zhongruan.web_demo.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("product")
public class ProductController {
    @Autowired
    ProductDao productDao;

    @RequestMapping("/toList")
    public String toList(Model model)
    {
        List<Product> products = productDao.getProducts();
        model.addAttribute("products",products);
        return "product-list";
    }

    @RequestMapping("/toEdit")
    public String toEdit(Model model, @RequestParam("productId") Integer id)
    {
        Product product= productDao.getProductById(id);
        model.addAttribute("product",product);
        return "product-edit";
    }

    @RequestMapping("/edit")
    public String edit(Model model,Product product)
    {
        System.out.println(product);
        productDao.updateProduct(product);
        model.addAttribute(product);
        model.addAttribute("msg","修改成功");
        return "index";
    }

}

UserController

package com.zhongruan.web_demo.controller;

import com.zhongruan.web_demo.dao.UserDao;
import com.zhongruan.web_demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    UserDao userDao;

    @RequestMapping("/demo")
    public String toDemo(Model model) {
        model.addAttribute("users", userDao.getUsers());
        return "user-list";
    }

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String Login(Model model, HttpServletRequest request, User user) {
        User rightUser = userDao.getUserById2(user.getUsername());
        //判断是否存在用户
        if (rightUser != null) {
            model.addAttribute("msg", "不存在该用户");
            return "login";
        }
        if (rightUser.getPassword() != user.getPassword()) {
            model.addAttribute("msg", "账号或密码错误");
            return "login";
        }
        HttpSession session = request.getSession();
        session.setAttribute("user", rightUser);
        return "index";
    }

    /**
     * mybatis增删改查方法测试
     *
     * @param model
     * @return
     */
    @RequestMapping("/test")
    public String test(Model model) {
        //model.addAttribute()
        User user = new User();
        user.setUsername("tusuzer2");
        user.setPassword("123");
        userDao.addUser(user);
        System.out.println(user);
        user.setPassword("456");
        System.out.println(userDao.updateUser(user));
        return "login";
    }

    @RequestMapping("/testLogin")
    public String loginTest(Model model,@RequestParam("username") String name, @RequestParam("password") String password) {

        User user=userDao.getUserByName(name,password);
        if (user == null) {
            model.addAttribute("msg", "不存在该用户");
            return "login";
        }
        if (!user.getPassword().equals(password)) {
            model.addAttribute("msg", "账号或密码错误");
            return "login";
        }
        return "index";
    }
}

entity
User

package com.zhongruan.web_demo.entity;

public class User {
    private Integer id;
    private String username;
    private String password;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

Product

package com.zhongruan.web_demo.entity;

public class Product {
    private Integer id;
    private String name;
    private String desc;


    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }

}

dao层和Mapper
UserDao

package com.zhongruan.web_demo.dao;

import com.zhongruan.web_demo.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserDao {

    List<User> getUsers();

    User getUserByName(@Param("name") String username, @Param("pwd") String password);

    User getUserById2(String username);

    int updateUser(User user);

    int addUser(User user);

    int deleteUser(User user);
}

ProductDao

package com.zhongruan.web_demo.dao;

import com.zhongruan.web_demo.entity.Product;

import java.util.List;

public interface ProductDao {
    List<Product> getProducts();

    Product getProductById(Integer id);

    int updateProduct(Product product);

}

UserMapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zhongruan.web_demo.dao.UserDao">
    <insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
        insert into tb_user (username, password) values (#{username},#{password});
    </insert>
    <update id="updateUser">
        update tb_user
        <set>
            <if test="username != null">
                username = #{username},
            </if>
            <if test="password != null">
                password = #{password},
            </if>
        </set>
        where username = #{username}
    </update>
    <delete id="deleteUser">
        delete from tb_user where username = #{username}
    </delete>

    <select id="getUsers" resultType="User">
        select * from tb_user
    </select>
    <select id="getUserByName" resultType="User">
        select * from tb_user where  username= #{name} and password = #{pwd};
    </select>
    <select id="getUserById2" resultType="User">
        select * from tb_user where username =#{name}
    </select>

</mapper>

ProductMapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zhongruan.web_demo.dao.ProductDao">

    <select id="getProducts" resultType="Product">
        select * from tb_product
    </select>

    <select id="getProductById" resultType="Product">
        select * from tb_product where id = #{praram1}
    </select>

    <update id="updateProduct" parameterType="Product">
        update tb_product set `name`=#{name},`desc`=#{desc} where id = #{id}
    </update>
</mapper>
相关标签: ssm java