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

ssm框架模糊查询和中文

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

ssm框架模糊查询和中文

主要是实现模糊查询和新增用户时添加中文字符

首先结构如下
ssm框架模糊查询和中文
ssm框架模糊查询和中文

User

package com.zhongruan.bean;

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

    public int getId() {
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}

UserController

package com.zhongruan.controller;

import com.github.pagehelper.PageInfo;
import com.zhongruan.bean.User;
import com.zhongruan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(@RequestParam(defaultValue ="1") int pageNum, @RequestParam(defaultValue ="5") int size, String searchname, HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        String username=(String) session.getAttribute("username");
//        if (username==null){
//            modelAndView.setViewName("failure.jsp");
//            return  modelAndView;
//        }
        if (searchname!=null){
            session.setAttribute("searchname",searchname);
        }else {
            searchname=(String) session.getAttribute("searchname");
        }
        List<User> users = userService.findAll(pageNum, size,searchname);
        PageInfo<User> pageInfo=new PageInfo<>(users);

        modelAndView.setViewName("allUser.jsp");
        modelAndView.addObject("pageInfo", pageInfo);
        return modelAndView;
    }

    @RequestMapping("/login.do")
    public String login(User user,HttpSession session) {
        Boolean flag = userService.login(user.getUsername(), user.getPassword());
        if (flag) {
            session.setAttribute("username",user.getUsername());
            return "redirect:/findAll.do";
        } else {
            return "failure.jsp";
        }
    }

    @RequestMapping("/delete.do")
    public String deleteById(int id) {
        userService.deleteById(id);
        return "redirect:/findAll.do";
    }

    @RequestMapping("/addUser.do")
    public String addById(User user) {
        userService.addById(user);
        return "redirect:/findAll.do";
    }

    @RequestMapping("/update.do")
    public String update(User user) {
        userService.updateById(user);
        return "redirect:/findAll.do";
    }

    @RequestMapping("/toupdate.do")
    public ModelAndView toupdate(int id) {
    User user =userService.findById(id);
    ModelAndView mv =new ModelAndView();
    mv.addObject("user",user);
    mv.setViewName("updateUser.jsp");
    return mv;
    }
}

IUserDao

package com.zhongruan.dao;


import com.zhongruan.bean.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface IUserDao {
    List<User> findAll(@Param("searchname")String searchname);
    User selectByUserName(String name);
    void  deleteById(int id);
    void  addById(User user);
    void updateById(User user);
    User findById(int id);
}

LoginFilter

package com.zhongruan.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        HttpSession session=request.getSession();
        if (session.getAttribute("username")==null&&
                request.getRequestURI().indexOf("/login.do")==-1){
            response.sendRedirect("index.jsp");
        }else {
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}

UserService

package com.zhongruan.service.iml;

import com.github.pagehelper.PageHelper;
import com.zhongruan.bean.User;
import com.zhongruan.dao.IUserDao;
import com.zhongruan.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {
    @Autowired
    private IUserDao userDao;

    @Override
    public List<User> findAll(int pageNum,int size,String searchname) {
        PageHelper.startPage(pageNum,size);
        return userDao.findAll(searchname);
    }

    @Override
    public Boolean login(String username, String password) {
        User user = userDao.selectByUserName(username);
        if (user != null && password.equals(user.getPassword())) {
            return true;
        }
        return false;
    }

    @Override
    public void deleteById(int id) {
        userDao.deleteById(id);
    }

    @Override
    public void addById(User user) {
        userDao.addById(user);
    }

    @Override
    public void updateById(User user) {
        userDao.updateById(user);
    }

    @Override
    public User findById(int id) {
       return userDao.findById(id);
    }
}

IUserService

package com.zhongruan.service;

import com.zhongruan.bean.User;

import java.util.List;

public interface IUserService {
    List<User> findAll(int pageNum,int size,String searchname);

    Boolean login(String username, String password);
    void deleteById(int id);

    void addById(User user);

    void  updateById(User user);
    User findById(int id);
}

resoueces包文件如下

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-4.3.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    <!-- 1.配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath: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.bean"></property>

        <!--配置加载映射文件 UserMapper.xml-->
      <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            <prop key="helperDialect">mysql</prop>
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>

        </property>


    </bean>

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



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


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

</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zjgm
jdbc.username=root
jdbc.password=123456

Log4j.properties

# Global logging configuration
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

Usermapper1.xml

<?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.dao.IUserDao">

<select id="findAll" resultType="com.zhongruan.bean.User" parameterType="String">
    select * from  tb_user
    <where>
        <if test="searchname!=null">
            username like "%"#{searchname}"%"
        </if>
    </where>
</select>

<select id="selectByUserName" resultType="com.zhongruan.bean.User">
    select * from  tb_user where username=#{username}
</select>

<select id="deleteById"  parameterType="int">
    delete from tb_user where id=#{id}
