IntelliJ IDEA 2016配置SpringMVC及简单开发


这里最好是用Download,试过Use library,觉得少些东西。如果下载不了。可以试试设置http proxy,选择auto-detect proxy settings。下载完成后,项目创建成功,需要配置Tomcat。点击右上角Edit Configurations,再点击+ Add New Configuration,选择Tomcat Server-Local,弹出对话框:


在新对话框中,点击Configure,点击+配置Tomcat路径。然后再点击右下角Fix或者Deployment的+添加Artifact。配置就完成了。点击运行,如果不成功,右键项目名,Open Module Settings,查看Problems,Fix即可。


我们可以在src中开发自己的主页,建个包名,再建个Java class:

 

package com.zhang.javaweb.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Created by Administrator on 2016/1/8 0008.
 */
@Controller
public class MainController {

    @RequestMapping(value = "main.form", method = RequestMethod.GET)
    public String mainPage(ModelMap map, HttpServletRequest request, HttpServletResponse response) {

        map.addAttribute("title", "我的网站");
return "main";
}
}

 

 

同时在web/WEB-INFO/dispatcher-servlet.xml中配置:


base-package是包名,prefix的值是上文中返回的main页面所在的文件夹,suffix的值是main的后缀名,即返回的是web/pages/main.jsp。

在web/WEB-INFO/web.xml中,


由于这句话,我们的网页必须是以.form结尾,如iava文件中的@RequestMapping(value = "main.form", ...),网址是http://localhost:8080/main.form。不想以.form结尾,可以将*.form换成/,并在java文件开始@Controller下面加上@RequestMapping("/")。如果想将http://localhost:8080也换为自己的页面,只需删除web文件夹中的index.jsp,在java文件中:

 

@Controller
@RequestMapping("/")public class HelloController {
@RequestMapping(method = RequestMethod.GET)
    public String printWelcome(ModelMap map) {
        map.addAttribute("message", "Hello World");
map.put("content", "This is my first spring mvc app");
        return "hello";
}

}

hello.jsp在web/pages中,

 

 

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2016/1/9 0009
  Time: 15:54
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" session="false" %>
<html>
<head>
    <title>${message}</title>
</head>
<body>
Hello IDEA Spring
 <h1>${message}</h1>
${content}</body>
</html>

运行结果如下:

 



---------------------------------------------------------------------------------

路径参数:

请求参数写在路径中,实现伪静态。

 

//路径参数
@RequestMapping(value = "/page/{name}/{age}", method = RequestMethod.GET)
public String getName(ModelMap map, @PathVariable("name") String name, @PathVariable("age") int age) {

    map.addAttribute("name",name);
map.addAttribute("age",age);
    return "name";
}

name.jsp

 

 

<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
 <div>
名字:${name}<br>
年龄:${age}</div>
</body>
</html>

在网址输入localhost:8080/page/xiaoming/20

 

显示如下:


----------------------------------------------------------------------------------------------------------------------------------------------

Url参数:

 

//URL参数
@RequestMapping(value = "/page",method = RequestMethod.GET)
public String result(ModelMap map, @RequestParam String name,@RequestParam int age){
    map.addAttribute("name",name);
map.addAttribute("age",age);
    return "name";
}

和表单提交方式一样http://localhost:8080/page?name=xiao&age=20

 


我们可以用Html表单把数据传入,再建一个页面:

 

@RequestMapping(value = "/adduser",method = RequestMethod.GET)
    public String addUser(ModelMap map){
return "add_user";
}

add_user.jsp

 

 

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@page pageEncoding="utf-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
<%--//HTML表单--%>
<form action="page" method="get">
名字:<input type="text" name="name"><br>
年龄:<input type="number" name="age"><br>
    <input type="submit">
</form>
</body>
</html>

表单中的method和Url的Metho方法要一致。

 



SpringMVC也为我们提供了表单,可以在创建时就为它提供一些默认值。

 

<%--//SpringMVC表单--%>
<form:form action="result" method="get" modelAttribute="user">
    名字:<form:input path="name"/><br>
年龄:<form:input path="age"/><br>
    <input type="submit">
</form:form>

modeAttribute的属性是我们为其提供的值,这里是一个java bean:

 

 

public class User {

    private String name;
    private int age;
    public String getName() {
        return name;
}

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

    public int getAge() {
        return age;
}

    public void setAge(int age) {
        this.age = age;
}
}

修改一下adduser页面:

 

 

@RequestMapping(value = "/adduser",method = RequestMethod.GET)
public String addUser(ModelMap map){

    User u = new User();
u.setName("xiao");
u.setAge(20);
map.addAttribute("user",u);
    return "add_user";
}

打开http://localhost:8080/adduser,页面的input中就会有默认值存在。

 


---------------------------------------------------------------------------------------------------------------------

配置Hibernate:

用xampp模拟服务器,打开Apache和MySQL,在phpmyadmin中创建一个user数据库。点击IDEA右侧Database-+-Data Source - MySQL,在对话框填入Database、User、Password,成功后页面如下:


数据连接成功后配置Hibernate框架,右键项目-Add Frameworks Support 勾选Hibernate


点击OK:


OK之后会生成Entity实体:

 

import javax.persistence.*;
/**
 * Created by Administrator on 2016/1/10 0010.
 */
