Så har jeg lige bikset noget sammen, som du måske kan bruge.
Jeg har sat noget log4j op, som jeg har brugt til at teste det med. Du kan bare fjerne alt med logger.XXXX hvis du ikke skal bruge det. Hvis du gerne vil have lidt logning i din application, kan du se mere her:
http://logging.apache.org/Det har følgende mappestruktur:
register (mappe i roden (/))
- adduser.jsp (fil i register mappen)
- usersaved.jsp (fil i register mappen)
- WEB-INF (mappe i register mappen)
--- web.xml (fil i register/WEB-INF mappen)
--- classes (mappe i register/WEB-INF)
--- lib (mappe i register/WEB-INF)
------ mysql-connector-java-3.1.8-bin.jar (fil i register/WEB-INF/lib, kan hentes her:
http://www.mysql.com/products/connector/j/ )
------ log4j-1.2.8.jar (fil i register/WEB-INF/lib, kan hentes her:
http://logging.apache.org/log4j/1.2/download.html )
------ dk (mappe i register/WEB-INF/classes)
--------- westsworld (mappe i register/WEB-INF/classes/dk)
------------ udvikleren (mappe i register/WEB-INF/classes/dk/westsworld)
--------------- register (mappe i register/WEB-INF/classes/dk/westsworld/udvikleren)
------------------ AddUser.java (fil i register/WEB-INF/classes/dk/westsworld/udvikleren)
------------------ dao (mappe i register/WEB-INF/classes/dk/westsworld/udvikleren/register)
--------------------- UserDAO.java (fil i register/WEB-INF/classes/dk/westsworld/udvikleren/register/dao)
------------------ model (mappe i register/WEB-INF/classes/dk/westsworld/udvikleren/register)
--------------------- User.java (fil i register/WEB-INF/classes/dk/westsworld/udvikleren/register/model)
Strukturen er lidt stor, når man lige skal indtaste den, men du må sige til hvis det giver problemer.
Derudover er der indholdet i filerne.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="register">
<servlet>
<servlet-name>AddUser</servlet-name>
<servlet-class>dk.westsworld.udvikleren.register.AddUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddUser</servlet-name>
<url-pattern>/AddUser.do</url-pattern>
</servlet-mapping>
</web-app>
adduser.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html>
<head>
<title>Add a User</title>
<style type="text/css">
body, html, table {
font-family: Verdana, Arial, Sans-serif;
font-size: 12px;
}
div.error {
background-color: red;
border: 1px solid #870000;
}
</style>
</head>
<body>
<c:if test="${param.error}">
<div class="error">
An error occured while trying to create the user, please try again.
</div>
</c:if>
<form method="post" action="AddUser.do">
Name:<br/>
<input type="text" name="name" value="<c:if test='${name}'><c:out value='${name}'/></c:if>" /><br/>
Phone:<br/>
<input type="text" name="phone" value="<c:if test='${phone}'><c:out value='${phone}'/></c:if>" /><br/>
Address:<br/>
<input type="text" name="address" value="<c:if test='${address}'><c:out value='${address}'/></c:if>" /><br/>
Remark:<br/>
<textarea rows="10" cols="40" name="remark"><c:if test="${remark}"><c:out value="${remark}"/></c:if></textarea><br/>
<input type="submit" value="Save" />
</form>
</body>
</html>
usersaved.jsp
<html>
<head>
<title>info</title>
</head>
<body>
The user has been saved!
</body>
</html>
AddUser.java
package dk.westsworld.udvikleren.register;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import org.apache.log4j.Logger;
import dk.westsworld.udvikleren.register.dao.UserDAO;
import dk.westsworld.udvikleren.register.model.User;
public class AddUser extends HttpServlet {
// Used for logging.
private static final Logger logger = Logger.getLogger(AddUser.class);
// The DAO file (Data Access Object), used for saving the user to the database.
private UserDAO userDAO = new UserDAO();
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean userSaved = false;
String name = request.getParameter("name");
String phone = request.getParameter("phone");
String address = request.getParameter("address");
String remark = request.getParameter("remark");
// logs some information about the register attempt.
logger.debug("name: "+name);
logger.debug("phone: "+phone);
logger.debug("address: "+address);
logger.debug("remark: "+remark);
// tests if the "needed" information is set.
if( name != null && phone != null && address != null ) {
// we create a user object.
User user = new User(name,phone,address);
user.setRemark(remark);
// we try and save the user
userSaved = userDAO.save(user);
}
// if the user was saved, we send him to a "user has been saved"-page.
if( userSaved ) {
response.sendRedirect("usersaved.jsp");
}
// else we send the user back to the form page, with the data entered.
else {
request.setAttribute("name", name);
request.setAttribute("phone", phone);
request.setAttribute("address", address);
request.setAttribute("remark", remark);
// the actual redirect.
request.getRequestDispatcher("AddUser.do").forward(request,response);
}
}
}
UserDAO.java
package dk.westsworld.udvikleren.register.dao;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.log4j.Logger;
import dk.westsworld.udvikleren.register.model.User;
public class UserDAO {
private static final Logger logger = Logger.getLogger(UserDAO.class);
/**
* Creates a connection to the database.
* @return a connection to the database, else null.
*/
private Connection getConnection() {
Connection connection = null;
try {
// we load the database driver
Class.forName("com.mysql.jdbc.Driver");
// we try to establish a connection to the database.
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/udv_register","root","12345");
}
catch(ClassNotFoundException cnfe) {
logger.error(cnfe);
}
catch(SQLException sqle) {
logger.error("Error establising a connection to the database", sqle);
}
return connection;
}
/**
* Saves the given user to the database.
* @param user the user to save to the database.
* @return true if the user was saved, else false.
*/
public boolean save(User user) {
boolean saved = false;
Connection connection = getConnection();
if( connection != null ) {
// just for tests!
if( user != null ) {
String sql = "insert into user(name,phone,address,remark) values('"+user.getName()+"','"+user.getPhone()+"','"+user.getAddress()+"','"+user.getRemark()+"')";
// debugs the sql sentance...
logger.debug("sql is: "+sql);
try {
// saves the user.
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
saved = true;
}
catch(SQLException sqle) {
logger.error("error trying to save the user: "+sqle);
}
finally {
try {
connection.close();
}
catch(SQLException sqle) {
logger.debug("Error closing the connection: "+sqle);
}
}
}
}
return saved;
}
}
Husk at rette oplysninger til database forbindelsen i getConnection() metoden (i UserDAO.java).
User.java
package dk.westsworld.udvikleren.register.model;
public class User {
private String name;
private String phone;
private String address;
private String remark;
public User( String name, String phone, String address ) {
this.name = name;
this.phone = phone;
this.address = address;
}
public String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
public String getAddress() {
return this.address;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getRemark() {
return this.remark;
}
}
tabellen vi skal bruge i systemet:
create table user(
id int primary key auto_increment,
name varchar(255) not null,
phone varchar(50) not null,
address varchar(255) not null,
remark text
);
For at state hele processen, skal du starte din server, og på ind på
http://localhost:8080/register/adduser.jsp (min server kører på port 8080, hvis din ikke gør, så husk at fjerne den)
Dette setup er testet på en resin server (
http://www.caucho.com/ ).