Spring4+SpringMVC+Hibernate4+MySQL5项目搭建

一、准备jar包
(1)Spring4的所有jar包
(2)Hibernate的所有jar包
(3)c3p0的jar包
(4)MySQL的jar包
(5)jackson的所有jar包

二、新建package
Spring4+SpringMVC+Hibernate4+MySQL5项目搭建_第1张图片

三、新建db.properties

user=root
password=
jdbcUrl=jdbc:mysql:///ssh
driverClass=com.mysql.jdbc.Driver

四、修改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_3_1.xsd" id="WebApp_ID" version="3.1">
    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    
    <servlet>
        <servlet-name>springDispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>

    
    <servlet-mapping>
        <servlet-name>springDispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    <filter>
        <filter-name>SpringOpenSessionInViewFilterfilter-name>
        <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>SpringOpenSessionInViewFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

web-app>

五、新建springmvc.xml


<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"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        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.1.xsd">
    
    <context:component-scan base-package="com.dobeyue.spsh">
        <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:default-servlet-handler/>
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/">property>
        <property name="suffix" value=".jsp">property>
    bean>
    
    <mvc:annotation-driven/>

beans>

六、新建applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    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.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">
    
    <context:property-placeholder location="classpath:db.properties"/>
    
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${user}">property>
        <property name="password" value="${password}">property>
        <property name="jdbcUrl" value="${jdbcUrl}">property>
        <property name="driverClass" value="${driverClass}">property>
    bean>
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialectprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.format_sql">trueprop>
            props>
        property>
        <property name="packagesToScan" value="com.dobeyue.spsh">property>
    bean>
    
    <context:component-scan base-package="com.dobeyue.spsh" use-default-filters="false">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    context:component-scan>

    
    <aop:aspectj-autoproxy/>

    
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>

    
    <tx:annotation-driven transaction-manager="transactionManager"/>

beans>

七、类
User.java

package com.dobeyue.spsh.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.stereotype.Component;
@Table(name="users")
@Entity
@Component
public class User{
    private Integer id;
    @Email
    private String username;
    @NotEmpty
    private String password;

    public User() {
        // TODO Auto-generated constructor stub
    }
    @GeneratedValue
    @Id
    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;
    }
    public User(Integer id, String username, String password) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
    }
}

UserDao.java

package com.dobeyue.spsh.dao;

import com.dobeyue.spsh.entities.User;

public interface UserDao {
     public User findUser(User user);
}

UserDao.java

package com.dobeyue.spsh.daoImpl;


import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.dobeyue.spsh.dao.UserDao;
import com.dobeyue.spsh.entities.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Transactional(readOnly=true)
    public User findUser(User user) {
        return (User) sessionFactory.getCurrentSession()
                .createQuery("FROM User u WHERE u.username = ? AND u.password = ? ")
                .setString(0, user.getUsername()).setString(1, user.getPassword()).uniqueResult();
    }

}

UserHandler.java

package com.dobeyue.spsh.handler;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.dobeyue.spsh.entities.User;
import com.dobeyue.spsh.service.UserService;

@Controller("userHandler")
public class UserHandler {
    @Autowired
    private UserService userService;
    @RequestMapping("/index")
    public void index(){}
//  @ResponseBody
    @RequestMapping(value="/doLogin",method=RequestMethod.POST)
    public String login(@Valid @RequestParam("username") String username
            ,@RequestParam("password") String password,Map map,Model model,User user,BindingResult result){
//      User user = userService.findUser(new User(null, username, password));
        System.out.println(result);
        user = userService.findUser(user);
        if(user!=null){ 
            map.put("user", user);
            model.addAttribute("user", user);
            return "success";
        }else{
            map.put("tip", "帐号或者密码错误");
            return "success";
        }
    }
}

UserService.java

package com.dobeyue.spsh.service;

import com.dobeyue.spsh.entities.User;

public interface UserService {
    public User findUser(User user);
}

UserServiceImpl.java

package com.dobeyue.spsh.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dobeyue.spsh.dao.UserDao;
import com.dobeyue.spsh.entities.User;
import com.dobeyue.spsh.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User findUser(User user) {
        return userDao.findUser(user);
    }

}

八、新建index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh"content="0.1; url=index"/>
<title>Insert title heretitle>
head>
<body>
    <form action="doLogin" method="post" >
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <input type="submit"/>
    form>
body>
html>

九、新建success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
head>
<body>
    success
    ${user}
    ${user.username}
    ${user.password}
    ${tip}
    <form:errors path="*"/>
    <form:form action="doLogin" method="post" modelAttribute="user" >
        <form:input path="username"/>
        <form:input path="password"/>
        <input type="submit"/>
    form:form>
body>
html>

最后,运行即可。

你可能感兴趣的:(javaweb,spring,spring,mvc,mysql,hibernate)