@Entity
@Table(name = "users", schema = "mydb", catalog = "")
public class UsersEntity {
    private long id;
    private String name;
    private byte age;
@Id
    @Column(name = "id")
    public long getId() {
        return id;
}

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

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
}

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

    @Basic
    @Column(name = "age")
    public byte getAge() {
        return age;
}

    public void setAge(byte age) {
        this.age = age;
}

    @Override
public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
UsersEntity that = (UsersEntity) o;
        if (id != that.id) return false;
        if (age != that.age) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;
        return true;
}

    @Override
public int hashCode() {
        int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (int) age;
        return result;
}
}

可能需要配置hibernate.cfg.xml,注意这个文件需要放在web/WEB-INFO/classes/里面。

 

 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        <mapping class="com.zhang.myjavaweb.db.entities.UsersEntity"/>
<!-- DB schema will be updated if needed -->
        <!-- <property name="hbm2ddl.auto">update</property> -->
</session-factory>
</hibernate-configuration>

org.hibernate.dialect.MySQLDialect可能没有,需要下载mysql-connector-java-5.1.38-bin.jar放在libs里面,并在项目添加一下。同时Hibernate为自动生成一个main java文件的数据库连接方法:

 

 

public class main {
    private static final SessionFactory ourSessionFactory;
    private static final ServiceRegistry serviceRegistry;
    static {
        try {
            Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
}
    }

    public static Session getSession() throws HibernateException {
        return ourSessionFactory.openSession();
}

//    public static void main(final String[] args) throws Exception {
//        final Session session = getSession();
//        try {
//            System.out.println("querying all the managed entities...");
//            final Map metadataMap = session.getSessionFactory().getAllClassMetadata();
//            for (Object key : metadataMap.keySet()) {
//                final ClassMetadata classMetadata = (ClassMetadata) metadataMap.get(key);
//                final String entityName = classMetadata.getEntityName();
//                final Query query = session.createQuery("from " + entityName);
//                System.out.println("executing: " + query.getQueryString());
//                for (Object o : query.list()) {
//                    System.out.println("  " + o);
//                }
//            }
//        } finally {
//            session.close();
//        }
//    }
}

下面注释的内容用不到,可以用来参考一下。为方便理解我将main修改为了DbConnection。

 

再在Controller里面建一个页面:

 

@RequestMapping(value = "users",method = RequestMethod.GET)
public String listUsers(ModelMap map){

    Session session = DbConnection.getSession();
List<User> list = session.createCriteria(UsersEntity.class).addOrder(Order.asc("id")).list();//Order.asc("id")按照id的正序排列   Order.desc 反序
map.addAttribute("users",list);
session.close();
    return "users";
}

users.jsp如下:

 

 

<%@ page import="com.jikexueyuan.myjavawebfor14.db.entities.UsersEntity" %>
<%@ page import="java.util.List" %>
<%@page pageEncoding="utf-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<ol>
<%for (UsersEntity e:(List<UsersEntity>)request.getAttribute("users")){%>
<li>名字:<%out.print(e.getName());%>,年龄:<%out.print(e.getAge());%></li>
<%}%>
</ol>
<a href="adduser">添加用户</a>
</body>
</html>

运行:

 


在此我添加了一个“添加用户”用来演示向数据库中加入数据,点击“添加用户”会跳转到adduser表单页面:

 

@RequestMapping(value = "/adduser",method = RequestMethod.GET)
public String addUser(ModelMap map){

    //可添加默认,也可不加
User u = new User();
u.setName("name");
u.setAge(0);
map.addAttribute("user",u);
    return "add_user";
}

add_user.jsp还是前面的表单

 

 

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@page pageEncoding="utf-8" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>添加用户</title>
</head>
<body>
<%--//HTML表单--%>
<%--<form action="page" method="get">--%>
    <%--名字:<input type="text" name="name"><br>--%>
    <%--年龄:<input type="number" name="age"><br>--%>
    <%--<input type="submit">--%>
<%--</form>--%>
<%--//SpringMVC表单--%>
<form:form action="result" method="get" modelAttribute="user">
    名字:<form:input path="name"/><br>
年龄:<form:input path="age"/><br>
    <input type="submit">
</form:form>

</body>
</html>

该表单将数据提交给result,我们在result中实现向数据库插入数据:

 

 

@RequestMapping(value = "/result",method = RequestMethod.GET)
public String result(ModelMap map, @RequestParam String name, @RequestParam int age, HttpServletRequest request, HttpServletResponse response){
    map.addAttribute("name",name);
map.addAttribute("age",age);
Session session = DbConnection.getSession();
Transaction transaction = session.beginTransaction();
UsersEntity ue = new UsersEntity();
ue.setName(name);
ue.setAge((byte) age);
session.save(ue);
transaction.commit();
session.close();
    return "result";
}

result.jsp

 

 

<%@ page contentType="text/html;charset=UTF-8"%>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
名字:${name}<br>
年龄:${age}<%
response.sendRedirect("users");
%>
</body>
</html>

可以看到result页面直接跳转到了users页面,既不会显示result页面,只用于中间操作。

 

在http://localhost:8080/adduser页面添加用户,点击提交,会在http://localhost:8080/users页面看到新的users数据,同时查看phpmyadmin的数据库,也可看到加入了新数据。


 

posted @ 2016-12-18 02:22  changchou  阅读(777)  评论(0编辑  收藏  举报