Vous êtes sur la page 1sur 21

CoreJava

Servlets&Jsp
JPA2.0
MongoDB
OO&D
AboutMe
ContactMe

JAVA EE, SERVLETS AND JSP

MVC architecture with servlets and jsp


by Prasad KharkarAugust 11, 2013111 Comments

Bio

LatestPosts

Prasad Kharkar
PrasadKharkarisajavaenthusiastandalwayskeentoexploreandlearnjavatechnologies.
HeisSCJP,OCPWCD,OCEJPADandaspirestobejavaarchitect.

InthistutorialwearegoingtolearnhowtocreateasimpleMVCapplicationusingservletsandjsp.
MVCi.e.ModelViewControllerisapatternhelpfulseparationofconcerns.
ModelrepresentsaPOJOobjectthatcarriesdata.
Viewisthelayerinwhichthedataispresentedinvisualformat.
Controlleristhecomponentwhichisresponsibleforcommunicationbetweenmodelandview.
Auseralwaysseestheviewandcommunicateswiththecontroller.Wewillunderstandthisusingasamplelogin
applicationwhichwilldisplayawelcomeusernamemessageandiftheloginfails,itwillredirecttoanerrorpage.
Hereiswhatwearegoingtocreate.
login.jsp:thiswillinputusernameandpassword
success.jsp:Ifloginissuccessful,thenthispageisdisplayed
error.jsp:Ifloginisnotsuccessfulthenthispageisdisplayed.
LoginController.java:Thisiscontrollerpartoftheapplicationwhichcommunicateswithmodel
Authenticator.java:Hasbusinesslogicforauthentication
User.java:Storesusernameandpasswordfortheuser.
Requirements:
EclipseIDE
Apachetomcatserver
JSTLjar
CreateanewDynamicwebprojectineclipsebyclickingFile>New>DynamicWebProject.Fill
thedetailsi.e.projectname,theserver.EnteryourprojectnameasMVCDemo.Youwillgetthe
followingdirectorystructurefortheproject.

InitialProjectStructure

Createsuccess.jsp,error.jspandlogin.jspandLoginControllerservlet,Authenticatorclass,User
classinthepackagesasshownintheimages.Putthejstl.jarinWEBINF/libfolder.

Now
thatwe
FileStructure

PackageStructure

have
file
structure,putthiscodeincorrespondingfiles.

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

package mvcdemo.controllers;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvcdemo.model.Authenticator;
import mvcdemo.model.User;

import sun.text.normalizer.ICUBinary.Authenticate;

