Web International Awards

payday loan

25

AUG 2010 0

Building a live news blogging system in JSP [II]

Tutorial app preview

Last week I started building a live news blogging system using JSP. This is a follow up tutorial I've decided to do after seeing the success of the previous series, which described how to build the same web application using php as backend.

Adding news to the database

In today's part I am going to code the JSP files needed to add content to the database. The same functionality has already been developed using PHP in the third part of the original tutorial series located over here. The PHP version contained a function that was used to generate a select field into the add news form which would contain all available news categories. Differently, I've chosen not to include such a feature in a JSP function. Instead, I've added it directly into the HTML template. Not so fancy, but it works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<form action="addnews.jsp" method="post" accept-charset="utf-8" id="form-overlay">
	<fieldset>
		<label for="title">Title : </label>
		<input type="text" name="title" value="" id="title" class="all-rounded"/>
		<label for="formcategory">Category :</label>
		<select name="formcategory" id="formcategory" length="1">
			<% 						
			st = new StringTokenizer(categories,"-");
			query = "SELECT name FROM Categories WHERE id>0 ORDER BY name ASC";
			rs = statement.executeQuery(query);
			count = 0;
				while (rs.next()) 
				{
					count++;
					String name = rs.getString("name");
					if(count==1) { %> <option selected="selected" value="<%=name%>"><%=name%></option> <% }
					else { %> <option value="<%=name%>"><%=name%></option> <% }
				}
			if(count==0) { %> <option value="none">none</option> <% }
			%>
		</select>
		<label for="body">Body text :</label>
		<textarea name="body" rows="8" cols="40" class="all-rounded"></textarea>
		<input type="submit" name="submit" value="Add news" id="submit" class="submit all-rounded" />
	</fieldset>
</form>

As you've seen in the previous part, the code on lines 8 to 10 is used to create a SQL query and run it. Lines 11/19 check if the SQL query returned an empty result. If yes, a default news category is created as the unique option; current case: none. If there's at least one category in the database, the code between line 12 and 17 gets the names of each category and adds each of them to the select field. The first category that's found is also pre-selected.

Processing the add news form

The form used to insert news in the database needs to be processed. The script is pretty straightforward, especially because I've already shown basic SQL queries in JSP just above ( or in the previous article in the series ). The first line of the script that processes the form is the usual line that imports all required libraries. All the following lines up to line 18 are used to create and instantiate the resources required to perform different operations on the mySQL database. Here's the full code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<%@ page import="java.sql.*" import="java.util.*" session="true" import="Javax.servlet.http.*" import="java.security.*" %>
 
<%
 
	String database = "lab8";
	String user = "root";
	String pass = "thebeastlocal";
	String table = "News";
 
	String connectionURL = "jdbc:mysql://localhost:3306/"+database+"?user="+user+";password="+pass;
	Connection connection = null;
	Statement statement = null;
	Statement update = null;
	ResultSet rs = null;
 
	Class.forName("com.mysql.jdbc.Driver").newInstance();
	connection = DriverManager.getConnection(connectionURL,user,pass);
	statement = connection.createStatement();
 
	if(session.getAttribute("loggedin")!=null)
	{
		String title = "";
		String formcategory = "";
		String body = "";
		int error = 0;
 
		if(request.getParameter("title")!=null) title = request.getParameter("title");
		else error = 1;
		if(request.getParameter("formcategory")!=null) formcategory = request.getParameter("formcategory");
		else error = 1;
		if(request.getParameter("body")!=null) body = request.getParameter("body");
		else error = 1;
 
		if(error==1)
		{
			response.sendRedirect("index.jsp?error=Please input information in all fields");
		}
		else
		{
			String username = (String) session.getAttribute("username");
			try
			{
				String query = "INSERT // INTO News(title,body,owner,publishing_date,publishing_time,category) VALUES('"+title+"','"+body+"','"+username+"',NOW(),NOW(),'"+formcategory+"')";
				// remove // between INSERT and INTO in above line
				statement.executeUpdate(query);				
			}
			catch (Exception e)
			{
				%><%=e%><%
			}
			response.sendRedirect("index.jsp?msg=News added to the system.");
		}
	}
	else response.sendRedirect("index.jsp?error=You must be logged in to access this feature.");
%>

Lines 20 and 54 in the above code check if the user trying to add a news to the database is logged in, as only logged in users are allowed to add items to the database. Lines 22 to 32 are used to initialize the variables which retain information users have inserted into the form fields on the previous page. On lines 34/36 errors are checked, and if any errors are found the users are redirected to the homepage of the web app and error messages are displayed. The code on line 40 gets the username of the person trying to add a news to the database as each news has an author and we need to know the info before inserting new items in the database. The try catch block between lines 41 and 50 is used to add the news to the database, or if any exceptions occur, catch and display them. If everything goes as planned the code on line 51 redirects users to the homepage and triggers a success message.

That's all it takes to nicely add information to a database using Java Server Pages. If you enjoyed the article, you can stay updated to new content via our RSS feed or by email.

Published on Wednesday, August 25th, 2010 at 12:00 pm in tutorials.

About Bogdan Pop

Bogdan Pop is a young Romanian entrepreneur who runs WebRaptor. He is a web developer with awesome design skills, who enjoys writing about everyday's work and usability. He relaxes by taking photos every once in a while and by mixing french electronic music. Connect with him via Twitter.
 

There are no comments. You can be the first to post one.





Save time next time! You won't have to fill out all these fields again. Register in just a few clicks and then login.


If you do not have a username, you can register in just a few clicks.