</select>

    <select id="updateById" parameterType="com.zhongruan.bean.User">
        update tb_user set username=#{username},password=#{password} where id=#{id}
    </select>

    <select id="addById" parameterType="com.zhongruan.bean.User">
      insert into tb_user (username,password) values (#{username},#{password})
    </select>

    <select id="findById" parameterType="int" resultType="com.zhongruan.bean.User">
        select * from tb_user where id=#{id}
    </select>
</mapper>

spring-mc-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:mvc="http://www.springframework.org/schema/mvc"
       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-4.3.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.3.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!-- 1.注解扫描位置-->
    <context:component-scan base-package="com.zhongruan.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">
    </bean>
</beans>

addUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>新增用户</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background: url(images/153_140416090512_2.jpg)">
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于servlet+jsp框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增用户</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="/addUser.do"
              method="post">
        用户姓名:<input type="text" name="username"><br><br><br>
        用户密码:<input type="text" name="password"><br><br><br>
        <input type="submit" value="添加" >
    </form>

</div>

allUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>user列表</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background: url(images/153_140416090512_2.jpg);background-size: 100%">
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于servlet+jsp框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>用户列表 —— 显示所有用户</small>
                </h1>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 column">
            <a class="btn btn-primary" href="addUser.jsp">新增</a>
        </div>
        <form action="/findAll.do" method="post">
            <input name="searchname" type="text">
            <input type="submit" value="搜索">
        </form>
    </div>
    <div class="row clearfix">
        <div class="col-md-12 column">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>id</th>
                    <th>用户名</th>
                    <th>密码</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:forEach var="user" items="${pageInfo.list}">
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.username}</td>
                        <td>${user.password}</td>
                        <td><a href="/delete.do?id=${user.id}">删除</a>|
                            <a href="/toupdate.do?id=${user.id}">修改</a></td>
                    </tr>
                </c:forEach>

                </tbody>
            </table>
        </div>
    </div>
    < <div>
    <a href="/findAll.do?pageNum=1&size=5">首页</a>

        <a href="/findAll.do?pageNum=${pageInfo.pageNum-1}&size=5">上一页</a>
    <c:forEach begin="1" end="${pageInfo.pages}" var="i">
        <a href="/findAll.do?pageNum=${i}&size=5">${i}</a>
    </c:forEach>
        <a href="/findAll.do?pageNum=${pageInfo.pageNum+1}&size=5">下一页</a>

    <a href="/findAll.do?pageNum=${pageInfo.pages}&size=5">尾页</a>
</div>
</div>

failure.jsp

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/10/14 0014
  Time: 10:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>失败</title>
</head>
<body>
登录失败
</body>
</html>

index.xml

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>登录</title>
    <meta name="description" content="登录界面">
    <meta name="keywords" content="登录界面">
    <link href="" rel="stylesheet">
    <style>
        body,p,div,ul,li,h1,h2,h3,h4,h5,h6{
            margin:0;
            padding: 0;
        }
        body{
            background: #E9E9E9;
        }
        #login{
            width: 400px;
            height: 250px;
            background: #FFF;
            margin:200px auto;
            position: relative;
        }
        #login h1{
            text-align:center;
            position:absolute;
            left:120px;
            top:-40px;
            font-size:21px;
        }
        #login form p{
            text-align: center;
        }
        #user{
            background:url(images/user.png) rgba(0,0,0,.1) no-repeat;
            width: 200px;
            height: 30px;
            border:solid #ccc 1px;
            border-radius: 3px;
            padding-left: 32px;
            margin-top: 50px;
            margin-bottom: 30px;
        }
        #pwd{
            background: url(images/pwd.png) rgba(0,0,0,.1) no-repeat;
            width: 200px;
            height: 30px;
            border:solid #ccc 1px;
            border-radius: 3px;
            padding-left: 32px;
            margin-bottom: 30px;
        }
        #submit{
            width: 232px;
            height: 30px;
            background: rgba(0,0,0,.1);
            border:solid #ccc 1px;
            border-radius: 3px;
        }
        #submit:hover{
            cursor: pointer;
            background:#D8D8D8;
        }
    </style>
</head>
<body>
<div id="login">
    <h1>登录管理</h1>
    <form action="/login.do" method="post">
        <p><input type="text" name="username" id="user" placeholder="用户名"></p>
        <p><input type="password" name="password" id="pwd" placeholder="密码"></p>
        <p><input type="submit" id="submit" value="登录"></p>
    </form>
</div>
<div style="text-align:center;">
    <p>更多模板:<a href="http://www.mycodes.net/" target="_blank">源码之家</a></p>
</div>
</body>
</html>

updateUser.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" isELIgnored="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<html>
<head>
    <title>新增用户</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- 引入 Bootstrap -->
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background: url(images/153_140416090512_2.jpg);background-size: 100%">
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    基于servlet+jsp框架的管理系统:简单实现增、删、改、查。
                </h1>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>更新用户</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="/update.do"
              method="post">
       <input type="hidden" name="id" value="${user.id}"><br><br><br>
        用户姓名:<input type="text" name="username" value="${user.username}"><br><br><br>
        用户密码:<input type="text" name="password" value="${user.password}"><br><br><br>
        <input type="submit" value="更新" >
    </form>

</div>

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">

  <display-name>Archetype Created Web Application</display-name>

  <!-- 配置加载类路径的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*: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>

  <!-- 前端控制器(加载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-mvc.xml</param-value>
    </init-param>
    <!-- 服务器启动的时候,让DispatcherServlet对象创建 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
<filter>
  <filter-name>LoginFilter</filter-name>
  <filter-class>com.zhongruan.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>LoginFilter</filter-name>
  <url-pattern>*.do</url-pattern>
</filter-mapping>
  <!-- 解决中文乱码过滤器 -->
  <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>

最后运行一下
结果除了实现基本的增删改,模糊查询,中文字符
ssm框架模糊查询和中文
ssm框架模糊查询和中文