public class LoginController extends HttpServlet {


private static final long serialVersionUID = 1L;

public LoginController() {
super();
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException {

String username = request.getParameter("username");


String password = request.getParameter("password");
RequestDispatcher rd = null;

Authenticator authenticator = new Authenticator();


String result = authenticator.authenticate(username, password);
if (result.equals("success")) {
rd = request.getRequestDispatcher("/success.jsp");
User user = new User(username, password);
request.setAttribute("user", user);
} else {
rd = request.getRequestDispatcher("/error.jsp");
}
rd.forward(request, response);
}

Authenticator.java
1
2
3
4
5
6
7
8
9
10
11
12
13

package mvcdemo.model;

public class Authenticator {

public String authenticate(String username, String password) {


if (("prasad".equalsIgnoreCase(username))
&& ("password".equals(password))) {
return "success";
} else {
return "failure";
}
}
}

User.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package mvcdemo.model;

public class User {

private String username;


private String password;

public User(String username, String password){


this.username = username;
this.password = password;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

20
21
22
23
24
25
26
27
28
29

public String getPassword() {


return password;
}
public void setPassword(String password) {
this.password = password;
}

error.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

Login failed, please try again.

</body>
</html>

login.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="LoginController" method="post">
Enter username : <input type="text" name="username"> <BR>
Enter password : <input type="password" name="password"> <BR>
<input type="submit" />
</form>
</body>
</html>

success.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<title>Insert title here</title>
</head>
<body>

Welcome ${requestScope['user'].username}.

</body>
</html>

andtheweb.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javae
e" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.c
<display-name>MVCDemo</display-name>
om/xml/ns/javaee

<servlet>
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"
<description></description>
<display-name>LoginController</display-name>
<servlet-name>LoginController</servlet-name>
<servlet-class>mvcdemo.controllers.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/LoginController</url-pattern>
</servlet-mapping>
</web-app>

Wearedonewiththecode.Letustryandrunit.
Startyourtomcatserverandhiturlhttp://localhost:8080/MVCDemo/login.jsp.
Youshouldbeabletoviewthispage.

Enterusernameasprasadandpasswordaspassword.YouwillseethemessageWelcomeprasad.

Letusunderstandwhathappensunderthehoodwiththehelpofdiagram.

1. First,uservisitslogin.jsppageandfillsoutdataandsubmitsform.
2. Thiscauses LoginController tobeinvokedbecauseof form action="LoginController" .
3. In LoginController ,followingcodecausesthemodeltobeinvokedandsetthe User properties.
1 Authenticator authenticator = new Authenticator();
2 String result = authenticator.authenticate(username, password);

and User user = new User(username, password); .


4. rd.forward(request, response); causestheservlettoforwardtojsppage.
success.jsppagedisplaystheusernamewithexpressionlanguage Welcome
${requestScope['user'].username}.

Notableadvantagesofmvcpatternare:
Thisseparatepresentationlayerfrombusinesslayer.
Thecontrollerperformsactionofinvokingthemodelandsendingdatatoview.
Modelisnotevenawarethatitisusedbysomewebapplicationordesktopapplication.Authenticator
classcanbeusedbydesktopapplicationsalso.Thusseparationhelpsinreusability.
HopethishelpsinunderstandinghowtocreateMVCapplicationusingservletsandjsp.

Related Posts

Servletlisteners:
ServletContextList

Servletlisteners:
ServletRequestLis

Servletlisteners:
HttpSessionListen

enerexample.

tener

erexample

RequestDispatch
erforwardmethod

RequestDispatch
erincludemethod

Tags: architecture eclipse javaee mvc request response servlets tomcat

formattingdatesusingSimpleDateFormat

Passbyvalueorpassbyreference?

111 comments for MVC architecture with servlets and jsp


SudhirKumar
November21,2013at3:16am

superb..
Reply

PrasadKharkar

November21,2013at10:34am

ThankyouSudhir.
Reply

sruthi
May14,2015at10:14pm

Hi,Thankyouverymuchfortheinformation.IntheaboveExampleintheAuthenticat
classwehavepasswordandusername.Howtoauthenticateiftheyarestoredindatabasein
theaboveexample.Thankyouverymuch.
Reply

PrasadKharkar
May15,2015at9:59am

Atbeginnerlevel,youcaneithercreatedatabaseconnectionfromwebapplication
andreadusernameandpasswordfromservletandthencheckforequality.Oryoucan
goforabetterwayofusingJavaAuthenticationandAuthorizationServicewhichcanbe
usedwithtomcat,jbossorwildfly.Pleasefollowtheselinks
jaaswithmysqlandjboss
jaaswithmysqlandtomcat
Reply

SudhirKumar
November21,2013at3:18am

canyouexplainmoreaboutStruts,Hibernate,SpringwithMVCandFrontControlerDesign
Pattern.
Reply

PrasadKharkar
November21,2013at10:50am

YesSudhir,tutorialsaboutthemwilldefinitelycomesoon.Iamworkingonthem.Thankyou
forreadingandshowinginterest.
Reply

SudhirKumar
November22,2013at10:25pm

cantellabout,howtopracticebestbecausegivinganswerininterviewlikerealworldisdifficult
anddevelopinganyapplicationfromscratchisdifficultformeathome.actuallyiwanttouseall
java/j2ee,struts,hibernate,spring,DB(somepartofXML&WebServicealso)asHomework.socanyou
giveanyideaor,canyougiveQuestionfordevelopingsmallapplicationwhichgivesrealworld
meaningtobecomeexp.
Reply

SudhirKumar
November22,2013at11:59pm

canyoutellabout,howtopracticebestbecausegivinganswerininterviewlikerealworldis
difficult.

Reply

PrasadKharkar
November23,2013at1:03am

IwouldrecommendyoutotakeupasampleprojectandimplementitusingMVC
architecturesothatyouwillgettoknowthedifficultiesfacedduringdevelopment.Forexample,
createasimpleuserregistrationforminwhichfieldsareenteredonaJSP,accessthemina
servletandagaindisplaythelistofallregisteredusersonaseparateJSPpage.UseMVC
architectureinit.
Reply

suhail
March24,2014at1:52pm

goodonethankusomuch.
Reply

sundyp
April23,2014at12:30pm

veryhelpful..findingforthisforalong..expectingmoretopicsfromu..
Reply

PrasadKharkar
April23,2014at1:11pm

ThankyouSandypforgoodfeedback

Iwillfulfilyourexpectations
Reply

MDNISHADHUSSAIN
June5,2014at5:59pm

hellosir,
ihavestartedlearningjspandservletandatthesametimedoingprojectinboththetechnologies
Sowillyoukindlytellmewhatwouldbethebeststartformeandwhatarethemaintopicsinboth
whichwillhelpmeinmakingproject..
Reply

PrasadKharkar
June5,2014at11:59pm

HiNishad,nowthatyouhavelearnedMVCarchitecturewell,learnaboutservlets,listeners
andotherwebcomponents.IwouldrecommendyoutouseJSFifitispossibleasitisevent
basedframework.
Reply

MDNISHADHUSSAIN
June7,2014at11:58am

thankssirbutihavenoideaaboutjsfasofnowsowillutellmehow.?
Reply

PrasadKharkar
June7,2014at9:41pm

Rightnowifyoudonthaveideaaboutjsf,itsgoodtostartwithservletsandJSP
itself.JSFpartcanbedonelateronceyouveunderstoodservletsandjsp
Reply

MDNISHADHUSSAIN
June10,2014at9:22am

okthankssir.

PrasadKharkar
June10,2014at2:46pm

Happylearning

Nishad
June11,2014at6:24pm

Hi,
siriamgettingabitconfusedregardingjsplikeiteventuallychangeintoservlet
thenwhatistheneedoftakingjsp..ifiwanttomakeadesignformforuserentry
likename,sexaddressinjspandmoreonthatusingjsponlysocanimakeitor
not..
plzzexplain

MDNISHADHUSSAIN
June11,2014at6:28pm

andifiwanttorunanappletcodeineclipsethenisitpossibletorunor
not.
ifimakeauiformusingappletthenitwouldbeagoodidea..????

sravani
June5,2014at9:41pm

ExcellentMr.Prasad,ihavelookingforthiskindofexplanationsofar.canyoupleasepostsome
moreexamples
Reply

PrasadKharkar
June5,2014at11:54pm

Sravani,thankyouforpositivefeedback:).Iamconstantlyaddingsomenicearticles.You
canliketheJavaGeekpageonfacebookforregularupdates.Iwouldalsoliketoreceivea
feedbackfromyouforanyimprovementsandsuggestions.
Reply

Kishan
June6,2014at1:45am

ThanQsirreallyitzusefultomeasamdoingaprojectnowinmytrainingperiodam
searchingthesekindofneatexplainationthanqonceagainandiwantyoutogivemoretutorialson
howtoconnectdbforupdateprofileandihave2questions1)amusingNetBeansIDEsoany
differencebetweeneclipseamihvtodoanymodificationfromurtutorial?
2)howtogetphotoasainputforupdateprofilepageThanQinadvance
Reply

PrasadKharkar
June6,2014at10:36am

1.Thoughyouareusingnetbeans,itmayhaveadifferentdirectorystructure,soinsteadof
webcontentdirectory,itcanhaveotherone.Therulesforawebapplicationdonotchange.You
justneedtocreateadynamicwebprojectinnetbeansandfollowtheprocessgiveninthistutorial
2.Youwillhavetousefileuploadfunctionalityforuploadingphotoandwhiledisplaying,I
recommendyousimplystoretheuploadedphotoonharddriveandputthelocationofphotoin
database.Whiledisplayingphotoforprofile,youcanpickphotolocationfromdatabaseand
displayonwebpage.
Iwillcertainlywritemoretutorialsasperyoursuggestion

Thankyouforreadingapositive

feedback.Happylearning.
Reply

MDNISHADHUSSAIN
June11,2014at6:35pm

sir,itwouldbeagreatfavourifyouhelpmeinmyproject..ifyouallowmetheniwillkeep
postingthequeriesandyouguidemehowtodoit.myprojecttitleisStudentMangement
SYstemitsaliveproject..wanttousejspandservlet.plzkindlyguidemestepbystep..
thanksandregards,
Nishad
Reply

PrasadKharkar
June11,2014at11:23pm

HiNishad,IamsurethislinkwilltellyouwhyyoushouldJSP.Youcanalwayspostqueries
aboutyourapplicationandIwilltrymybesttohelpyouout.
Reply

MDNISHADHUSSAIN
June12,2014at12:32am

okthankssir.
Reply

MDNISHADHUSSAIN
June25,2014at8:45am

ComparisonofMVCimplementationbetweenJ2EEandASP.NET,Whoisthebest?
whatisthedifferencebetweenthetwo.?
Reply

randy
July24,2014at3:35pm

HowcanIconnectaalreadycompletedJSPwithaOracledatabaseintoaMVC?
Reply

PrasadKharkar
July25,2014at9:25am

Youcancreateaclasswhichreturnsthedatabaseconnectionandusethatobjectinto
businesslogici.e.model.
Reply

zchumager
July26,2014at10:50pm

Greattutorial,justoneerror.Onthejspfiletheline
Welcome${requestScope[user].username}
shouldbe
Welcome${requestScope[user].getUsername()}
becauseyourattributeisprivateandyouhaveagetterforit
Reply

MADHU
July31,2014at11:32pm

Prasadbroawesomeexplanatn.Tqsomuchandcanupleaseupdatesomemoreexampleon
eachtopicofservletsandjspsothatwouldbebetterforbeginners.
Reply

PrasadKharkar
August1,2014at10:35am

HiMadhu,thankyouforgoodfeedback.Youcanfindgoodtutorialsforservletsandjsp
rightinthemenu.Here
Reply

MADHU
August7,2014at11:36pm

Thankyoubroandcorejavaconceptswhatyouhavegivenisthatenoughorwe
needtolearnmore?BecauseiwantputoneyearvirtualexperienceonJavasoisthe
conceptsyouexplainedcorejavaandj2eeissufficient?
Reply

PrasadKharkar
August8,2014at7:45am

Knowledgeisneverenough

butmyarticleswilldefinitelybehelpful.
Reply

vamsi
August14,2014at7:48pm

Theexplanationwasexcellent.IamnowabletounderstandMVCarchitectureverywell.Could
youpleasepostsomeexamplesonCRUDoperationsinvolvingMVCarchitecture.Thatisonearea
thatIwanttoimprove.
Reply

DebaprioBanik
August22,2014at5:34pm

Nicelyput.Canyoupleaseexplainabitmoredetailonhowthelogin.jspgetsloadedfirst?
Reply

PrasadKharkar
August22,2014at7:18pm

Ihavedirectlyvisitedtheurlforlogin.jsp
Reply

manishaagarwal
September6,2014at2:40pm

pleaseexplaintheuseofjstl.jar
Reply

SnigdhodebMitra
September24,2014at11:54pm

Sir,
IamafresherbtechIT.IhavestartedlearningJ2EEforthepastfewweeks.Iamfacingsome
probleminstructuringaMCVpatterninjava.Itwouldbeveryhelpfulifyoucanpleaseguidemein
thisandifcansendmeasmallexampleofthebasicfunctionalitiesofINSERT,UPDATE,andDELETE
featuresusingMysqlinaMVCformat.Iwouldmeeagerlywaitingforyoureplyandwouldbevery
thankfulifyoucanmakesometimeformyourbusyscheduleandhelpme
Reply

PrasadKharkar
September25,2014at8:32am

HiSnigdhodeb,Pleaseletmeknowtheproblemsyouarefacingwhilecreatingapplication
usingmvcpattern.Iwilldefintielyhelpyouwithit.
Reply

krishna
October16,2014at8:55pm

Niceworkprasad,Simpebutperfect
Reply

PrasadKharkar
October17,2014at11:42am

HiKrishna,thankyouforreading.Iamgladitwasusefulforyou.
Reply

Pingback:CoffeeAdvisorwebapplication|Nigoutsi'sLocalSite

Pingback:CoffeeAdvisorwebapplication|AM0335

Flora
October27,2014at9:38pm

Thanku.thearticleisveryuseful.AfterreadingsomanyarticlesonotherwebsiteIfoundthis
oneneat,clearandtothepoint.IamfromnoncsbackgroundandnowworkinginITcompanyand
undergoingtraininginjava.Ithinkthiswillhelpmetoclearmydoubtsandmakemelovecoding
Reply

PrasadKharkar
October28,2014at8:57am

HiFlora,Iamgladthiswasusefulforyou.Happylearning
Reply

Akila
October28,2014at11:59am

ThankYouVerymuchIgotaclearideaonMVCmodel.
Itwasveryusefulandeasytounderstand..KeepGoing..
Reply

Sandeep
November5,2014at1:30pm

HiPrasaddoyouhaveanyotherexampleinwhichaformhasmanyinputvaluesandPOJO
modelinsuchcase.
Reply

PrasadKharkar
November5,2014at11:05pm

Thisformalreadycontainstwovaluesinit.Couldyoupleasetellmewhatexactlyyouwant
toaskwhenyousayithasmanyinputvaluesandPOJOmodelinsuchcase?
Reply

Santosh
November10,2014at11:56am

greatarticlesirthankyousomuch
Reply

Nageswar
November28,2014at12:22pm

Thankuprasad,igotclearideaonmvc..pleasepostmoretutorials
Reply

PrasadKharkar
November29,2014at11:47pm

Iamgladitwasusefulforyou.Iwillsurelykeepwriting

Happylearning
Reply

abhinayjain
November29,2014at12:01pm

verysimpleandeasytounderstand..
Itsagoodexample.ThankyouPrasad.
PrasadihaveaquarycorrespondingtorequestDispatcher
canuexplainmeindetail
Reply

PrasadKharkar
November29,2014at11:46pm

Iamgladitwasusefulforyou

Whatisyourquery?
Reply

Ruthvik
January5,2015at8:30pm

hiprasad,
itsagoodexamplebutifwanttoconnecttoadatabasehowshoulditbedone?canuhelpmewitha
examplewherethequeriesshouldbewritten?
Reply

PrasadKharkar
January9,2015at5:13pm

HiRuthvik,Ididntexactlygetwhatyouwantedtosay.Couldyoupleaseelaborate?
Reply

anusha
January10,2015at11:19am

Hi,
Thetutorialisverygood.ItriedthesamebutmgettingerrorinmyLoginController.java.
Theerrorishere.ItissayinfCannotinstantiatethetypeauthenticatoratthefirstlineandThe
methodauthenticate(Stirng,String)isundefinedforthetypeAuthenticator.
Authenticatorauthenticator=newAuthenticator()
Stringresult=authenticator.authenticate(username,password)
pleasecheckandgivemethereplyasap.

MyIDE:Eclipseluna
JDK7
Tomcat8
Reply

PrasadKharkar
January10,2015at5:12pm

ItseemsyourcontainerisnotabletorecognizeAuthenticatorclass.Couldyoupleasepost
fullstacktrace?
Reply

akash
June2,2015at10:18pm

Hi,
Ithinkyouhaveimportedwrongclassfile.
Pleaseimportmvcdemo.model.Authenticator
Reply

Priya
January18,2015at7:13pm

Superb
Reply

RAVI
January22,2015at9:18pm

verygoodtutorial..superbprasadkeepitup..:
Reply

James
February9,2015at2:27am

HiPrasad,greatdocumentyouhavewrittenhere,keepupthegoodwork.Ihavetriedallthe
mentionedsteps,butwhenihittheURLhttp://localhost:8080/MVCDemo/login.jspiamgettinga
requestedresourceisnotavailable,pagenotfounderror.Canyoupleasehelpmeouthere.Many
thanks.
Reply

PrasadKharkar
February9,2015at9:40pm

pleasecheckwhetheryourserverisupbyvisitinglocahost:8080.
Reply

jugal
February11,2015at9:40am

Hellosircurrentlyiworkingontheliveprojectandurtutorialisveryusefultome
butcanupleasehelpmeinspringmvcgivemesomeexaplesandwebsitestolearnonline

thankyou
Reply

kavitha.N
February11,2015at10:45am

thankssirfortheinformation,itsverymuchhelpfultome
iamfresheridnthaveanyexperienceinjava,butiwanttostartupprojectsfrmhomeusingjava
technology,soplzcanusuggestmethethingswatandallihavetolearntodevelopprojectinjava
Reply

PrasadKharkar
February12,2015at5:32pm

HiKavitha,Iamgladitwasusefulforyou.Firstdecidewhatkindofprojectyouwanttodo,
thenwillbeabletotell.
Reply

samin
March3,2015at12:10am

hello,plstellwhatistheadvantagestomakejspprogrambymvcstrutureratherthensimple..
Reply

PrasadKharkar
March3,2015at11:33am

HiSamin,Ithinkthislinkshouldansweryourquestion.
Reply

Pingback:MVCarchitecturewithservletsandjsptheJav...

Chris
March9,2015at4:23am

HelloPrasad,thankyouforthistutorial!Canyoupleasediscusshowpackagingworksin
servlets?IalwaysseemtogeterrorswhenIcreatepackagesformyservlets,andthentrytoimport
otherclassesandusetheirfunctions.
Thankyou!
Reply

PrasadKharkar
March9,2015at4:18pm

HiChris,thereisnodifferenceinservletpackagesandnormalpackage.Couldyouplease
posttheerrorsyouaregetting?Illtrytoresolvethem
Reply

azzmi
March14,2015at3:10pm

verygoodarticle..regards
Reply

ShakourGhafarzoy
March17,2015at4:51pm

.terrificMVCexamplethankuSir
Reply

sachin
March20,2015at9:48pm

owsm.
Reply

AshishMahadik
March25,2015at10:54am

Hi,
Canyoutellmeifwewanttoprinttableinourjsppageandtablevaluecomefromdatabaseandwe
usemvcarchitecturethenitiscorrecttogetallvaluesinjsppagebydirectlywritequeryinthatjsp
pageoruseservlettogetallvalues?
Reply

PrasadKharkar
March25,2015at11:51am

HiAshish,jspsaremeantfordisplayingpurposeonly.aJSPdeveloperneednothave
knowledgeofsqlqueries.Writingsqlorjavacodeinjspwouldbreakthemvcpattern.Itisnot
advisabletowritelogicinjsp.Youshoulduseservletorfurtherlayerstocallvaluesfrom
database.
Reply

AshishMahadik
March25,2015at2:49pm

ThanksPrasad,
itcanclearallmyconceptaboutmvcpattern
Reply

PrasadKharkar
March26,2015at10:56am

Imgladyoufoundituseful.HappylearningAshish
Reply

kapil
March28,2015at11:46am

sir,icreatedthatarchitecturbuthowtorunit..
plzspecifyhere.
Reply

PrasadKharkar
March28,2015at8:44pm

HiKapil,Ivealreadyexplainedhowtorunit.Whatistheproblemyouarefacing?Pleaselet
meknow.
Reply

ravi
April1,2015at1:35pm

superbtutorial.showmetodatabaseauthenticationofservletmvc
Reply

aishwarya
April4,2015at12:07pm

sircanuexplainmeifidontuseeclipsehowcaniproceedinnotepad
Reply

PrasadKharkar
April4,2015at3:47pm

youwillhavetocompilealljavafiles,servlet,jspseparatelywithrespectivecommands
(Needsomegooglingforit).Afterthatyouneedtocreatewarfileandthendeployundertomcat
Reply

veena
April9,2015at1:30am

Hi,
IamtryingtoruntheloginJsp,butIamfacing404erroralsoIamgettingerrorfortaglibin
success.jsp.
Pleasehelp.
Reply

PrasadKharkar
April9,2015at9:42am

pleaseprovidethestacktrace.Haveyoufollowedallthestepsmentionedinthearticle?
Reply

Mourad
April14,2015at4:57pm

Thanksforthistutorial.Ihaveaproblem,ifwehavetwoclassesforexample,UserandAdmin,
AdminextendsUser,howcanwerespectMVCarchitecture?Imeaninthatcasewewillhavetwo
beans,twoclassesforDAOaccess?thanksforhelping
Reply

Ashish

April18,2015at8:01pm

HelloPrasad,
IamconfusinginMVCpatternthat
1.InprojectorMVCpatternhowmanyservletwecanuseinoneprojectisitrecommendthatonlyone
servletisinallprojectormultiplewecanuse?whatwouldbeprefer.
2.whatdifferencebetweendatatransferobjectclassanddataaccessobject(DAO)classusedin
application.
3.howweshouldhideDAOclassfromdirectaccessinMVCpattern.
Providestandardindustrialcodingproceduretome.
Reply

Juan
April25,2015at10:29pm

Woulditbepossibletodownloadtheproject?Itwouldhelp
Reply

Nahar
May23,2015at8:01am

Thanksforthetutorialprasad,butihaveaproblemwhichiswhenicompile3ofthatjavafile,i
gotthiserrorfromLoginController.java,packagesun.text.normalizer.ICUBinarydoesnotexistI
dontknowmuchaboutthatpackagedeclarationCanuhelpme
Reply

Muthu
May26,2015at5:37pm

thanksforyourexampleitisverynice..ihaveonequestionregardingabove
examplewhetherwecanuseforminthelayerbetweenjspandservletcontroller?
UserFormuserForm
Stringusername=userForm.getUsername()
likethisone..
Reply

PrasadKharkar
May28,2015at9:23am

TheFormyouaretalkingaboutisavailableinstruts.
Reply

Utsav
June9,2015at12:51pm

Simplyawesomeexample.HatsofftoyouPrasadji
Reply

Hakeem
June9,2015at8:16pm

ThankyouMr.Prasad.YourexplanationonMVCwassimpleyetverydetailedandhelpful.
IamcurrentlydevelopanapplicationfortheorganizationIworkfor,IamusingJAVAandIhavea
couplequesitonsthatIhopeyoucananswer.

WithintheaformentionedapplicationIwanttoimplementServerSidevalidation,wherewouldyouput
thesaidblockofcode,intheModelortheControllerclass?
Usingyouraboveexample,letsassumethatyouwantedtoensurethattheuserenteredbotha
passwordandusername,wouldyouputthevalidaitonblockintheLoginControllerclassorthe
Authenticatorclass?
Secondly,whatisthebestwaytoimplementUserPrivillegesandPermissionsinJAVAusingtheMVC
Designpattern?DoIimplementanInterceptingfilterandplacethelogicthereordoIdistrubutethe
logicbetweentheviewandmodel?
Anyadvicewouldbegreatlyappreciated.Thankyoumuchinadvance.
KindRegards,
Hakeem
Reply

PrasadKharkar
June9,2015at8:21pm

HiHakeem,Iamgladyoufoundituseful.TobehonestthereisnoIDEALwayofdoing
things.ThistutorialonlyexplainshowmvcarchitecturecanbedoneusingservletsandJSP.For
authenticationandauthorization,IbelieveyoushoulduseJavaAuthenticationandAuthorization
Service.Youcanfindsometutorialsonmyblogitself.Iamsuretheywillhelp.
Reply

Hakeem
June10,2015at2:42am

Wow,Prasad.Thankyousomuchforyourquickresponse.Iamgoingtolookatyour
tutorialsnow.Also,doyouknowofanytutorialssiteIcanreaduponJavaAuthenticationand
Autorizaiton?
Reply

prakhar
June25,2015at4:42pm

HowwecanhandlemultiplerequestusingsingleController(Servlet)likewedousingfilterin
struts?pleaseexplainwithanexampleifpossible.
Reply

PrasadKharkar
June26,2015at9:12am

TherearesomeshortcomingswithasimpleMVCarchitectureinservletsandjspandthatis
whystrutsprovidesthatfunctionality
Reply

Saha
July6,2015at5:31pm

HowtostartlearningJSP,Servlet?
IgottraininginJ2EEtech,butitwentovermyhead.Cz,Iamaslowlearner!
Now,Iamtryingtolearnitmyself.Pleasesuggestme.
Andalso,Igotseverelyconfusedbecoz,theytaughtMVC,DAOwithoutexplainingwell.
Tellmeaboutthatalso.
Reply

Anish
July7,2015at10:53pm

Hello!Sir.MyselfAnish.Iwanttoknowhowtoretrieveallrecordfromatableonaviewpage
suchasjsp.Afterretrievedwemaketheallthefirstrowsprovidealinklikeaswhenweaccessthe
irctcrailsitetherewecheckthetrainandaftercheckingifvalidtrainallinfothenitrenderthealltrain
details.whenweclickonthetrainnobylinkthenitmovedusbookpagethatssoon..pleasetellme
howtoimplementinmyprojectthisproceedure..ok
Reply

Aditi
July13,2015at1:07pm

HiPrasad,
Thiswasveryhelpful.Thanksabunch!
Reply

Kannan
July13,2015at3:52pm

HelloPrasad,
Canyoutellmewhichisthebusinesslogicinthisexample?
Reply

PrasadKharkar
July14,2015at8:48am

HiKannan,thisisjustasamplemvcarchitecturewhichelaboratesdifferentlayers.
Businesslogictermreferstothecodewhichfulfillsfunctionality.Althoughyoucanconsiderthe
modellayerasbusinesslayerhere.
Reply

logeshkumar
October28,2015at2:45pm

sirineedasolutionforcreatingwebappinframeworkspring,hibernate,jsf
Reply

PrasadKharkar
October29,2015at10:50am

HiLogesh,
Pleasetellmetheproblemyouarefacingwhilebuildingtheapp,Iwilltrymybesttohelp
Reply

srikanthaddani
July15,2015at4:31pm

verygoodarchitecture..
Reply

Suhas
August6,2015at12:23pm

Thanksforgoodexplanation
Reply

Ajit
August7,2015at11:34am

Hellosir,
iamfresher,idontknowactualworkingofmvc
canutellmehowtoimplementservlet,jspandhowtogettheconnection
Reply

subodh
August10,2015at12:47pm

sir..Mayiwritemultiplemethodinoneservlet..
ifyesthenhowcanwecallfromhtmlthatwhichparticularoneisgettingtocall
Reply

yanyan
August11,2015at9:22am

wouldyouexplainthewaythatIdonotneedtousethebuildpathtohaveservlet.jarformy
program.
Reply

GaoLJ
October11,2015at7:19pm

Thanksforyoursharing!IamlearningwebservicetobuildaBigdataecosystembetweenmy
Hadoopsystemandapplication.YourMVCJSPtutorialhelpsme!
Reply

Leave a Reply
Youremailaddresswillnotbepublished.Requiredfieldsaremarked*
Name*
Email*
Website
Comment

PostComment

Copyright2015theJavaGeek.AllRightsReserved.

TheJavaGeek
LikePage

898likes

QuickLinks
CoreJava
Servlets&Jsp
JPA2.0
MongoDB
OO&D
AboutMe
ContactMe
2015thejavageek.comAllrightsreserved.
PrivacyPolicy

Vous aimerez peut-être aussi